Android Studio下的一個AIDL實例

在服務端定義AIDL接口

新建一個appservice項目

添加一個.aidl文件,右鍵 -> New -> AIDL -> AIDL File

在aidl文件中加入一個返回字符串的方法,完成之後build->make project

package com.example.appservice;

interface IMyAidlInterface {
    String getValue();
}

添加一個類MyService繼承Service

public class MyService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        return new MAIDLServiceImpl();
    }

    public class MAIDLServiceImpl extends com.example.appservice.IMyAidlInterface.Stub{
        @Override
        public String getValue() throws RemoteException {
            return "成功連上服務端";
        }
    }

}

在.xml文件中對service進行配置,添加代碼

<service
    android:name=".MyService"
    android:process=":remote"
    android:exported="true">
<intent-filter>
    <category android:name="android.intent.category.DEFAULT" />
    <action android:name="com.example.appservice.IMyAidlInterface" />
</intent-filter>
</service>

在客戶端調用接口

新建一個項目appclient

將服務端的aidl文件夾複製粘貼過來,build->make project

修改MainActivity代碼

public class MainActivity extends AppCompatActivity {
    private Button btCallAIDL;
    private IMyAidlInterface aidlService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btCallAIDL = (Button) findViewById(R.id.bt_call_aidl);
        // 點擊按鈕綁定服務端的服務
        btCallAIDL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.example.appservice.IMyAidlInterface"); // 參數爲服務端的Service的action的name參數的值
                intent.setPackage("com.example.appservice"); // 參數爲服務端的包名
                bindService(intent, new MyConnection(), BIND_AUTO_CREATE);// 綁定Service
            }
        });
    }

    private class MyConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            aidlService = IMyAidlInterface.Stub.asInterface(service);// 獲得服務端的RemoteInterface的對象。
            try {
                String str = aidlService.getValue();// 調用服務端的方法
                Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

}

效果展示圖

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