1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <android/binder_auto_utils.h>
18 #include <android/binder_ibinder_jni.h>
19 #include <android/binder_manager.h>
20 #include <jni.h>
21 #include <log/log.h>
22 
23 extern "C" JNIEXPORT jobject JNICALL
Java_example_vib_MyActivity_gimme__Ljava_lang_String_2(JNIEnv * env,jclass,jstring str)24 Java_example_vib_MyActivity_gimme__Ljava_lang_String_2(JNIEnv* env, jclass /**/, jstring str) {
25     ALOGI("%s", __func__);
26 
27     // Best practice is probably libnativehelper ScopedUtfChars or
28     // libbase ScopeGuard (for platform code), but this is with minimal
29     // dependencies.
30     const char* name = env->GetStringUTFChars(str, nullptr);
31 
32     ALOGI("example vib gimme %s", name);
33 
34     jobject jbinder = nullptr;
35 
36     // Java does not have vendor variants. It's only safe to pass a service when
37     // 'vendor: true' if it is @VintfStability.
38     if (AServiceManager_isDeclared(name)) {
39         ndk::SpAIBinder binder = ndk::SpAIBinder(AServiceManager_waitForService(name));
40         jbinder = AIBinder_toJavaBinder(env, binder.get());
41     } else {
42         ALOGI("not declared");
43     }
44 
45     env->ReleaseStringUTFChars(str, name);
46 
47     return jbinder;
48 }
49