-1

How do I check if an activity is running already and if so, restart the activity?

Currently, I'm using this code to start the activity. However, if the activity NewActivity is already running, I would like to restart it (or send a broadcast)?

Intent intent = new Intent(this, NewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(EXTRA_STRING, true);
startActivity(intent);
return;
Jignasha Royala
  • 1,032
  • 10
  • 27
  • You should not do so, if there is no such specific requirement. Instead declare the `launchMode` of activity to `singleTop` and receive updated intent in `onNewIntent()`method and update existing Activity. – Paresh P. Apr 16 '18 at 10:14
  • Great. Didn't know we could do that. I'll try doing that. Thanks! :) – Ashim Neupane Apr 16 '18 at 10:18

2 Answers2

1

If NewActivity is already running then simply use this trick to restart.

 Intent intent = new Intent(this, NewActivity.class);
 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 intent.putExtra(EXTRA_STRING, true);
 finish();
 startActivity(intent);

Better you can follow this: How do I restart an Android Activity

Faysal Ahmed
  • 7,501
  • 5
  • 28
  • 50
  • finish() wouldn't work since I'm not starting the activity from NewActivity itself. The NewActivity is being started from a Service. – Ashim Neupane Apr 16 '18 at 10:13
1

if your current activity is NewActivity and you want to restart it self than use

recreate();

If currently any other activity is on foreground than use

 Intent intent = new Intent(this, NewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
 intent.putExtra(EXTRA_STRING, true);
startActivity(intent);
 finish();

FLAG_ACTIVITY_CLEAR_TASK will clear all other activities available in activity stack, whereas FLAG_ACTIVITY_NEW_TASK will start a new task for you NewActivity

Jyot
  • 540
  • 5
  • 17