android widget

什么是AppWidget?AppWidget就是我們平常在桌面上見到的那種一個個的小窗口,利用這個小窗口可以給用戶提供一些方便快捷的操作。

創建簡單的AppWidget

  1. 添加AppWidgetProviderInfo Metadata
    在res文件夾下新建一個名字為xml的文件夾,然后在xml目錄下創建一個名為appwidget.xml的文件:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="200dp"
    android:minHeight="100dp"
    android:updatePeriodMillis="0"
    android:previewImage="@drawable/cd01"
    android:initialLayout="@layout/widget_layout">
</appwidget-provider>
  1. 為appwidget定義layout
    在layout文件夾下面新建一個widget_layout.xml文件,在這個文件中描述了appWidget的控件和布局等等信息:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">
        <TextView
            android:id="@+id/widget_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="widget"/>

        <Button
            android:id="@+id/widget_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="button"/>
</LinearLayout>
  1. 創建AppWidgetProvider的子類
public class MyWidgetProvider extends AppWidgetProvider {
    public static final String BROADCAST_STR = "com.kevinwang.widget";
    public static final String MY_WIDGET_PROVIDER = "MyWidgetProvider";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(MY_WIDGET_PROVIDER,"==onReceive()==");
        super.onReceive(context,intent);
        //接受廣播事件
        if (intent != null && TextUtils.equals(intent.getAction(), BROADCAST_STR)) {
            //只能通過遠程對象來設置appwidget中的控件狀態
            RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
            //通過遠程對象將textView的文字設置為”hello”
            remoteViews.setTextViewText(R.id.widget_text, "hello");

            //獲得appwidget管理實例,用于管理appwidget以便進行更新操作
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
            //獲得所有本程序創建的appwidget
            ComponentName componentName = new ComponentName(context,MyWidgetProvider.class);
            //更新appwidget
            appWidgetManager.updateAppWidget(componentName, remoteViews);
        }
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        //到達指定的更新時間或者當用戶向桌面添加AppWidget時被調用
        Log.i(MY_WIDGET_PROVIDER,"==onUpdate()==");
        super.onUpdate(context, appWidgetManager, appWidgetIds);
        //創建一個Intent對象
        Intent intent = new Intent();
        intent.setClass(context, MyWidgetProvider.class);
        intent.setAction(BROADCAST_STR);

        //設置pendingIntent
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
        //Retrieve a PendingIntent that will perform a broadcast
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);

        //為button按鈕綁定一個事件便于發送廣播
        remoteViews.setOnClickPendingIntent(R.id.widget_btn,pendingIntent);
        appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
    }

    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        //刪除一個AppWidget時調用
        Log.i(MY_WIDGET_PROVIDER,"==onDelete()==");
        super.onDeleted(context, appWidgetIds);
    }

    @Override
    public void onEnabled(Context context) {
        //AppWidget的實例第一次被創建時調用
        Log.i(MY_WIDGET_PROVIDER,"==onEnabled()==");
        super.onEnabled(context);
    }

    @Override
    public void onDisabled(Context context) {
        //刪除一個AppWidget時調用
        Log.i(MY_WIDGET_PROVIDER,"==onDisabled()==");
        super.onDisabled(context);
    }
}
  1. 在AndroidManifest中進行聲明
        <receiver android:name=".MyWidgetProvider">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
            </intent-filter>
            <meta-data android:name="android.appwidget.provider"
                       android:resource="@xml/appwidget"/>
        </receiver>

可以看到在配置文件里面定義了一個receiver,它的名字是上面創建處理控件代碼的那個類。
intent-filter中的action是系統自帶的用于更新所有appwidget的廣播動作。
meta-data標簽是一個描述我們創建appwidget的元數據,其中的android:name="android.appwidget.provider"是固定的,
android:resource="@xml/appwidget"指定創建的appWidget的布局信息。這樣程序就知道到哪里去初始化這些appWidget啦。

AppWidget與程序交互
appwidget運行的進程和我們創建的應用不在一個進程中,所以我們也就不能像平常引用控件那樣來獲得控件的實例。這個時候就需要用到RemoteViews。

RemoteViews,顧名思義,它是一個遠程視圖。App Widget中的視圖,都是通過RemoteViews表現的。

RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
//為button按鈕綁定一個事件便于發送廣播
remoteViews.setOnClickPendingIntent(R.id.widget_btn,pendingIntent);

上面出現的pendingIntent又是用來做什么的呢?PendingIntent可以看作是對Intent的一個封裝,但它不是立刻執行某個行為,而是把PendingIntent放入一個新的進程。通過觸發事件去觸發這個PendingIntent。如果我們把Intent看成一封信,那么PendingIntent就是一封被信封包裹起來的信。這封信在remoteViews.setOnClickPendingIntent()中被“郵寄”到了appwidget, 當appwidget中的按鈕單擊時他知道將這封信打開,并執行里面的內容。

     //創建一個Intent對象
     Intent intent = new Intent();
     intent.setClass(context, MyWidgetProvider.class);
     intent.setAction(BROADCAST_STR);

     //設置pendingIntent
     PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

在onUpdate方法中為AppWidget綁定事件

 public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
     //到達指定的更新時間或者當用戶向桌面添加AppWidget時被調用
     //創建一個Intent對象
     Intent intent = new Intent();
     intent.setClass(context, MyWidgetProvider.class);
     intent.setAction(BROADCAST_STR);

     //設置pendingIntent
     PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
     //Retrieve a PendingIntent that will perform a broadcast
     RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);

     //為button按鈕綁定一個事件便于發送廣播
     remoteViews.setOnClickPendingIntent(R.id.widget_btn,pendingIntent);
     //更新Appwidget
     appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
     super.onUpdate(context, appWidgetManager, appWidgetIds);
 }

在onReceive中接受廣播并更新AppWidget

 public void onReceive(Context context, Intent intent) {
     //接受廣播事件
     if (intent != null && TextUtils.equals(intent.getAction(), BROADCAST_STR)) {
         Log.i("onReceive()", "enter if block!");
         //只能通過遠程對象來設置appwidget中的控件狀態
         RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
         //通過遠程對象將textView的文字設置為”hello”
         remoteViews.setTextViewText(R.id.widget_text, "hello");

         //獲得appwidget管理實例,用于管理appwidget以便進行更新操作
         AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
         //獲得所有本程序創建的appwidget
         ComponentName componentName = new ComponentName(context,MyWidgetProvider.class);
         //更新appwidget
         appWidgetManager.updateAppWidget(componentName, remoteViews);
     }
     else {
         super.onReceive(context,intent);
     }
 }

AppWidget的生命周期
當我們添加AppWidget時


點擊其中的按鈕時

移除控件時

從上面的結果中可以看出,AppWidgetProvider的其它4個生命周期函數的執行都是由onReceiver分發下去的。

在AppWidgetProvider實現中已經對接收到的
ActionAppWidgetManager.ACTION_APPWIDGET_UPDATE,
AppWidgetManager.ACTION_APPWIDGET_DELETED,
AppWidgetManager.ACTION_APPWIDGET_ENABLED以及
AppWidgetManager.ACTION_APPWIDGET_DISABLED做了處理,分別執行onUpdate()/ onDeleted() / onEnabled() / onDisabled()。

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

推薦閱讀更多精彩內容