簡體   English   中英

從清單中注冊的廣播接收器更新UI

[英]Update UI from a broadcast receiver registered in the manifest

我有這個問題,我正在清單中為AlarmManager注冊我的廣播接收器。 我正在通過待處理的Intent在我的Activity中安排它。

    AlarmManager alarmMgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingIntent =PendingIntent.getBroadcast(this, 0, new Intent(this, AlarmReciever.class),PendingIntent.FLAG_CANCEL_CURRENT);
    alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, Constants.ALARM_TRIGGER_AT_TIME,Constants.ALARM_INTERVAL, pendingIntent);

但在我的接收器類中,我正在使用AlarmManager進行一些網絡更新...我將其保存在數據庫中。 我在活動中有一個ListAdapter,需要notifydatasetChanged ...我需要一個我的活動實例。

怎么弄? 基本上我想至少在我的應用程序可見時更新我的​​UI。

在你的活動中創建一個BroadcastReceiver在你的活動的onResume中注冊它,並在onPause注銷它。完成網絡更新后,創建一個Intent ,輸入你要發送到你的活動的所有數據並解雇它。如果你的活動在前台,然后只有它才會收到此意圖。從您活動中的BroadcaseReceiver onReceive() ,您可以獲取所有數據,然后更新Ui。

在你的Activity中創建一個BroadcastReceiver ::

 private class MyReceiver extends BroadcastReceiver
{
        @Override
        public void onReceive(Context context, Intent intent) {

             /////// update your UI from here ////////     
            }

}

onCreate()里面,創建一個這個接收器的實例::

myReceiver=new MyReceiver();

OnResume()注冊此接收器::

    IntentFilter filter=new IntentFilter();
    filter.setPriority(1);
    filter.addAction( "MyPackageName.MyAction" );
    registerReceiver(myReceiver, filter);

onPause()重新啟用它::

unregisterReceiver( myReceiver );

現在,在完成網絡更新后觸發一個意圖啟動此接收器::

            Intent broadcastIntent=new Intent();
            broadcastIntent.setAction( "MyPackageName.MyAction" );
            broadcastIntent.putExtra();// put data to send to your activity
            sendBroadcast( broadcastIntent );

我得到了答案。為了讓我的活動更加清晰可見

        Intent i=new Intent(caller,Dot.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        caller.startActivity(i);

如果活動可見,它將調用代碼中的OnNewIntent(),從而調用onResume(),您可以在其中更新UI。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM