Activity与Service跨进程通讯、数据库访问

1.通过广播来操作写数据库

在一个项目中,Activity和子进程的Service想要访问同一个数据库,可能会造成多线程访问数据异常,目前我的解决方案是Service发送广播,然后BroadcastReceiver接收到广播后再写入数据库,如果需要读的话,可能还是需要走aidl进行数据读写。

Service.java

Intent intent = new Intent("com.test.sms");
intent.putExtra("message", JSON.toJSONString(data));
getApplicationContext().sendBroadcast(intent);

BroadcastReceiver.java

public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals("com.test.sms")) {
            //...
        }
}

Manifest.xml

<receiver
      android:name=".services.MyReceiver">
     <intent-filter>
          <action android:name="com.langtian.sms"/>
     </intent-filter>
</receiver>

2.aidl来处理多进程之间的数据访问

Android Studio先从左侧Project中新建aidl,然后重新Build项目,可在app/build/generated/source/aidl/debug/packname/中找到AS自动生成的aidl接口。

将接口复制到需要通讯项目中(client)。

以下是在Activity中的调用代码:

Activity.java

ServiceConnection connection= new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
               IMyAidlInterface aidl=IMyAidlInterface.Stub.asInterface(service);
              
 }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };
        Intent intent = new Intent("com.service.MyService");
        AppData.context.bindService(intent, connection, Context.BIND_AUTO_CREATE);

Service.java

private MyThread thread;

   public class MyBinder extends IMyAidlInterface.Stub { //实现aidl接口
       public MsgServices getService() {
           return MyServices.this;
       }

       @Override
       public String getData()throws RemoteException{
           String str=JSON.toJSONString(getData());
           return str;
       }
   }

   @Nullable
   @Override
   public IBinder onBind(Intent intent) {
    
       return binder;
   }

IMyAidlInterface.aidl

interface IMyAidlInterface {

    String getData();

}

 

服务启动后,通过aidl接口即可进行对多进程Service调用了,值得注意的是,aidl仅接受标准数据类型,且传输大小不得超过1M。

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注