[置顶] android AIDL 进程间通信
16lz
2022-03-14
1.定义aidl文件
a.ITestService.aidl
package com.open.aidl.service;import com.open.aidl.service.ITestServiceCallback;interface ITestService { void registerCallback(ITestServiceCallback cb); void unregisterCallback(ITestServiceCallback cb); int request(inout Bundle mBundle);}
b.ITestServiceCallback.aidl
package com.open.aidl.service;oneway interface ITestServiceCallback { void onResponse(inout Bundle mBundle);}
2.定义Activity
<package com.open.aidl;import android.app.Activity;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.os.RemoteException;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import com.open.aidl.service.ITestService;import com.open.aidl.service.ITestServiceCallback;import com.open.aidl.service.TestService;public class MainActivity extends Activity {private final String TAG="MainActivity";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);init();}private void init(){findViewById(R.id.bindBtn).setOnClickListener(clickListener);findViewById(R.id.unBindBtn).setOnClickListener(clickListener);}View.OnClickListener clickListener=new OnClickListener() {@Overridepublic void onClick(View v) {switch(v.getId()){case R.id.bindBtn:bind();break;case R.id.unBindBtn:unbind();}}};private void bind(){Intent mIntent=new Intent(TestService.class.getName());bindService(mIntent, mServerConnection, Context.BIND_AUTO_CREATE);}private void unbind(){if(null!=mService){try {mService.unregisterCallback(mCallBack);} catch (RemoteException e) {e.printStackTrace();}unbindService(mServerConnection);}}@Overrideprotected void onDestroy() {unbind();super.onDestroy();}private ITestService mService=null;private ServiceConnection mServerConnection=new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {Log.v(TAG, "onServiceDisconnected");mService=null;}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {Log.v(TAG, "onServiceConnected");mService=ITestService.Stub.asInterface(service);try {mService.registerCallback(mCallBack);mService.request(null);} catch (RemoteException e) {e.printStackTrace();}catch (Exception e) {e.printStackTrace();}}};private ITestServiceCallback mCallBack=new ITestServiceCallback.Stub() {@Overridepublic void onResponse(Bundle mBundle) throws RemoteException {Log.v(TAG,"call from service");}};}
3.定义Service.
package com.open.aidl.service;import android.app.Service;import android.content.Intent;import android.os.Bundle;import android.os.Handler;import android.os.IBinder;import android.os.IInterface;import android.os.RemoteCallbackList;import android.os.RemoteException;import android.util.Log;/** * 后台服务类 * @author DexYang * */public class TestService extends Service {private final String TAG="TestService";private Object mCallbacksLock=new Object();private Handler mHandler=new Handler();@Overridepublic void onCreate() {super.onCreate();Log.v(TAG, "onCreate()");}@Override public void onStart(Intent intent, int startId) {Log.v(TAG, "onStart()"); handleCommand(intent); }@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.v(TAG, "onStartCommand()");handleCommand(intent);return START_STICKY;}private void handleCommand(Intent intent){}@Overridepublic IBinder onBind(Intent arg0) {Log.v(TAG, "onBind()");if(null!=arg0&&TestService.class.getName().equals(arg0.getAction())){handleCommand(arg0);}return mBinder;} @Overridepublic void onRebind(Intent intent) {Log.v(TAG, "onRebind()");if(TestService.class.getName().equals(intent.getAction())){handleCommand(intent);}super.onRebind(intent);} @Overridepublic boolean onUnbind(Intent intent) {Log.v(TAG, "onUnbind()");return true;}@Overridepublic void onDestroy() {Log.v(TAG, "onDestroy()");mCallbacks.kill();android.os.Process.killProcess(android.os.Process.myPid());super.onDestroy();}/** * Binder 相关 */private final CusRemoteCallbackList<ITestServiceCallback> mCallbacks= new CusRemoteCallbackList<ITestServiceCallback>();private ITestService.Stub mBinder=new ITestService.Stub() {@Overridepublic int request(Bundle mBundle) throws RemoteException {Log.v(TAG,"call from Activity request ");mHandler.postDelayed(new Runnable(){@Overridepublic void run() {synchronized (mCallbacksLock) {int callbacksNum = mCallbacks.beginBroadcast(); for (int i=callbacksNum-1; i>=0; i--) { try { mCallbacks.getBroadcastItem(i).onResponse(null);; } catch (Exception e) { e.printStackTrace(); } } mCallbacks.finishBroadcast();}}}, 3000);return 0;}@Overridepublic void registerCallback(ITestServiceCallback cb)throws RemoteException {Log.v(TAG,"registerCallback :");if (cb != null){mCallbacks.register(cb);}}@Overridepublic void unregisterCallback(ITestServiceCallback cb)throws RemoteException {Log.v(TAG,"unregisterCallback :");if (cb != null) {mCallbacks.unregister(cb);}}};/** * 经过测试onCallbackDied()方法,只有在bindService(),没有调用unbind()方法process就挂了的情况下才会执行 * @author Administrator * @param <E> */private class CusRemoteCallbackList<E extends IInterface> extends RemoteCallbackList<E>{@Overridepublic void onCallbackDied(E callback) {Log.v(TAG, "CusRemoteCallbackList onCallbackDied 1");super.onCallbackDied(callback);}@Overridepublic void onCallbackDied(E callback, Object cookie) {Log.v(TAG, "CusRemoteCallbackList onCallbackDied 2");super.onCallbackDied(callback, cookie);}} }
4.配置AndroidManifest.xml文件
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.open.aidl" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.open.aidl.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:label="TestService" android:name="com.open.aidl.service.TestService" android:process="com.open.aidl" android:exported="true"> <intent-filter> <action android:name="com.open.aidl.service.TestService"/> </intent-filter> </service> </application></manifest>
5.测试运行.
点击bind service ,
在TestService中 打印了call from Activity,说明Activity 调用 Service 成功;
3秒后在Activity中 打印了call from service,说明Service 调用 Activity 成功。
Demo代码地址:http://download.csdn.net/detail/zz7zz7zz/6010119
邮箱:zz7zz7zz@163.com
微博:http://weibo.com/u/3209971935
更多相关文章
- Android(安卓)面试:常见问题总结
- android WebView结合javascript相互调用
- android WebView结合javascript相互调用
- Android自定义对话框(Dialog)位置,大小
- Android(安卓)TV自定义通用标题栏(组合控件)
- Android(安卓)App怎样调用 Frameworks Bluetooth接口
- Android(安卓)自定义设置文本字体间间距
- android WebView 应用内点击超链接不调用系统浏览器
- Android(安卓)Property实现介绍