6

I'm trying to bring my app from background to foreground. In onHandleIntent() of my custom IntentService class, I have:

Intent intent = new Intent();
intent.setClass(getApplicationContext(), MainActivity.class); // Also tried with "this" instead of getApplicationContext()
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER); 
startActivity(intent);

Now this code works at first sight but I found a scenario where it doesn't work. If you have the app opened and you put it to background via home button and execute startActivity() within ~5 second, there will be a delay before your app will come to foreground. This is a known implementation and you can find the topic discussed on stackoverflow. In this scenario, the app succeeded in coming from background to foreground.

If you repeat the same experiment above, but instead of waiting for the app to come to foreground, go browse (scroll, swipe, etc) around your phone (I was browsing around the google playstore). The result is that startActivity() will get called but the app will not come to the foreground.

I'm not asking for a solution but more of an explanation on why this is happening. Is this intended behavior?

kyrax
  • 1,192
  • 3
  • 13
  • 29
  • How do you know that startActivity() is getting called? Can you provide the AndroidManifest.xml code for the activity? – kmaini Oct 14 '15 at 20:57
  • I had a debug print after it. Whatever happens inside of `startActivity()`, I am not sure. The only property in the manifest regarding this activity that I am suspicious of is `android:launchMode="singleTask"` – kyrax Oct 14 '15 at 21:06

3 Answers3

0

Use the context of your class. For instance :

Intent intent= new Intent(context, other.class)

Instead of getapplicationContext()

jose
  • 25
  • 3
0

Use the code :

 private void startMenuActivity() {
        Intent i = new Intent(this, MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
        finish();
    }
young_08
  • 1,196
  • 2
  • 13
  • 35
  • 1
    OP has stated that he is calling this code from a `Service`. In that case, calling `finish()` isn't possible. Also, your code isn't significantly different from the code OP is already using. Also, OP wants to bring his existing task from the background to the foreground, `FLAG_ACTIVITY_CLEAR_TOP` only controls which `Activity` would be shown. Nothing in this answer will help solve the problem. – David Wasser Oct 16 '15 at 15:14
0

the below code works for me,

    val login = Intent(applicationContext, SignInActivity::class.java)
    login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
    login.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    applicationContext.startActivity(login)        
Prasanna Narshim
  • 778
  • 10
  • 14