아래와 같이 Android studio에서
1, AIDL 인터페이스 작성
2, Client 코드에서 Native Service를 ServiceManager로 가져와 Service의 함수들을 이용
모두 시도해본 것은 아니나 아래의 경우의 수가
모두 AIDL or Binder를 통하여 IPC가 가능
Native Service <-> Java Client
Native Service <-> Native Client
Java Service <-> Java Client
Java Service <-> Native Client
#AIDL
package android.binder.example; /** * AIDL file for Binder API generating * */ interface IDemoAPI{ String getName(); String getFullName(String part); int sum(int a,int b); }
#JAVA Client
package com.technicolor.clienttest; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.binder.example.IDemoAPI; import java.lang.reflect.Method; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private IDemoAPI mService; private static final String TAG = "HelloActivity IDemoAPI"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getDemoAPIService(); try{ Log.d(TAG, "1+2="+Integer.toString(mService.sum(1,2))); Log.d(TAG, "Name="+mService.getName()); Log.d(TAG, "FullName="+mService.getFullName("AAABBBCCC")); }catch(Exception e){ Log.d(TAG,e.toString()); } } static final String SERVICE_NAME="android.binder.example"; /* * Get binder service */ private void getDemoAPIService() { IBinder binder=null; Log.d(TAG,"getDemoAPIService"); try{ //android.os.ServiceManager is hide class, we can not invoke them from SDK. So we have to use reflect to invoke these classes. Object object = new Object(); Method getService = Class.forName("android.os.ServiceManager").getMethod("getService", String.class); Object obj = getService.invoke(object, new Object[]{new String(SERVICE_NAME)}); binder = (IBinder)obj; }catch(Exception e){ Log.d(TAG, e.toString()); } if(binder != null){ mService = IDemoAPI.Stub.asInterface(binder); Log.d(TAG, "Find binder"); } else Log.d(TAG,"Service is null."); } }
#Native Service
#include "server.h" int main(int argc, char *argv[]) { sp proc(ProcessState::self()); //get service manager sp sm = defaultServiceManager(); //Register a service with the SERVICE_NAME sm->addService(String16(SERVICE_NAME),new demo_api::DemoAPI()); ALOGE("%s service is starting.....",SERVICE_NAME); //Start Service ProcessState::self()->startThreadPool(); //Loop for waiting for request IPCThreadState::self()->joinThreadPool(); return 0; }
출처:
1, <https://stackoverflow.com/questions/42002869/is-it-possible-to-bind-to-a-java-service-from-a-native-c-client-and-transact>
2, https://github.com/qianjigui/android_system_service_example
'android' 카테고리의 다른 글
chcon 예제 (change context) (0) | 2021.01.05 |
---|---|
Android X란? (0) | 2020.07.23 |
ForegroundService test (0) | 2020.07.08 |
wake lock example (0) | 2020.07.03 |
Xlint error in Android studio (0) | 2020.04.24 |