Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 RemoteViews 實作跨進程更新 UI 的完整流程

編輯:關於 Android 程式設計

一、為什麼不直接用 AIDL

先前談過以 AIDL 達成跨進程更新 UI,這個傳統做法可行,但缺點相當明顯:

  • View 上的方法數量龐大,若每個都要在 IPC 介面中補一份對應宣告,維護成本極高。
  • View 的每一次方法呼叫都會觸發一次 IPC,累積起來的效能開銷不可小覷。
  • 部分參數天生無法跨進程傳遞,例如 OnClickListener 只是個介面,並未實作序列化。

RemoteViews 正是為了解決這些問題而生:它把「要更新什麼」打包成一份可跨進程傳遞的描述,接收端再依描述還原成真正的 View。

二、展示效果

同一支 App 內有 MainActivity 與 Temp2Activity 兩個頁面,兩者被配置在不同進程。目標是由 Temp2Activity 去改變 MainActivity 的畫面——在 MainActivity 中動態加上兩個 Button,而且連點擊事件都要能正常運作。

操作順序是:在 MainActivity 點「跳轉到新進程 ACTIVITY」進入 Temp2Activity,先按「綁定服務」啟動 Service,再按「AIDL 更新」觸發更新,返回後即可看到 MainActivity 多出兩個具備點擊事件的按鈕。

三、核心程式碼

先定義 AIDL 介面,這裡只保留一個方法:接收 RemoteViews 物件並套用。

IremoteViewsManager.aidl

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

 interface IremoteViewsManager {
 void addRemoteView(in RemoteViews remoteViews);
 }

Service 端收到 RemoteViews 後,把它包進 Message 交給主執行緒的 Handler 處理。

RemoteViewsAIDLService.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.widget.RemoteViews;
 import com.czhappy.remoteviewdemo.IremoteViewsManager;
 import com.czhappy.remoteviewdemo.activity.MainActivity;

 public class RemoteViewsAIDLService extends Service {
 private static final String TAG = "RemoteViewsAIDLService";

 private Binder remoteViewsBinder = new IremoteViewsManager.Stub(){
 @Override
 public void addRemoteView(RemoteViews remoteViews) throws RemoteException {
 Message message = new Message();
 message.what = 1;
 Bundle bundle = new Bundle();
 bundle.putParcelable("remoteViews", remoteViews);
 message.setData(bundle);
 new MainActivity.MyHandler(RemoteViewsAIDLService.this, getMainLooper()).sendMessage(message);
 }
 };

 public RemoteViewsAIDLService() { }

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

MainActivity 用 apply() 把 RemoteViews 還原成真正的 View,再掛到容器上。這裡刻意用 WeakReference 持有 Context,避免記憶體洩漏。

MainActivity.java

 package com.czhappy.remoteviewdemo.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.View;
 import android.widget.LinearLayout;
 import android.widget.RemoteViews;
 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 1:
 RemoteViews remoteViews = msg.getData().getParcelable("remoteViews");
 if (remoteViews != null) {
 Log.i(TAG, "updateUI");
 View view = remoteViews.apply(weakReference.get(), mLinearLayout);
 mLinearLayout.addView(view);
 }
 break;
 default:
 break;
 }
 }
 };

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

Temp2Activity 負責綁定服務、組裝 RemoteViews,並用 PendingIntent 為遠端 View 掛上點擊行為。

Temp2Activity.java

 package com.czhappy.remoteviewdemo.activity;

 import android.app.PendingIntent;
 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 android.widget.RemoteViews;
 import com.czhappy.remoteviewdemo.IremoteViewsManager;
 import com.czhappy.remoteviewdemo.R;
 import com.czhappy.remoteviewdemo.service.RemoteViewsAIDLService;

 public class Temp2Activity extends AppCompatActivity {
 private String TAG = "Temp2Activity";
 private IremoteViewsManager remoteViewsManager;
 private boolean isBind = false;

 private ServiceConnection remoteViewServiceConnection = new ServiceConnection() {
 @Override
 public void onServiceConnected(ComponentName name, IBinder service) {
 Log.i(TAG, "onServiceConnected");
 remoteViewsManager = IremoteViewsManager.Stub.asInterface(service);
 }
 @Override
 public void onServiceDisconnected(ComponentName name) {
 remoteViewsManager = 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, RemoteViewsAIDLService.class);
 isBind = bindService(viewServiceIntent, remoteViewServiceConnection, Context.BIND_AUTO_CREATE);
 }

 /** 更新 UI */
 public void UpdateUI(View view){
 RemoteViews remoteViews = new RemoteViews(Temp2Activity.this.getPackageName(), R.layout.button_layout);

 Intent intentClick = new Intent(Temp2Activity.this, FirstActivity.class);
 PendingIntent openFirstActivity = PendingIntent.getActivity(Temp2Activity.this, 0, intentClick, 0);
 remoteViews.setOnClickPendingIntent(R.id.firstButton, openFirstActivity);

 Intent secondClick = new Intent(Temp2Activity.this, SecondActivity.class);
 PendingIntent openSecondActivity = PendingIntent.getActivity(Temp2Activity.this, 0, secondClick, 0);
 remoteViews.setOnClickPendingIntent(R.id.secondButton, openSecondActivity);

 remoteViews.setCharSequence(R.id.secondButton, "setText", "想改就改");

 try {
 remoteViewsManager.addRemoteView(remoteViews);
 } catch (RemoteException e) {
 e.printStackTrace();
 }
 }

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

別忘了在 AndroidManifest.xml 中把 Temp2Activity 指定到獨立進程,Service 也要註冊。

AndroidManifest.xml

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="https://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.FirstActivity" />
 <activity android:name=".activity.SecondActivity" />
 <activity android:name=".activity.Temp2Activity" android:process=":remote2" />
 <service android:name="com.czhappy.remoteviewdemo.service.RemoteViewsAIDLService" />
 </application>
 </manifest>

四、RemoteViews 的能力界線

RemoteViews 天生就是為跨進程更新 UI 而設計,內部封裝了許多可用方法,但它並非萬能——目前支援的版面與控制項相當有限。

支援的 Layout:FrameLayout、LinearLayout、RelativeLayout、GridLayout

支援的 View:AnalogClock、Button、Chronometer、ImageButton、ImageView、ProgressBar、TextView、ViewFlipper、ListView、GridView、StackView、AdapterViewFlipper、ViewStub

自訂 View 完全不在支援範圍內。因此究竟該選 RemoteViews、AIDL 還是 BroadcastReceiver,仍要回歸實際需求來權衡。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved