2

I have a BroadcastReceiver that receives a push notification, I then start an activity and show a notification. (notice that the activity is not started when the user actions the notification)

My intention is to start the activity in "background mode" and then when the user responds to the notification bring the activity to the front.

All is working perfectly except that the activity briefly shows and then immediately hides. (flashing activity for a second).

Here is my code:

BroadcastReceiver...
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("BACKGROUND",true);
        context.startActivity(intent);


MainActivity.....
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getIntent().getBooleanExtra("BACKGROUND",false)) {
            moveTaskToBack(true);
        } else {

        }
Wayne
  • 3,359
  • 3
  • 30
  • 50

2 Answers2

3

Had the same problem. Solved by adding android:windowDisablePreview attribute in your theme.

For example, in your res/values/styles.xml:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="android:windowDisablePreview">true</item>
    </style>

</resources>

Not sure if there is any way to add it programatically though.

ianyuhsunlin
  • 101
  • 1
  • 3
  • this is a great solution. – jaaaawn Jun 09 '16 at 09:38
  • android:windowDisablePreview is not recommended, because it slows down the Activity start time; also, if the Activity itself needs some time to open (such as when it loads a site), the user won't see anything until it has finished. See https://developer.android.com/topic/performance/vitals/launch-time It might be that the OP doesn't mind this in his scenario. But a better way is by using a service, see my answer below. – VSim Sep 16 '18 at 08:58
0

Had the same problem.
Solved it by starting a service which then opens the Activity when it's needed. This is the recommended way to do it.

VSim
  • 161
  • 3
  • 10