通过AIDL实现跨进程更新UI

一、概述

本篇文章将和大家一起来学习AIDL实现跨进程更新UI。
需求是:在同一个应用中有两个Activity,MainActivity和TempActivity,这两个Activity不在同一个进程中。

通过AIDL实现跨进程更新UI

现在需要通过TempActivity来改变MainActivity中的视图,即修改MainActivity中TextView的显示内容并且添加两个Button,也就是实现跨进程更新UI这么一个功能。

对于这种跨进程更新UI的需求我们可以通过AIDL或者BroadcastReceiver的方式实现,而本篇文章主要通过AIDL的方式实现,如果你对AIDL
还不熟悉的话可以先看看我的这篇文章:

二、实现效果图

在MainActivity里点击“跳转到新进程ACTIVITY”按钮,会启动一个新进程的TempActivity,我们先点击“绑定服务”,这样我们就启动了服务,再点击“AIDL更新”按钮,通过调用handler来实现跨进程更新UI,点击返回,我们发现MainActivity页面中的TextView内容已经更新了,并且新添加了两个按钮。
通过AIDL实现跨进程更新UI

三、核心代码

IViewManager.aidl
里面提供了两个方法,一个是根据id更新TextView里面的内容,一个是根据id添加view视图

// IViewManager.aidl
package com.czhappy.remoteviewdemo;

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

interface IViewManager {
    void setTextViewText(in int id,in String text);//设置TextView的内容
    void addView(in int layoutId);                 //添加View视图
}

rebuild project让IDE工具自己生成AIDL接口对应的java文件。

ViewAIDLService.java

package com.czhappy.remoteviewdemo.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;

import com.czhappy.remoteviewdemo.IViewManager;
import com.czhappy.remoteviewdemo.activity.MainActivity;

public class ViewAIDLService extends Service {
    private static final String TAG = "ViewAIDLService";
    private Binder viewManager = new IViewManager.Stub(){
        @Override
        public void setTextViewText(int id, String text) throws RemoteException {
            Message message = new Message();
            message.what = ;
            Bundle bundle = new Bundle();
            bundle.putInt("id",id);
            bundle.putString("text",text);
            message.setData(bundle);
            new MainActivity.MyHandler(ViewAIDLService.this,getMainLooper()).sendMessage(message);
        }

        @Override
        public void addView(int layoutId) throws RemoteException {
            Message message = new Message();
            message.what = ;
            Bundle bundle = new Bundle();
            bundle.putInt("layoutId",layoutId);
            message.setData(bundle);
            Log.i(TAG,"thread name = "+Thread.currentThread().getName());
            new MainActivity.MyHandler(ViewAIDLService.this,getMainLooper()).sendMessage(message);
        }

    };
    public ViewAIDLService() {
    }

    /**
     * 当客户端绑定到该服务时调用
     * @param intent
     * @return
     */
    @Override
    public IBinder onBind(Intent intent) {
        return viewManager;
    }
}

MainActivity.java

package com.czhappy.remoteviewdemo.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.czhappy.remoteviewdemo.R;

import java.lang.ref.WeakReference;

public class MainActivity extends AppCompatActivity {

    private static String TAG = "MainActivity";
    private static LinearLayout mLinearLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mLinearLayout = (LinearLayout) this.findViewById(R.id.mylayout);
    }

    public static class MyHandler extends Handler {
        WeakReference<Context> weakReference;
        public MyHandler(Context context, Looper looper) {
            super(looper);
            weakReference = new WeakReference<>(context);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.i(TAG, "handleMessage");
            switch (msg.what) {
                case : //修改MainActivity中TextView的内容
                    Bundle bundle = msg.getData();
                    TextView textView = (TextView) mLinearLayout.findViewById(bundle.getInt("id"));
                    textView.setText(bundle.getString("text"));
                    break;
                case : //在MainActivity中添加View视图
                    LayoutInflater inflater = LayoutInflater.from(weakReference.get());
                    View view = inflater.inflate(msg.getData().getInt("layoutId"),null);
                    mLinearLayout.addView(view);
                default:
                    break;
            }
        }

    };

    public void readyGo(View view){
        Intent intent = new Intent(MainActivity.this, TempActivity.class);
        startActivity(intent);
    }

}

TempActivity.java

package com.czhappy.remoteviewdemo.activity;

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.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import com.czhappy.remoteviewdemo.IViewManager;
import com.czhappy.remoteviewdemo.R;
import com.czhappy.remoteviewdemo.service.ViewAIDLService;

public class TempActivity extends AppCompatActivity {

    private String TAG = "TempActivity";

    private IViewManager viewsManager;
    private boolean isBind = false;


    private ServiceConnection viewServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e(TAG,"onServiceConnected");
            viewsManager = IViewManager.Stub.asInterface(service);

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //回收
            viewsManager = null;
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_temp);
    }

    /**
     * 绑定服务
     */
    public void bindService(View view) {
        Intent viewServiceIntent = new Intent(this,ViewAIDLService.class);
        isBind = bindService(viewServiceIntent,viewServiceConnection, Context.BIND_AUTO_CREATE);
    }

    /**
     * 更新UI
     */
    public void UpdateUI(View view){
        try {
            viewsManager.setTextViewText(R.id.mytext,"通过AIDL跨进程修改TextView内容");
            viewsManager.addView(R.layout.button_layout);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(isBind){
            unbindService(viewServiceConnection);
            isBind = false;
        }

    }

}

配置文件AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.czhappy.remoteviewdemo">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".activity.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activity.TempActivity"
            android:process=":remote">
        </activity>

        <service android:name="com.czhappy.remoteviewdemo.service.ViewAIDLService"/>

    </application>

</manifest>

相关推荐