我需要检查我的应用程序是在后台运行还是在前台运行,然后相对于它执行一些操作。
我搜索了很多,没有明确的解决方案。
在onPause()和onResume()方法中创建一个父活动,保留一些变量来相应地更新它们。创建任何新活动时,都会继承父活动。 虽然这是我实现任务的最佳解决方案,但有时即使应用程序在后台单击电源按钮,也会调用onResume()。
使用GETTASKS权限 - 此解决方案也很好。但它只能用于调试目的。如果您想将自己的应用放在Google Play商店中,则不会。
对此有任何其他优选解决方案吗?
答案 0 :(得分:9)
这解决了我的问题:
private boolean isAppOnForeground(Context context,String appPackageName) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = appPackageName;
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
// Log.e("app",appPackageName);
return true;
}
}
return false;
}
答案 1 :(得分:8)
原始答案:https://stackoverflow.com/a/60212452/10004454 按照Android文档的推荐方法是
class MyApplication : Application(), LifecycleObserver {
override fun onCreate() {
super.onCreate()
ProcessLifecycleOwner.get().lifecycle.addObserver(this);
}
fun isActivityVisible(): String {
return ProcessLifecycleOwner.get().lifecycle.currentState.name
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onAppBackgrounded() {
//App in background
Log.e(TAG, "************* backgrounded")
Log.e(TAG, "************* ${isActivityVisible()}")
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onAppForegrounded() {
Log.e(TAG, "************* foregrounded")
Log.e(TAG, "************* ${isActivityVisible()}")
// App in foreground
}}
在gradle(应用程序)中添加:implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
然后在运行时调用MyApplication().isActivityVisible()
答案 2 :(得分:2)
使用AppVisibilityDetector,我实现此类来检测应用可见性状态。它可以检测前台和后台状态并执行回调方法。
AppVisibilityDetector.init(MyApp.this, new AppVisibilityCallback() {
@Override
public void onAppGotoForeground() {
//app is from background to foreground
}
@Override
public void onAppGotoBackground() {
//app is from foreground to background
}
});
MyApp是您的应用程序类
public class MyApp extends Application { ... }
您不需要为您的活动或AndroidManifest.xml中的任何权限添加其他代码
答案 3 :(得分:1)
您可以使用此代码获取应用运行的前景(真实)状态
public boolean isAppForground(Context mContext) {
ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(mContext.getPackageName())) {
return false;
}
}
return true;
}
答案 4 :(得分:0)
使用以下函数检查您的应用程序是在Background还是Foreground
public static Boolean getProcessState(Context mContext) {
ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
boolean noProcessOnForeground = true;
boolean isProcessForeground = false;
System.out.println("Checking if process: " + mContext.getApplicationInfo().processName + " is Foreground or Background");
List<ActivityManager.RunningAppProcessInfo> current_processes = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo appProcess : current_processes) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
noProcessOnForeground = false;
if ((mContext.getApplicationInfo().processName).equalsIgnoreCase(appProcess.processName)) {
isProcessForeground = true;
System.out.println("Process is Foreground");
break;
// Toast.makeText(getApplicationContext(), "Process is Foreground", Toast.LENGTH_SHORT).show();
} else {
System.out.println("Process is Background");
// Toast.makeText(getApplicationContext(), "Process is Background", Toast.LENGTH_SHORT).show();
isProcessForeground = false;
break;
}
}
}
if (noProcessOnForeground) {
System.out.println("there is no process on foreground so setting " + mContext.getApplicationInfo().processName + " as background");
isProcessForeground = false;
}
return isProcessForeground;
}
答案 5 :(得分:0)
只想在Activity / Fragment中使用以下代码:
final boolean isAlive = AppVisibilityHelper.isForeground(HomeActivity.this);
想要制作如下所示的课程:
public class AppVisibilityHelper{
public static boolean isForeground(final Context context) {
final String packageName = "com.acb.android";
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1);
ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
return componentInfo.getPackageName().equals(packageName);
}
}
如果您想在每一秒后检查一次,请在活动中使用以下代码:
Runnable CheckAppIsRunning = new Runnable() {
@Override
public void run() {
final boolean isAlive = AppVisibilityHelper.isForeground(HomeActivity.this);
if (isAlive) {
// App is running
} else {
// App is not running
}
}
appIsRuningHandler.postDelayed(CheckAppIsRunning, 1000);
}
};
在onCreate()中只需调用一次:
appIsRuningHandler.postDelayed(CheckAppIsRunning, 1000);
答案 6 :(得分:0)
检查应用是否处于forground状态或背景状态
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
final String packageName = getPackageName();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses)
{
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND && appProcess.processName.equals(packageName))
{
//if app in background state this will execute
Intent intent = getPackageManager().getLaunchIntentForPackage("hinditextonphoto.com.allcomponents");
startActivity(intent);
System.out.println("bbbbbbbbbbbbb background");
}
else if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName))
{
//if app in forground state this will execute
System.out.println("bbbbbbbbbbbbb forground");
}
}