当前位置: 代码迷 >> 综合 >> 两个应用间传递数据(AIDL)实例
  详细解决方案

两个应用间传递数据(AIDL)实例

热度:62   发布时间:2023-12-25 08:56:02.0
  1. 在AS中新建两个应用 (AIDL_1和AIDL_2)

  2. 在两个应用的app目录下新建一个文件夹(app->new->AIDL->AIDL File),AS会帮你自动建包和aidl接口在这里插入图片描述
    *注意两个应用的 com.permissionx.aidl_1 的这个包名要一样

    interface IMyAidlInterface {
          
    /*** Demonstrates some basic types that you can use as parameters* and return values in AIDL.*/
    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,double aDouble, String aString);int getId();
    String getName();
    }
    
  3. AIDL1 为服务端,所以新建一个Service

    public class MyService extends Service {
          
    public MyService() {
          
    }@Override
    public IBinder onBind(Intent intent) {
          return mBinder;
    }private final IMyAidlInterface.Stub mBinder=new IMyAidlInterface.Stub() {
          @Overridepublic void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
          }@Overridepublic int getId() throws RemoteException {
          return 3;}@Overridepublic String getName() throws RemoteException {
          return "AIDL_1_Test";}
    };Ser
    }
    

    然后在manifests中注册Service

        <serviceandroid:name=".MyService"android:enabled="true"android:exported="true"><intent-filter><action android:name="AIDL.test"/></intent-filter></service>
    
  4. AIDL_2为客户端,去bind AIDL_1的Service

    public class MainActivity extends AppCompatActivity {
          在这里插入代码片
    private TextView textView;@Override
    protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);textView=findViewById(R.id.tv_test);Intent intent=new Intent();intent.setAction("AIDL.test"); //为AIDL_1 注册服务时指定的 actionintent.setPackage("com.permissionx.aidl_1"); bindService(intent,conn, Context.BIND_AUTO_CREATE);}private final ServiceConnection conn=new ServiceConnection() {
          private IMyAidlInterface mService;@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {
          mService = IMyAidlInterface.Stub.asInterface(service);// 接收到来自AIDL_1的数据runOnUiThread(()->{
          try {
          Log.e(TAG,mService.getName());textView.setText(mService.getName());} catch (RemoteException e) {
          e.printStackTrace();}});}@Overridepublic void onServiceDisconnected(ComponentName name) {
          runOnUiThread(()->{
          try {
          Log.e("TAG",mService.getName()+"xxx");textView.setText("无数据");} catch (RemoteException e) {
          e.printStackTrace();}});mService=null;}
    };
    }
    
  5. 测试,先点开AID_1这个服务端,然后点开AIDL_2客户端,发现TextView中数据为AIDL_1中的数据,完成数据传递
    在这里插入图片描述