編輯:關於 Android 程式設計
什麼是 RemoteViews?顧名思義就是「遠程 View」。需要注意的是,RemoteViews 並不是 View 的子類,它直接繼承自 Object。它的核心能力是「跨進程更新介面」,聽起來就很強大。實際應用中,它主要出現在通知欄與桌面小工具上。本文就以通知欄為例,帶大家完整剖析。


先定義兩個按鈕,分別用來發送不同的通知。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="普通通知" />
<Button
android:id="@+id/btn_zdy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="自定義通知" />
</LinearLayout>
先看普通通知的 Java 程式碼:
case R.id.btn_normal:
// 1. 創建通知對象
Notification nf = new Notification();
// 2. 通知的常用設置
nf.icon = R.drawable.ic_launcher; // 圖標
nf.when = System.currentTimeMillis(); // 通知時間
nf.tickerText = "這是普通的通知";
nf.flags = Notification.FLAG_AUTO_CANCEL;
// 3. 創建延時意圖
Intent intent = new Intent(this, NormalNotificationActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
nf.setLatestEventInfo(this, "普通通知", "這是來自普通通知的摘要信息", pi);
// 4. 創建 NotificationManager 對象
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// id 最好每次都不同,否則第二次發送無效
nm.notify(nId++, nf);
break;
這只是一個簡單的通知,尚未涉及 RemoteViews,主要用來理解普通通知的書寫方式。
再來看自定義通知:
case R.id.btn_zdy:
Notification myNf = new Notification();
myNf.icon = R.drawable.ic_launcher;
myNf.when = System.currentTimeMillis();
myNf.tickerText = "這是自定義的通知";
myNf.flags = Notification.FLAG_AUTO_CANCEL;
Intent myIntent = new Intent(this, NormalNotificationActivity.class);
PendingIntent myPi = PendingIntent.getActivity(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// 4. 創建 RemoteViews
RemoteViews rv = new RemoteViews(getPackageName(), R.layout.activity_mynotification);
rv.setTextViewText(R.id.msg, "我是自定義通知");
rv.setTextViewText(R.id.des, "我是對自定義通知的一些簡單描述信息");
// contentView 與 contentIntent 必須同時設置,否則會報錯
myNf.contentView = rv;
myNf.contentIntent = myPi;
// 5. 創建 NotificationManager 對象
NotificationManager myNm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
myNm.notify(nId++, myNf);
break;
自定義通知有兩個關鍵點必須注意:一是 contentView 與 contentIntent 必須同時賦值,少一個就會拋出 contentIntent required 的異常;二是 notify() 的第一個參數不要設為常量,否則只能發送一則通知。
RemoteViews 能跨進程更新 UI,本質是透過 Binder,因此它必然實作了序列化介面:
public class RemoteViews implements Parcelable, Filter
那麼它如何自定義文字內容呢?大部分都透過 setTextViewText() 這類方法完成:
public void setTextViewText(int viewId, CharSequence text) {
setCharSequence(viewId, "setText", text);
}
public void setCharSequence(int viewId, String methodName, CharSequence value) {
addAction(new ReflectionAction(viewId, methodName, ReflectionAction.CHAR_SEQUENCE, value));
}
注意這裡的第二個參數是 setText,跟 TextView 的 setText() 如出一轍。它被包裝成一個 ReflectionAction(反射動作),並透過 addAction() 加入 mActions 集合。
private void addAction(Action a) {
if (mActions == null) {
mActions = new ArrayList();
}
mActions.add(a);
a.updateMemoryUsageEstimate(mMemoryUsageCounter);
}
Action 是所有可對填充後檢視執行動作的基底類別,實作了 Parcelable 介面。簡單來說,setTextViewText() 會先把操作封裝成一個 Action,再放進 actions 集合中。
真正把這些 Action 落地執行的,是 apply() 方法:
public View apply(Context context, ViewGroup parent, OnClickHandler handler) {
RemoteViews rvToApply = getRemoteViewsToApply(context);
Context c = prepareContext(context);
LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater = inflater.cloneInContext(c);
inflater.setFilter(this);
View result = inflater.inflate(rvToApply.getLayoutId(), parent, false);
rvToApply.performApply(result, parent, handler);
return result;
}
private void performApply(View v, ViewGroup parent, OnClickHandler handler) {
if (mActions != null) {
final int count = mActions.size();
for (int i = 0; i < count; i++) {
Action a = mActions.get(i);
a.apply(v, parent, handler);
}
}
}
它先 inflate 出版面,再遍歷 mActions 逐一執行 apply()。由於先前加入的是 ReflectionAction,因此這裡執行的是它的 apply(),核心就是透過反射呼叫對應方法:
@Override
public void apply(View root, ViewGroup rootParent, OnClickHandler handler) {
final View view = root.findViewById(viewId);
if (view == null) return;
Class param = getParameterType();
Class klass = view.getClass();
Method method = klass.getMethod(this.methodName, getParameterType());
method.invoke(view, this.value);
}
方法名先前已經透過 setText 傳入,這裡只要 invoke 即可。這就是 RemoteViews 的大致流程。
建立兩個應用,一個作為本地、一個作為遠程。若想在單一應用中實現,也可在 AndroidManifest 中為某個 Activity 加上 android:process=":remote" 讓它跑在獨立進程。這裡為了效果明顯,採用兩個應用。通知欄的跨進程是透過 Binder 實現,本例則改用廣播接收者來傳遞。
本地布局中準備一個 LinearLayout 用來承載從遠程傳來的版面:
public class MainActivity extends Activity {
private LinearLayout ll_layout;
private BroadcastReceiver mRemoteViewsReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
RemoteViews remoteViews = intent.getParcelableExtra("remoteViews");
if (remoteViews != null) {
updateLayout(remoteViews);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll_layout = (LinearLayout) findViewById(R.id.ll_layout);
filter = new IntentFilter("com.lw.remoteviewstest1");
registerReceiver(mRemoteViewsReceiver, filter);
}
protected void updateLayout(RemoteViews remoteViews) {
View view = remoteViews.apply(this, ll_layout);
ll_layout.addView(view);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mRemoteViewsReceiver != null) {
unregisterReceiver(mRemoteViewsReceiver);
}
}
}
重點在於:收到 RemoteViews 後呼叫 apply() 得到一個 View,再把它加入本地版面。
public void send(View view) {
// 創建 RemoteViews
RemoteViews rv = new RemoteViews(getPackageName(), R.layout.activity_notification);
// 為延時意圖中的按鈕設置點擊事件
Intent sendIntent = new Intent(this, SecondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, sendIntent, PendingIntent.FLAG_UPDATE_CURRENT);
rv.setOnClickPendingIntent(R.id.btn_toast, pendingIntent);
// 將 RemoteViews 帶到另一個應用
Intent intent = new Intent("com.lw.remoteviewstest1");
intent.putExtra("remoteViews", rv);
sendBroadcast(intent);
}
要為 RemoteViews 添加點擊事件,必須使用 PendingIntent。它最終仍是透過添加 Action 來實現,只不過這裡的 Action 是 SetOnClickPendingIntent 而非反射 Action,其 apply() 最後會呼叫 setOnClickListener()。
整體思路總結:遠程透過 Intent 攜帶 RemoteViews 傳到本地,本地取得後呼叫 apply() 得到 View,再將這個 View 添加到本地對應的版面容器中,即可完成跨進程的 UI 更新。
WebView小案例:動手做一個有道詞典查詢工具
近來在學 WebView 元件,順手做了一個有道詞典的小範例:輸入單字、點擊按鈕,頁面就在 WebView 裡載入對應的查詢結果。做法很簡單,記錄下來給大家參考。 效果預
用 ListView 打造自定義表格:動態列、單元格合並與自定義鍵盤
要解決的三個問題 1. 列數不固定:根據數據源動態生成不同列數; 2. 支持按數據定義合並單元格; 3. 可填寫的單元格能自由選擇自定義鍵盤或系統鍵盤。 圍繞這三點做了
Android 安全實戰:用 Xposed Hook 攔截 App 的帳號與密碼
Xposed 能 Hook 幾乎所有 Java 方法,是分析 App 行為的利器。本文示範如何攔下一個 App 登入時輸入的帳號與密碼(請先確保 Xposed 環境已就緒
Android 自定義 View 實戰:從繪製流程到屬性封裝的完整路線
Android 為開發者準備了大量現成的 UI 元件——TextView、Button、ImageView,再加上 LinearLayout、RelativeLayout