第三章--與Widget的愛恨情仇

Widget就是平時所說的桌面小部件,可以很方便的在桌面上進行操作,但是本質(zhì)上它是一個廣播接收器。直接看代碼。

public class TestWidget extends AppWidgetProvider{
    public static final String WIDGET_BUTTON = "widget_button";
    @Override
    //接收廣播
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
    }
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);
}

點進AppWidgetProvider,可以看到它是繼承BroadcastReceiver的。onUpdate()在用戶把小部件拖到桌面,創(chuàng)建Widget實例時會調(diào)用。onReceive()在接收廣播的時候會被調(diào)用。所以在使用Widget的時候應(yīng)該在AndroidManifest中注冊.。且由于當(dāng)程序開始的時候就監(jiān)聽,所以采用靜態(tài)注冊。

<receiver android:name=".TestWidget">
            <!--將該BroadcastReceiver當(dāng)成桌面控件-->
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
            </intent-filter>
            <!--指定桌面控件的meta-data-->
            <meta-data android:name="android.appwidget.provider"
                android:resource="@layout/widget_setting"/>
        </receiver>
  1. action里面表示接收系統(tǒng)發(fā)來的有關(guān)這個app的所有widget的消息。
  2. meta-data 指定了對應(yīng)的資源文件。name 是指定metadata名,
    resource是指定對應(yīng)的資源路徑。那我們就把指定的資源文件貼出來。
<appwidget-provider
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:initialLayout="@layout/layout_widget"
    android:minHeight="140dp"
    android:minWidth="140dp"
    android:previewImage="@drawable/smile"
    android:updatePeriodMillis="2000"
    android:widgetCategory="home_screen"
    >

</appwidget-provider>

簡單解釋一下:

  • initialLayout : 加載到桌面時對應(yīng)的布局文件
  • minWidth : 最小寬度
  • minHeight : 最小高度
  • previewImage : 預(yù)覽圖片
  • updatePeriodMillis : 更新widget的時間間隔(ms)
  • widgetCategory : widget可以被顯示的位置。home_screen表示可以將widget添加到桌面,keyguard表示widget可以被添加到鎖屏界面。

加載在桌面的布局文件如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/widget_text_View"
        android:layout_gravity="center_horizontal"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/wighet_button"
        android:layout_gravity="center_horizontal"/>
</LinearLayout>

第一個注意的地方,widget支持的控件有限,基本上包括以下幾種:AnalogClock、Button、Chronometer、ImageButton、ImageView、ProgressBar、TextView、ViewFlipper、ListView、GridView、StackView、AdapterView、Flipper。其他就顯示不出來
前面準備工作做的差不多了,現(xiàn)在就是加載布局文件了。利用RemoteViews可以直接加載整個布局文件。在onUpdate()中的代碼如下

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);
        Log.i(TAG, "onUpdate");
        //指定加載的頁面布局文件
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.layout_widget);
        Intent intent = new Intent();
        intent.setClass(context, TestWidget.class);
        intent.setAction(WIDGET_BUTTON);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);    remoteViews.setOnClickPendingIntent(R.id.wighet_button, pendingIntent);
        //
        appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
    }

為Button設(shè)置點擊事件是remoteViews.setOnClickPendingIntent(R.id.wighet_button, pendingIntent);傳入的第一參數(shù)是Button的id,第二個是PendingIntent,,我的理解是不立即執(zhí)行的意圖。現(xiàn)在是想點擊了Button然后發(fā)送廣播,在onReceive()中更新TextView的內(nèi)容。

    @Override
    //接收廣播
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        Log.i(TAG, "onReceive");
        if (intent != null && TextUtils.equals(intent.getAction(), WIDGET_BUTTON)){
            Log.i(WIDGET_BUTTON, "I am clicked");
            RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.layout_widget);
            //設(shè)置文字的內(nèi)容
            remoteViews.setTextViewText(R.id.widget_text_View, "be clicked");

            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
            //將AppWidgetProvider的子類實例包裝成ComponentName
            ComponentName componentName = new ComponentName(context, TestWidget.class);

            appWidgetManager.updateAppWidget(componentName, remoteViews);

        }
    }

第二個注意的地方,RemoteViews 絕對不能復(fù)用,據(jù)說Binder data size limit is 512k,由于傳輸?shù)絘ppWidget進程中的Binder最大數(shù)據(jù)量是512K,并且RemoteView也不會每次清理, 所以如果每次都使用同一個RemoteView進行傳輸會因為溢出而報錯。所以必須每次重新建一個RemoteView來傳輸。
這樣一來一去,基本上就實現(xiàn)了一個可以操作的widget。如果想接收其他地方發(fā)的廣播,需要在AndroidManifest中注冊,然后在onReceive()中進行相關(guān)操作。
此時應(yīng)該有圖,但是圖不見了,自行腦補一個TextView下有個Button。


當(dāng)綁定多個Button或者view設(shè)置點擊事件的時候,如果只是設(shè)置Intent的Action不同,好像不能分辨,就是所有的按鈕都是一個功能,我的做法是將PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);的第二個參數(shù)設(shè)置的不同,這樣就可以分辨。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容