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

更多相关文章

  1. android WebView解析 调用html5页面
  2. Android中下拉列表框操作
  3. Android(安卓)SQLiteOpenHelper的使用
  4. Android中按钮点击后背景改变样式
  5. 高德地图Android,绘制自定义定位蓝点、marker、面
  6. android视频录制(调用系统视频录制),生成缩略图
  7. Android(安卓)Camera框架分析
  8. Android(安卓)webView中调用JavaScript
  9. Android系统启动——Zygote进程

随机推荐

  1. Android中MVP模式
  2. TextView最大长度限制,超出部分省略号显示
  3. Android 学习笔记(4)—— ToggleButton 、S
  4. Android(安卓)— 运行时权限检查
  5. Android(安卓)Volley入门到精通:初识Volle
  6. android HAL 详解
  7. Android多线程:理解和简单使用总结
  8. Android之怎么使用SQLite数据库(增、删、
  9. Android(安卓)开发工具集合 - (Android(
  10. Android 2.2 源码结构分析