android學習記錄(十八)---AppWidget顯示內容隨資料改變而更新

來源:互聯網
上載者:User

標籤:android   appwidget   即時更新   android學習記   

我們知道,appWidget可通過設定widgetinfo中的updateTimeMillies設定更新的間隔,那麼,當我們需要即時進行更新的時候呢?該如何進行appWidget顯示內容的更新?如行程應用中添加了新的行程,想立刻在appWidget顯示內容更新。

如何?

我們知道,widgetProvider本質上就是一個廣播接收器,所以我們可以在資料修改處發送一個與之符合的廣播。

當我們的intent並沒附帶任何額外資料,只定義了action的時候,會調用WidgetProvider中的onReceive方法。

那麼我們就簡單的實現以下資料即時更新:

發送廣播:

public void addData(Context context){    add....();    updateWidget(context)}//發送廣播,使appWidget更新private void updateWidget(Context context) {    Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);      context.sendBroadcast(intent);}

YourAppWidgetProvider代碼:

@Overridepublic void onReceive(Context context, Intent intent) {        super.onReceive(context, intent);        final AppWidgetManager mgr = AppWidgetManager.getInstance(context);        final ComponentName cn = new ComponentName(context, EventWidgetProvider4x2.class);        mgr.notifyAppWidgetViewDataChanged(mgr.getAppWidgetIds(cn), R.id.widget4x2LV);}

我又好奇什麼時候會調用AppWidgetProvider的onUpdate呢?

查看AppWidgetProvider部分源碼:

  public void onReceive(Context context, Intent intent) {               String action = intent.getAction();        if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {            Bundle extras = intent.getExtras();            if (extras != null) {                int[] appWidgetIds = extras.getIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS);                if (appWidgetIds != null && appWidgetIds.length > 0) {                    this.onUpdate(context, AppWidgetManager.getInstance(context), appWidgetIds);                }            }        }…

即只有在intent中含有extras且key為AppWidgetManager.EXTRA_APPWIDGET_IDS的值不為空白時調用。
當我們的廣播不含有這個extras的時候,onReceive會調用,onUpdate不會。

隨時歡迎各路好漢能發表見解,想法值得分享~

android學習記錄(十八)---AppWidget顯示內容隨資料改變而更新

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.