編輯:關於 Android 程式設計
先前談過以 AIDL 達成跨進程更新 UI,這個傳統做法可行,但缺點相當明顯:
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 天生就是為跨進程更新 UI 而設計,內部封裝了許多可用方法,但它並非萬能——目前支援的版面與控制項相當有限。
支援的 Layout:FrameLayout、LinearLayout、RelativeLayout、GridLayout
支援的 View:AnalogClock、Button、Chronometer、ImageButton、ImageView、ProgressBar、TextView、ViewFlipper、ListView、GridView、StackView、AdapterViewFlipper、ViewStub
自訂 View 完全不在支援範圍內。因此究竟該選 RemoteViews、AIDL 還是 BroadcastReceiver,仍要回歸實際需求來權衡。
Android Parcelable 完全解析:讓自訂物件能跨越 Activity 傳遞
在 Android 裡,如果你想把自訂物件透過 Intent 從一個 Activity 傳到另一個 Activity,就必須讓該物件實作 Parcelable 介面。Pa
仿 RadioGroup 打造可複用的單選卡片容器(以底部導航/Tab 為例)
需求很直觀:一排四張樣式相同、內容不同的卡片,同一時間只能有一張處於選中狀態,選中後回傳對應的金額。圖上只是示意效果,實際資料要從伺服器拉回來再灌進控制項。 先盤點幾種
Android 客戶端註冊與登入實作詳解(上)
開發 Android App 幾乎一定會跟伺服器打交道,其中帳號的註冊與登入更是必備技能。本文聚焦「客戶端如何向伺服器發起註冊請求」,伺服器端收到請求後的處理不在討論範圍
Android UI 技巧:ActionBar 隨 ScrollView 滾動產生透明度漸變
近年許多應用會讓 ActionBar 的背景透明度隨著 ScrollView 滾動而改變,這種效果能提升畫面層次感,也能讓使用者更清楚目前內容的位置。 實作思路 核心概念