moveTaskToBack in onCreate causes activity to show

2019-05-31 00:52发布

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 {

        }

2条回答
【Aperson】
2楼-- · 2019-05-31 01:27

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.

查看更多
在下西门庆
3楼-- · 2019-05-31 01:41

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.

查看更多
登录 后发表回答