天天看點

Android AIDL的了解和使用

注:内容部分來自于極客學院

一、AIDL的使用場景

1.AIDL (Android Interface Definition Language) 是一種IDL 語言,用于生成可以在Android裝置上兩個程序之間進行程序間通信(interprocess communication, IPC)的代碼。如果在一個程序中(例如Activity)要調用另一個程序中(例如Service)對象的操作,就可以使用AIDL生成可序列化的參數。

2.隻有當你允許其他的一個應用程式通路你的應用程式的服務時,

服務端程式使用Intent顯示的啟動另一個App的Service

1.在服務端程式要有一個Service

public class AppService extends Service {
    public AppService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("tag","Service is create");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("tag", "Service is destory");
    }
           

2.在用戶端程式中

private Intent serviceIntent;
    Button btn_start;
    Button btn_stop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_start = (Button) findViewById(R.id.btn_start);
        btn_stop = (Button) findViewById(R.id.btn_stop);
        serviceIntent = new Intent();
        //通過包名顯示的啟動一個Service    第一個參數為app的包名  第二個為app中Service的全路徑
        serviceIntent.setComponent(new ComponentName("com.tjpld.aidlservicetest", "com.tjpld.aidlservicetest.AppService"));
        btn_start.setOnClickListener(this);
        btn_stop.setOnClickListener(this);
    }
           

使用AIDL綁定方式啟動一個Service

1.首先建立一個AIDL檔案

/*
*AIDL測試
*/
package com.tjpld.aidlservicetest;

// Declare any non-default types here with import statements

interface IAidlAppService {
    /**
     * Demonstrates some basic types that you can use as parameters
     * and return values in AIDL.
     */
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);

}
           

2.在Service的Bind中傳回建立的AIDLService對象

@Override
    public IBinder onBind(Intent intent) {
        //通過AIDL綁定一個Service
        return new IAidlAppService.Stub() {
            @Override
            public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

            }
        };
    }
           

3.在用戶端啟動用綁定的方式啟動一個Service

bindService(serviceIntent,this, Context.BIND_AUTO_CREATE);
           

三、通過AIDL綁定Service并通信

1.在你的AIDL檔案中添加一個回調方法

interface IAidlAppService {
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
            double aDouble, String aString);
    void setData(String data);
}
           

2.在Servcie中實作該方法

String PACKAGE_SAYHI="com.example.test"
  String  data="内部消息";
    boolean isRunning;
    public AppService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        //通過AIDL綁定一個Service
        return new IAidlAppService.Stub() {
            @Override
            public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

            }

            @Override
            public void setData(String data) throws RemoteException {
                AppService.this.data=data;
            }
            //在這裡可以做權限認證,return false意味着用戶端的調用就會失敗,比如下面,隻允許包名為com.example.test的用戶端通過,  
        //其他apk将無法完成調用過程  
        public boolean onTransact(int code, Parcel data, Parcel reply, int flags)  
                throws RemoteException {  
String packageName = null;  
String[]packages=MyService.this.getPackageManager(). getPackagesForUid(getCallingUid());  
if (packages != null && packages.length > ) {  
                packageName = packages[];  
            }  

if (!PACKAGE_SAYHI.equals(packageName)) {  
                return false;  
            }  

 return super.onTransact(code, data, reply, flags);  
        };
    }
           

3.在Client端建立一個Folder類型為AIDL

4.将服務端儲存AIDL檔案的包名原封不動的複制,并且在client的AIDL檔案夾下建立相同的包,并考入AIDL檔案

5.執行個體化AIDL對象在onServiceConnection

private IAidlAppService iAidlService = null;//遠端通信服務
 @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.e("tag", "BindService Success");
        //注意綁定的方式
        iAidlService = IAidlAppService.Stub.asInterface(service);
    }
    //-----------------------------
     case R.id.btn_send:
                //執行遠端通信
                if (iAidlService != null) {
                    try {
                        Log.e("tag", "data---->" + et_data.getText().toString());
                        iAidlService.setData(et_data.getText().toString());
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                break;