标签:
AIDL:android interface define language(接口定义语言)
作用:方便远程调用其他服务中的方法
注意:安卓四大组件都要在清单文件注册
aidl创建图:
interface InterfaceAidl { void interfacePay(); }
public class MyService extends Service { class MyBinder extends InterfaceAidl.Stub { @Override public void interfacePay() throws RemoteException { pay(); } } @Nullable @Override public IBinder onBind(Intent intent) { MyBinder binder = new MyBinder(); return binder; } private void pay() { Log.i("service","支付成功"); } }
public class MainActivity extends AppCompatActivity { private Intent intent; private MyServiceConnection myServiceConnection; private InterfaceAidl interfaceAidl; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intent = new Intent(this,MyService.class); myServiceConnection = new MyServiceConnection(); } public void bind(View view){ bindService(intent, myServiceConnection, BIND_AUTO_CREATE); } public void pay(View view){ try { interfaceAidl.interfacePay(); } catch (RemoteException e) { e.printStackTrace(); } } class MyServiceConnection implements ServiceConnection{ @Override public void onServiceConnected(ComponentName name, IBinder service) { interfaceAidl = InterfaceAidl.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName name) { } } @Override protected void onDestroy() { super.onDestroy(); unbindService(myServiceConnection); } }
远程调用服务
interface InterfaceAidl { void interfacePay(); }
<service android:name=".MyService"> <intent-filter> <action android:name="aidl_interface.pay"></action> </intent-filter> </service>
public class MainActivity extends AppCompatActivity { private Intent intent; private InterfaceAidl interfaceAidl; private MyServiceConnection myServiceConnection; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intent = new Intent(); myServiceConnection = new MyServiceConnection(); intent.setAction("aidl_interface.pay"); intent.setPackage("com.example.administrator.aidlservice"); } public void bind(View view){ bindService(intent,myServiceConnection,BIND_AUTO_CREATE); } public void pay(View view){ try { interfaceAidl.interfacePay(); } catch (RemoteException e) { e.printStackTrace(); } } class MyServiceConnection implements ServiceConnection{ @Override public void onServiceConnected(ComponentName name, IBinder service) { interfaceAidl = InterfaceAidl.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName name) { } } @Override protected void onDestroy() { super.onDestroy(); unbindService(myServiceConnection); } }
标签:
原文地址:http://www.cnblogs.com/anni-qianqian/p/5403638.html