android - 是否可以确定应用程序是否已在屏幕上消失/出现?
问题描述
我想确定我的应用程序是否在屏幕上,即当用户单击主页按钮或锁定屏幕时,我想接收我的应用程序已进入后台的一次性事件。当用户打开我的应用程序或解锁屏幕时,我希望收到该应用程序出现在屏幕上的一次性事件。
Activity的onPause、onResume、onStart、onStop方法不是我想要的。当设备屏幕被锁定/解锁时,这些方法被多次调用。有时当屏幕解锁并且我的应用程序在屏幕上时,我会收到onStop / onPause。这对我的用例来说是一个糟糕的场景。当应用打开任何Dialog时调用onWindowFocusChanged。这也是一个糟糕的场景。
是否有另一种变体如何解决问题?
解决方案
假设您在项目中使用 AndroidX,那么您可以使用ProcessLifecycleOwner来确定应用程序已经消失或出现在屏幕上。
ProcessLifecycleOwner
为整个应用程序进程提供生命周期的类。
它对于您希望对您的应用程序进入前台或进入后台做出反应并且您在接收生命周期事件时不需要毫秒精度的用例很有用。
在您的代码中使用:
1.创建一个从应用程序类扩展的类。
public class MyApplication extends Application {
private final MyLifecycleObserver observer = new MyLifecycleObserver();
@Override
public void onCreate() {
super.onCreate();
ProcessLifecycleOwner.get().getLifecycle().addObserver(observer);
}
class MyLifecycleObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onAppMoveToForeground() {
Log.d("MyLifecycleObserver", "My app moves to foreground.");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onMoveAppToBackground() {
Log.d("MyLifecycleObserver", "My app moves to background.");
}
}
}
2.添加你的AndroidManifest.xmlandroid:name=".MyApplication"
文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidx">
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
推荐阅读
- linux - ftok() 中的这个“项目标识符”是什么?
- azure - 在 Azure VM 下的 Docker 中运行的 IIS ARR 反向代理返回 404
- laravel - Laravel - websockets 主管运行错误
- selenium - 不依赖于当前 Chrome 安装的 Selenium chromedriver
- java - 为什么 bigInteger 没有 -1 的位长?
- firebase - Firebase 查询在复杂数据模型中返回太多文档
- r - R中的动态对齐图(空间图的自定义ggplot2图例)
- nuget - 如何仅为特定目标框架从 NuGet 包还原程序集
- pyspark - Pyspark - 合并连续的重复行但保持开始和结束日期
- python - 尝试/捕获在 python 中关闭 postgres 数据库连接