通过.aidl文件描述您的服务访问界面:
// IRemoteService.aidl package com.example.android; // 在这里使用import语句声明所有非默认类型 /** Example service interface */ interface IRemoteService { /** Request the process ID of this service, to do evil things with it. */ int getPid(); }
现在,在构建应用程序之后,sdk工具将生成适当的.java文件。该文件将包含Stub实现我们的aidl接口的类,并且需要扩展它:
public class RemoteService extends Service { private finalIRemoteService.Stubbinder = new IRemoteService.Stub() { @Override public int getPid() throws RemoteException { return Process.myPid(); } }; @Nullable @Override public IBinder onBind(Intent intent) { return binder; } }
然后在活动中:
public class MainActivity extends AppCompatActivity { private final ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { IRemoteService service = IRemoteService.Stub.asInterface(iBinder); Toast.makeText(this, "活动过程: " +Process.myPid+ ", Service process: " + getRemotePid(service), LENGTH_SHORT).show(); } @Override public void onServiceDisconnected(ComponentName componentName) {} }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onStart() { super.onStart(); Intent intent = new Intent(this, RemoteService.class); bindService(intent, connection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); unbindService(connection); } private int getRemotePid(IRemoteService service) { int result = -1; try { result = service.getPid(); } catch (RemoteException e) { e.printStackTrace(); } return result; } }