1.定義AIDL接口:需要保證包名一樣
在Android Studio中 src目錄上右鍵創建一個AIDL文件 並命名,完成後會再main下自動生成一個aidl目錄,該目錄的包名和java下的包名是一致的。
2.make Project 然後生成接口
3,哪裏需要用拷貝接口過來
通過AIdl,bind啓動遠程服務
private boolean bindStepService() { Activity activity = getReference(); if (activity != null) { try { Intent service = new Intent(activity, ModuleHub.moduleSport().getStepService()); return activity.bindService(service, mStepConnect, Context.BIND_IMPORTANT); } catch (Exception e) { return false; } } return false; }
和服務綁定之後,設置監聽到服務裏面,服務有數據變化,通知過來
private StepCountListener mStepCountListener = new StepCountListener(this); private IServiceAutoStepInterface mServiceAutoStepInterface; private ServiceConnection mStepConnect = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mServiceAutoStepInterface = IServiceAutoStepInterface.Stub.asInterface(service); try { mServiceAutoStepInterface.registerListener(mStepCountListener); } catch (Throwable e) { } } @Override public void onServiceDisconnected(ComponentName name) { try { //mServiceAutoStepInterface android.os.DeadObjectException if (!AndroidUtils.haveRunProcess(ShadowApp.context()) && mServiceAutoStepInterface != null) mServiceAutoStepInterface.unRegisterListener(mStepCountListener); mStepCountListener = null; } catch (Throwable e) { e.printStackTrace(); } mServiceAutoStepInterface = null; } };
Service裏面註冊監聽的過程:
private List<IStepCountListener> mArrayList = Collections.synchronizedList(new ArrayList<IStepCountListener>()); private IBinder mBinder = new IServiceAutoStepInterface.Stub() { @Override public void registerListener(IStepCountListener listener) throws android.os.RemoteException { mArrayList.clear(); if (null != listener) { if (-1 == getStepCountListenerIndex(listener)) { mArrayList.add(listener); YDLog.logWannig(kTag, "register listener ,list not found"); } YDLog.logInfo(kTag, "register listener ,cur size :" + mArrayList.size()); } else { throw new android.os.RemoteException(); } } @Override public void unRegisterListener(IStepCountListener listener) throws android.os.RemoteException { int index = getStepCountListenerIndex(listener); mArrayList.clear(); // if (index >= 0 && index < mArrayList.size()) { // mArrayList.remove(index); YDLog.logInfo(kTag, "unRegister listener ,remove succ"); // } YDLog.logInfo(kTag, "unRegister listener,callback"); } @Override public int getCurStepCount() throws android.os.RemoteException { return todayStepCount; } @Override public void onStepDetectedCallBack(int step, long st, long et) throws RemoteException { } };
主要是要拿到binder對象,在啓動服務之後可以拿到
@Nullable @Override public IBinder onBind(Intent intent) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { setForegroundService(); } return mBinder; }