Android中AIDL的理解与使用(二)——跨应用绑定Service并通信

时间:2023-09-04 20:49:08

跨应用绑定Service并通信:

1、(StartServiceFromAnotherApp)AIDL文件中新增接口:

  void setData(String data);

  AppService文件中实现接口:

  public IBinder onBind(Intent intent) {
    return new IAppServiceRomoteBinder.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 {
      }
    };
  }

2、(StartServiceFromAnotherApp)修改AppService内部数据:

  private String data = "默认信息";

  public void setData(String data) throws RemoteException {
    AppService.this.data = data;
  }

3、((StartServiceFromAnotherApp)AppService

  onCreat写线程,onDestroy中销毁,每隔一秒输出data,方便测试内部数据的变化:

  private boolean running = false;

   public void onCreate() {
    super.onCreate();
    System.out.println("Service started");

    new Thread(){
      @Override
      public void run() {
        super.run();
        running = true;
        while(running){
          System.out.println(data);
        try {
          Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
            }
        }
      }
    }.start();
  }

  public void onDestroy() {
    super.onDestroy();
    System.out.println("Service destroy");
    running = false;
  }

4、(AnotherApp)主布局:

  <EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="这是另一个应用中的数据"
    android:id="@+id/etInput" />

  <Button
    android:text="同步数据到绑定的服务中"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/btnSync" />

5、(AnotherApp)进入MainActivity,按钮及输入文本的监听:

   private EditText etInput;

   etInput = (EditText) findViewById(R.id.etInput);

   findViewById(R.id.btnSync).setOnClickListener(this);

6、如何通过Binder方便地执行远程函数?把StartServiceFromAnotherApp中AIDL文件拷贝到AnotherApp中,保持包名一致。

7、(AnotherApp)进行数据最后处理:

  private IAppServiceRomoteBinder binder = null;

  case R.id.btnUnbindService:
    unbindService(this);
    binder = null;
    break;
  case R.id.btnSync:
    if(binder != null){
      try {
      binder.setData(etInput.getText().toString());
        } catch (RemoteException e) {
           e.printStackTrace();
        }
    }

  

  public void onServiceConnected(ComponentName name, IBinder service) {
      //binder = IAppServiceRomoteBinder(service); 两个类定义所在地址不一样,不能强制类型转换
      binder = IAppServiceRomoteBinder.Stub.asInterface(service);
  }