Go to the previous activity from BroadcastReceiver?

I need to close the current activity from the broadcast receiver. I'm not sure how to name the ending, maybe there is a way to simulate the back key. Any implementation will be fine if it gets the job done.

@Override
public void onReceive(Context context, Intent intent) {
// How can I finish the current activity here?
}

      

+3


source to share


10 replies


In the broadcast receiver write: YourCurrentActivityName.this.finish();

Or you can complete the front activity with this.finish (); so the last open one got stuck in front.


Update: Code for the first case:



Using the broadcast receiver to terminate the background stack:

public class ActivityFirstName extends Activity {

    private BroadcastReceiver mFinishReceiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // other code

        if (mFinishReceiver == null) {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("com.example.ACTION_TERMINATE");// a string to identify your action
            mFinishReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    // How can I finish the current activity here?
                    if ("com.example.ACTION_TERMINATE".equals(intent.getAction())) {
                        ActivityFirstName.this.finish();
                    }
                }
            };
            registerReceiver(mFinishReceiver, intentFilter);
        }

        // other code

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isFinishing()) {
            if (mFinishReceiver != null) {
                unregisterReceiver(mFinishReceiver);
            }
        }
    }

}

      

And front / current work, broadcast sender:

public class ActivitySecondName extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);

        // code code code

        final Button button = (Button) findViewById(R.id.button_id);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Perform action on click
                terminateBackActivities();
            }
        });
    }

    private void terminateBackActivities() {
        Intent i = new Intent("com.example.ACTION_TERMINATE"); // the two action strings MUST be same
        // i.putExtra(...); // to send extra data
        sendBroadcast(i);
    }

}

      

+2


source


You can just call this.finish();



+1


source


Assuming from your comment that BroadcastReceiver is not an inner class of the activity, here's what you should do: Instead of having the broadcast receiver in a separate class, define it inside your activity like this:

private BroadcastReceiver mFinishReceiver = new BroadcastReceiver(){
@Override
    public void onReceive(Context context, Intent intent){
        YourActivity.this.finish();
    }
};

      

Then you will want to register the receiver in onResume () as such:

@Override
public void onResume(){
    super.onResume();
    registerReceiver(mFinishReceiver, new IntentFilter(yourIntentAction));
}

      

You will also want to unregister this receiver in onPause () so you don't miss it:

@Override
public void onPause(){
    super.onPause();
    unregisterReceiver(mFinishReceiver);
}

      

Then you can remove another sink with its own class, and also remove its definition in the manifest. The above example ensures that you can always call finish () without any problem, because the receiver is only registered when the activity starts, since it is internal to the activity class.

EDIT: Change the methods to onCreate () and onDestroy () rather than onPause () and onDestroy (), as per madlymad's comment.

+1


source


the ActivityManager class can give you the current foreground activity (even if it's not an application). The getRunningTasks methods will give you a list of running tasks, the first item in the list will be the most recently started activity. Unfortunately this method will just give you an object of type RecentTaskInfo , not the activity itself, so there is no way to call its finish () method I believe: /

On the other hand, if you want to close the current activity from your application, you can implement a static variable in a personal class that each activist would set in their onResume () method. This way, you will always know which activity is ongoing. But I guess this is not what you are looking for.

Edit: getRunningTasks is for debugging purposes only, as the doc says.

0


source


As suggested in other answers, you can just call finish () an activity in your broadcast receiver code, or you can even trigger the back button by clicking the key event yourself.

this.dispatchKeyEvent(new Keyevent(ACTION_DOWN, KEYCODE_BACK)); 

      

0


source


Not sure if this is helpful to you or not, but its helping me one day and I think this is the same case, so I am in charge of you.

Whenever the receiver of the broadcast receives a call, you can proceed to any action by clicking on that broadcast message.

As well as:

@Override
public void onReceive(Context context, Intent intent) {
    // My Notification Code
    notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
    int icon = R.drawable.app_icon;
    //System.out.println("The ID Number is: "+Long.parseLong(intent.getData().getSchemeSpecificPart()) );
    contentText = intent.getStringExtra("MyMessage");
    System.out.println("The Message is: "+intent.getStringExtra("MyMessage"));
    CharSequence text = "Your tax amount due period";
    CharSequence contentTitle = "Tax Toolbox";

    long when = System.currentTimeMillis();

    intent = new Intent(context, MenuPageActivity.class); // here i am calling activity
    intent.putExtra("sixMonth", "sixMonth");
    intent.putExtra("messageSixMonth", contentText);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    notification = new Notification(icon,text,when);

    long[] vibrate = {0,100,200,300};
    notification.vibrate = vibrate;  // To vibrate the Device

    notification.ledARGB = Color.RED;
    notification.ledOffMS = 300;
    notification.ledOnMS = 300;

    notification.defaults |= Notification.DEFAULT_LIGHTS;
    //notification.flags |= Notification.FLAG_SHOW_LIGHTS;

    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    notificationManager.notify(com.project.TaxToolbox.NotificationConstants.NOTIFICATION_ID_SIX_MONTH, notification);


}

      

Now, in the onCreate () of this activity, you need to determine if this is a call using a notification or not.

As if:

  NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

    System.out.println("The Extra for twoMonth is:  "+getIntent().hasExtra("twoMonth"));
    System.out.println("The Extra for sixMonth is:  "+getIntent().hasExtra("sixMonth"));
    System.out.println("The Extra for EveryMonth is:  "+getIntent().hasExtra("everyMonth"));



    if(getIntent().hasExtra("sixMonth")){
        notificationManager.cancel(NotificationConstants.NOTIFICATION_ID_SIX_MONTH);
        final AlertDialog alert3 = new AlertDialog.Builder(MenuPageActivity.this).create();
        alert3.setTitle("Tax Toolbox");
        alert3.setMessage(getIntent().getExtras().getString("messageSixMonth"));
        alert3.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                return;
            }
        });
        alert3.setIcon(R.drawable.app_icon);
        alert3.show();

      

// here you can do something else or close the activity. }

Not sure, but it might be useful to you.

Feel free to comment if it helps you.

0


source


Try using:

Intent i = new Intent(context,intent.getClass());

      

0


source


Create a generic activity class and extend that generic class to all activities, this way you can have centralized code. Registering the broadcast receiver in the onStart activity and unregistering it in onStop this way will only register one action visible, for broadcast purposes.

Sample code:

public class BaseActivity extends Activity {

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerReceiver(receiver, new IntentFilter(YOUR_INTENT_FILTER)); 
    }
    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onStop()
     */
    protected void onStop(){
        unregisterReceiver(receiver);
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onStart()
     */
    protected void onStart(){
        super.onStart();
        registerReceiver(receiver, new IntentFilter(YOUR_INTENT_FILTER)); 
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {

        /*
         * (non-Javadoc)
         * 
         * @see
         * android.content.BroadcastReceiver#onReceive(android.content.Context,
         * android.content.Intent)
         */
        @Override
        public void onReceive(Context context, Intent intent) {
            onBackPressed();//on back pressed simply calls finish()
        }
    };
} // End of BaseActivity 
// End of File

      

0


source


Place finish();

after u has completed all tasks in the onReceive()

class BroadcastReceiver

as shown below:

 @Override
 public void onReceive(Context context, Intent intent) {
    // Do all the tasks onReceive of BroadCast Receiver
    finish(); // This finishes the current activity here....   
}

      

0


source


Follow instructions from gezdy on How to get the current foreground activity context in android? so that you can get a link to the current activity from anywhere in the application.

From there, you can call .finish () to close the current activity.

0


source







All Articles