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 > 0) {  
                packageName = packages[0];  
            }  

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;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章