跨进程通信AIDL的使用

绑定服务的过程

首先创建一个Service

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new IMyServiceInterface.Stub() {
            @Override
            public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

            }
        };
    }

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("MyService onCreate");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("MyService onDestroy");

    }
}

生成一个AIDL文件

package com.example.aidldemo;

// Declare any non-default types here with import statements

interface IMyServiceInterface {
    /**
     * 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);
}

接下来实现在另一个应用中开启/停止/绑定/解绑服务

创建一个module anotherapp

在anotherapp中的MainActivity.java 实现下面的方法

public class MainActivity extends AppCompatActivity implements ServiceConnection {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开启服务
                Intent i = new Intent();
                i.setComponent(new ComponentName("com.example.aidldemo","com.example.aidldemo.MyService"));
                startService(i);
            }
        });

        findViewById(R.id.btn_stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭服务
                Intent i = new Intent();
                i.setComponent(new ComponentName("com.example.aidldemo","com.example.aidldemo.MyService"));
                stopService(i);
            }
        });
        findViewById(R.id.bind_service).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //绑定服务
                Intent i = new Intent();
                i.setComponent(new ComponentName("com.example.aidldemo","com.example.aidldemo.MyService"));
                bindService(i,MainActivity.this, Context.BIND_AUTO_CREATE);
            }
        });

        findViewById(R.id.unBind_Service).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //解绑服务
                Intent i = new Intent();
                i.setComponent(new ComponentName("com.example.aidldemo","com.example.aidldemo.MyService"));
                unbindService(MainActivity.this);
            }
        });

    }

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

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
}

接下来实现2个应用之间的的通信,修改AIDL文件,添加setDate(String data);

package com.example.aidldemo;

// Declare any non-default types here with import statements

interface IMyServiceInterface {
    /**
     * 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);
            
    void setDate(String data);
}

Rebuild一下,然后修改MyService里面的数据,每隔1秒输出数据来观测数据的变化。

package com.example.aidldemo;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

public class MyService extends Service {

    private String data ="test";
    private boolean running = false;
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new IMyServiceInterface.Stub() {
            @Override
            public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

            }

            @Override
            public void setDate(String data) throws RemoteException {
                MyService.this.data = data;
            }
        };
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("MyService onDestroy");
        running = false;
    }
}

服务启动的时候,会不断的输出数据,当我们在anotherapp中修改数据的时候,这边的数据也会发生改变

接下来我们需要把AIDL文件拷贝下,而且要保证包名一样,

复制这个包名

 

点击Finish

再将AIDL文件复制进这个目录下

将anotherapp 输入框中的内容同步到app中

package com.example.anotherapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.EditText;

import com.example.aidldemo.IMyServiceInterface;

public class MainActivity extends AppCompatActivity implements ServiceConnection {

    private EditText et_input;
    private IMyServiceInterface binder = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_input = findViewById(R.id.et_input);
        findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开启服务
                Intent i = new Intent();
                i.setComponent(new ComponentName("com.example.aidldemo","com.example.aidldemo.MyService"));
                startService(i);
            }
        });

        findViewById(R.id.btn_stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //关闭服务
                Intent i = new Intent();
                i.setComponent(new ComponentName("com.example.aidldemo","com.example.aidldemo.MyService"));
                stopService(i);
            }
        });
        findViewById(R.id.bind_service).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //绑定服务
                Intent i = new Intent();
                i.setComponent(new ComponentName("com.example.aidldemo","com.example.aidldemo.MyService"));
                bindService(i,MainActivity.this, Context.BIND_AUTO_CREATE);
            }
        });

        findViewById(R.id.unBind_Service).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //解绑服务
                Intent i = new Intent();
                i.setComponent(new ComponentName("com.example.aidldemo","com.example.aidldemo.MyService"));
                unbindService(MainActivity.this);
            }
        });

        findViewById(R.id.btn_syn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //将输入框中输入的内容同步到app中
                if(binder!=null){
                    try {
                        binder.setDate(et_input.getText().toString());
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }

            }
        });

    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        binder = IMyServiceInterface.Stub.asInterface(service);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
}

布局文件如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

  <Button
      android:id="@+id/btn_start"
      android:layout_width="200dp"
      android:layout_height="80dp"
      android:text="start Service"/>

    <Button
        android:id="@+id/btn_stop"
        android:layout_width="200dp"
        android:layout_height="80dp"
        android:text="stop Service"/>

  <Button
      android:id="@+id/bind_service"
      android:layout_width="200dp"
      android:layout_height="80dp"
      android:text="bind Service"/>

  <Button
      android:id="@+id/unBind_Service"
      android:layout_width="200dp"
      android:layout_height="80dp"
      android:text="unBind Service"/>

  <EditText
      android:id="@+id/et_input"
      android:layout_width="match_parent"
      android:layout_height="80dp"/>

  <Button
      android:id="@+id/btn_syn"
      android:layout_width="200dp"
      android:layout_height="80dp"
      android:text="同步数据到另一个应用"/>
</LinearLayout>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值