aneela
aneela

Reputation: 1619

Starting An Activity From BroadCast Receiver

My app is consisted of many activities and a BraodcastReceiver. I want to restart an activity if it is on foreground when my app receives the broadcast Intent.How can I implement it?

Upvotes: 1

Views: 982

Answers (2)

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132992

use Intent.FLAG_ACTIVITY_REORDER_TO_FRONT to launch activity to be brought to the front of its task's history stack if it is already running and if not then start as new one. to make confirm if Activity is running or not use ActivityManager

    @Override
        public void onReceive(Context context, Intent intent) {
            //start activity
            if(isRunning(context)){

             Intent i = new Intent(context,Your_Activity_Name.class);
             i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
             context.startActivity(i);
            }
           else{
                 // Activity not available in activity stack
            }
        }

  public boolean isRunning(Context ctx) {
        ActivityManager activityManager = (ActivityManager) 
                         ctx.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = 
                      activityManager.getRunningTasks(Integer.MAX_VALUE);

        for (RunningTaskInfo task : tasks) {
            if (ctx.getPackageName().equalsIgnoreCase(
                                     task.baseActivity.getPackageName())) 
                return true;                                  
        }

        return false;
    }

and also set android:noHistory AndroidManifest.xml to store Activity in activity stack no longer visible on screen :

<activity
       android:noHistory="false"
       android:name=".Your_Activity" />

Upvotes: 2

Nikolay Elenkov
Nikolay Elenkov

Reputation: 52966

Make the activity singleTop and just send the intent.

Upvotes: 0

Related Questions