从锁定屏幕启动时,Android Activity 会打开两次

Posted

技术标签:

【中文标题】从锁定屏幕启动时,Android Activity 会打开两次【英文标题】:Android activity opens twice when starting from lock screen 【发布时间】:2020-06-18 11:14:54 【问题描述】:

各位,上周我尝试了一些 android 开发,但目前遇到以下错误:我正在后台运行一个带有服务的计时器。时间到了,即使手机处于锁定状态,也应打开活动。使用以下代码,虽然没有锁定一切都很好。但是从锁定屏幕打开时,它总是会打开两次.. :/

我在 onCreate 中添加了这个,让它从锁定屏幕打开。

protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    //allow window to be popped up while in lock screen
    Window window = this.getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
    window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
    window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    setContentView(R.layout.activity_entry);

我正在通过意图从服务中打开活动。

    callEntryActivityIntent = new Intent(this, EntryActivity.class);
    callEntryActivityIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    pendingIntent = PendingIntent.getActivity(this, 0, callEntryActivityIntent, 0);

当计时器结束时 -> startActivity(callEntryActivityIntent);

也许有人有想法。我真的是 android 开发的新手,两周前就开始了。

【问题讨论】:

【参考方案1】:
I am new too, but I guess **android activity cycle** has an answer:
+ The user opens an activity.
       - onCreated() is called
       - onStart() is called
       - onResume() is called  
+ The user LOCKS the device 
       - onPause() is called
       - onDestroy() is called
       - onCreate() is called
       - onStart() is called
       - onResume() is called 
       - onPause() is called   
+ The user UNLOCKS the device
       - onResume() is called
       - onDestroy() is called
       - onCreate() is called
       - onStart() is called
       - onResume() is called.

Hope this helps

【讨论】:

这是 android Q 权限更改的问题。看到这里developer.android.com/guide/components/activities/… 必须授予权限无论如何谢谢你的回答! :)

以上是关于从锁定屏幕启动时,Android Activity 会打开两次的主要内容,如果未能解决你的问题,请参考以下文章

Android 锁定屏幕放心

Android中Activity运行时屏幕方向与显示方式详解

将移动应用程序启动图标放在通知屏幕上以从锁定设备启动

屏幕关闭时从 BroadcastReceiver 打开 Activity

默认锁定屏幕上的 Android 活动

Appium API(常用)