Android中AIDL的理解與使用(一)——跨應用啟動/綁定Service


AIDL(Android Interface Definition Language)——安卓接口定義語言

一、startService/stopService

1、同一個應用程序啟動Service:

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    startService(new Intent(this,AppService.class));  //啟動Service
  }
  protected void onDestroy() {
    super.onDestroy();
    stopService(new Intent(this,AppService.class));  //停止Service
  }

2、跨應用啟動service:

  通過Action的隱式Intent啟動Service在安卓5.0以前的版本是可以實現跨應用啟動Service的,安卓5.0以后的版本若想實現

跨應用啟動Service的功能必須使用顯示Intent。

  public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Intent serviceIntent;
    
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      serviceIntent = new Intent();
      serviceIntent.setComponent(new ComponentName("com.w.startservicefromanotherapp","com.w.startservicefromanotherapp.AppService"));

      findViewById(R.id.btnStartService).setOnClickListener(this);
      findViewById(R.id.btnStopService).setOnClickListener(this);
  }

    public void onClick(View v) {
      switch (v.getId()){
        case R.id.btnStartService:
          // Intent i = new Intent();
          //i.setComponent(new ComponentName("com.w.startservicefromanotherapp","com.w.startservicefromanotherapp.AppService"));

          //顯示 Intent被啟動程序的包名,被啟動服務的類名
          startService(serviceIntent);
          break;
        case R.id.btnStopService:
          stopService(serviceIntent);
          break;
         }
    }
  }

二、bindService/unbindService

跨應用綁定Service:AIDL——用於在多個應用程序之間進行通信

1、在StartServiceFromAnotherApp新建AIDL文件IAppServiceRomoteBinder,會全自動生成相關的類。

2、在返回Binder時(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 {  }
    };
  }

3、在AnotherApp項目中綁定這個服務:

  findViewById(R.id.btnBindService).setOnClickListener(this);
  findViewById(R.id.btnUnbindService).setOnClickListener(this);


  case R.id.btnBindService:
    bindService(serviceIntent,this, Context.BIND_AUTO_CREATE);
    break;
  case R.id.btnUnbindService:
    unbindService(this);
    break;

  @Override
  public void onServiceConnected(ComponentName name, IBinder service) {
    System.out.println("Bind Service");
    System.out.println(service);  //顯示IBinder service
  }

  @Override
  public void onServiceDisconnected(ComponentName name) {  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM