1. 程式人生 > >Android Studio 使用AIDL

Android Studio 使用AIDL

以前在Eclipse 中寫過aidl 。最近想在Android Studio 中實現以下。


 我先寫下我遇到的一個坑,困擾了我一下午才解決。

在所有的程式碼都寫好後,執行程式一點反應都沒有。

最後發現是許可權的問題。我的是6.0的手機,預設是不支援關聯啟動的

需要去手機 設定--》應用程式---》許可權管理  ---》選擇你的服務應用 開啟關聯啟動 




開始:

先進行準備工作

新建立一個應用 如:AidlDemo 該應用作為客戶端 在該應用中建立一個Moudle AidlService 作為服務端

/2、


目錄結構如下:


2、開始寫服務端

1、建立檔案AIDL 名稱為 IMyAidlInterface



會在 main目錄下生成如下檔案

IMyAidlInterface.aidl 中 寫兩個方法 add print




然後 Build  一下,這樣就生成了java介面檔案,地址在專案資料夾/app/build/generated/aidl裡面




aidlservice 建立一個服務

public class AidlDemoService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("dd", "service------onCreate");
    }

    @Override
    public void unbindService(ServiceConnection conn) {
        super.unbindService(conn);
        Log.e("dd", "service------unbindService");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("dd", "service------onDestroy");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.e("dd", "service------onBind");
        return stub;
    }

    public IMyAidlInterface.Stub stub = new IMyAidlInterface.Stub() {
        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

        }

        @Override
        public int add(int x, int y) throws RemoteException {
            return x + y;
        }
	
@Override public String printStr(String str) throws RemoteException { return str; } }; }

manifest.xml 中新增配置資訊 action 是用來啟動你的服務的

服務端完成。

客戶端:

1、把aidlService 中的aidl資料夾整個拷貝到 app中


2、編寫MainActivity ,進行邏輯實現

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private IMyAidlInterface anInterface;
    private Button addBtn;
    private Button printBtn;
    private Button bindBtn;
    private Button unBindBtn;
    private ServiceConnection connection;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        printBtn = (Button) findViewById(R.id.print_btn);
        addBtn = (Button) findViewById(R.id.add_btn);
        bindBtn = (Button) findViewById(R.id.bind_btn);
        unBindBtn = (Button) findViewById(R.id.unBind_btn);
        printBtn.setOnClickListener(this);
        addBtn.setOnClickListener(this);
        bindBtn.setOnClickListener(this);
        unBindBtn.setOnClickListener(this);
        
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
		
		//服務繫結的時候走這裡
                Log.e("dd", "activity------onServiceConnected");
                anInterface = IMyAidlInterface.Stub.asInterface(service);
            }
            @Override
            public void onServiceDisconnected(ComponentName name) {
		
		// 當記憶體不足或者服務異常關閉的時候走這裡(解綁是不走這個方法的)
                Log.e("dd", "activity------onServiceDisconnected");
                anInterface = null;
            }
        };
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.print_btn:	// print
                if (anInterface == null) {
                    return;
                }
                try {
			// printStr 方法
                    String aaa = anInterface.printStr("helloWorld");
                    printBtn.setText("" + aaa);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.add_btn:	// add
                if (anInterface == null) {
                    return;
                }
                try {
                    int a = anInterface.add(10, 15);
                    addBtn.setText("" + a);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.bind_btn://  繫結服務
                Toast.makeText(MainActivity.this, "bind", Toast.LENGTH_SHORT).show();
                bind();
                break;
            case R.id.unBind_btn:// 解除繫結
                Toast.makeText(MainActivity.this, "unBind", Toast.LENGTH_SHORT).show();
                unBind();
                break;
        }
    }

    /**
     * 繫結服務
     */
    private void bind() {
        Intent intent = new Intent();
        intent.setAction("com.example.aidlservice.AidlDemoService");
//      5.0以上需要設定    否則報錯
        intent.setPackage("com.example.aidlservice");
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    /**
     * 解綁服務
     */
    private void unBind() {
        if(connection!=null){
            unbindService(connection);
        }
    }
}



結束:見證奇蹟的時刻將要來來臨

首先把兩個應用都跑到手機上


點選繫結,然後 add   print  成功輸出。