[学习笔记]Android中AIDL的理解与使用

来源:互联网 发布:林忆莲歌词知乎 编辑:程序博客网 时间:2024/06/04 21:49

以下内容纯粹为本人学习笔记【记录】之用,所听课程(Q群群友百度网盘提供)为极客学院一位老师所讲(老师大名我尚未知晓),如有侵权请告知。在此特别感谢这位老师录制的视频资料。

AIDL:Android Interface Definition Language Android接口定义语言
1、跨应用启动Service
新建一个Project和Module,分别命名为:StartSvcFromAnotherApp、AnotherApp
代码分别如下:
Project—-StartSvcFromAnotherApp
MainActivity

public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        startService(new Intent(this, AppService.class));//启动服务    }    @Override    protected void onDestroy() {        super.onDestroy();        stopService(new Intent(this, AppService.class));//停止服务    }}

AppService

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();        System.out.println("Service started");    }    @Override    public void onDestroy() {        super.onDestroy();        System.out.println("Service destroy");    }}

activity_main默认即可,不用修改。
Module—-AndroidApp
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private Intent serviceIntent;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    serviceIntent = new Intent();    serviceIntent.setComponent(new ComponentName("com.keen.startsvcformanotherapp", "com.keen.startsvcformanotherapp.AppService"));    findViewById(R.id.btnStartAppService).setOnClickListener(this);    findViewById(R.id.btnStopAppService).setOnClickListener(this);}@Overridepublic void onClick(View v) {    switch (v.getId()) {        case R.id.btnStartAppService:            startService(serviceIntent);            break;        case R.id.btnStopAppService:            stopService(serviceIntent);            break;    }}

}
activity_main 添加两个按钮即可,用来启动和停止服务。

    <Button        android:text="启动服务"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/btnStartAppService" />    <Button        android:text="停止服务"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/btnStopAppService" />

2、跨应用绑定Service
运用到Binder,它是指定类里定义的。Android提供了一种机制,用于在多个应用程序之间进行通信,这种机制成为AIDL。
app/java/com.keen.startsvcformanotherapp/new AIDL

3、跨应用绑定Service并通信
增加接口是在AIDL文件里。

原创粉丝点击