简体   繁体   中英

Update UI from a broadcast receiver registered in the manifest

I have this problem that I'm registering my Broadcast receiver for AlarmManager in the manifest. And I'm scheduling it in my Activity through pending Intent.

    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);

But in my receiver class I'm doing some network updates using AlarmManager...which I'm saving in a database. I have a ListAdapter in the activity and need to notifydatasetChanged...for which I need an instance of my activity.

How to get it? Basically I want to update my UI at least when my app is visible.

create a BroadcastReceiver in your activity, register it inside the onResume of your activity and unregister it in onPause .After completing the network update , create an Intent , put in all the data that you want to send to your activity and fire it.If your activity is in foreground then only it will receive this intent.From onReceive() of BroadcaseReceiver in your activity you can get all the data and then update the Ui.

create a BroadcastReceiver In your Activity ::

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

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

}

Inside onCreate() , create an instance of this receiver ::

myReceiver=new MyReceiver();

Register this receiver from OnResume() ::

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

unreigister it in onPause() ::

unregisterReceiver( myReceiver );

Now, Fire an intent after completing network update fire an intent to start this receiver ::

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

I got the answer..For refreshing my activity which is visible

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

If activity visible it will call the OnNewIntent() in your code and thus onResume() where you can update Your UI..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM