android之app widget(三)

來源:互聯網
上載者:User

    1. 接受來自App Widget的廣播

     //Androidmanifest中的檔案旨要,只要有個一action符合就會調用繼承AppWidgetProvider的類:

      <receiver android:name="繼承AppWidgetProvider的類">

     <intent-filter>

        <action android:name="android.appwidget.action.APPWIDGET_UPDATA"/>

       </intent-filter>

       <intent-filter>

        <action android:name="mars.appwidget03.UPDATE_APP_WIDGET"/>      //這是自訂action

       </intent-filter>

       <meta-data android:name="android.appwidget.provider"

          android:resource="@xml/example_appwidget_info"/>

       </receiver>

    //在代碼中繼承AppWidgetProvider的類的程況如下:

     A. 在Update方法中

     Intent intent = new Intent();

     intent.setAction("mars.appwidget03.UPDATE_APP_WIDGET");

       使用getBroadcast方法得到PendingIntent對象

     PendingIntent pendingIntent = PendingIntent.getBroadcast(contect,0,intent對象,0);

       B. 再onReciever方法中接收步驟A發送的廣播

    

    2. 更新App Widget當中控制項的狀態

    public void onReceive(Context context, Intent intent){

    String action = intent.getAction();

    if(action == "mars.appwidget03.UPDATE_APP_WIDGET"){

      RemoteViews remoteViews = new RemoteViews(context.getPackage , R.layout.example_appwidget);

      //修改圖片

      remoteViews .setImageViewResource(R.id.imageId , R.drawable.ku);

      remoteViews 。setTextViewText(R.id.widgetTextId , "");

      //獲得AppWidgetManager 對象

      AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

      //ComponentName指的是整個app widget控制項 , 而RemoteViews指的是app widget裡面的控制項

      ComponentName componentName = new ComponentName(context, ExampleAppWidgetProvider.class);

      //更新appwidget

      appWidgetManager .updateAppWidget(componentName , remoteViews);

        }

        //必須要有else語句,不然其他的onUpdate,onEnable等函數將不會調用

        else{

        super onReceive(context,intent);

          }

      }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.