简体   繁体   English

如何知道我的应用程序是在前台还是后台,android?

[英]How to know if my application is in foreground or background, android?

I need to check if my application is running in background or foreground and then perform some operations relatively to it.我需要检查我的应用程序是在后台还是前台运行,然后执行一些相对于它的操作。

I searched a lot and a clear solution is not available.我搜索了很多,但没有明确的解决方案。

  1. Make a parent activity in its onPause() and onResume() methods keep some variable to update them accordingly.在其 onPause() 和 onResume() 方法中创建一个父活动,保留一些变量以相应地更新它们。 When you create any new activity inherit your parent activity.当您创建任何新活动时,继承您的父活动。 Although this is the best solution I feel to achieve my task, but sometimes if the power button is clicked even though application is in background, it's onResume() is invoked.虽然这是我觉得完成我的任务的最佳解决方案,但有时如果即使应用程序在后台单击电源按钮,也会调用 onResume()。

  2. Use GETTASKS permission - This solution is also good.使用 GETTASKS 权限 - 这个解决方案也很好。 But it can only used for debug purpose.但它只能用于调试目的。 Not if you want to put your app on Google Play Store.如果您想将您的应用程序放在 Google Play 商店中,则不会。

Get Running Taks 获得运行任务

Any other preferred solution for this?任何其他首选解决方案?

Well this solved my issue:嗯,这解决了我的问题:

  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;
}

Original Answer : https://stackoverflow.com/a/60212452/10004454 The recommended way to do it in accordance with Android documentation is原始答案: 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
}}

In your gradle (app) add : implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"在您的 gradle(应用程序)中添加: implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"

Then to check the state at runtime call MyApplication().isActivityVisible()然后在运行时检查状态调用MyApplication().isActivityVisible()

use AppVisibilityDetector , I implement this class to detect the app visibility status.使用AppVisibilityDetector ,我实现了这个类来检测应用程序的可见性状态。 it can detect the foreground and background status and perform the callback method.它可以检测前台和后台状态并执行回调方法。

 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
    }
});

the MyApp is your Application class MyApp 是您的应用程序类

public class MyApp extends Application { ... }

you don't need add some other codes to your Activity or any permissions in the AndroidManifest.xml您不需要在您的活动中添加一些其他代码或在 AndroidManifest.xml 中添加任何权限

You can use this code to get the status of foreground( true ) running of your app您可以使用此代码获取应用程序的前台( true )运行状态

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;
}

Use the following Function to check if your application is in Background or 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;
}

Just want to use below code in Activity/Fragment:只想在活动/片段中使用以下代码:

final boolean isAlive = AppVisibilityHelper.isForeground(HomeActivity.this);

Want to make one class like below:想要制作一个如下所示的课程:

 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);
        }
    }

If you want to check it after every one second then use below code in Activity:如果您想在每一秒后检查一次,请在 Activity 中使用以下代码:

 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);
        }
    };

And in onCreate() just call it once like:在 onCreate() 中只需调用一次,例如:

appIsRuningHandler.postDelayed(CheckAppIsRunning, 1000);

check app is in forground state or background state检查应用程序处于前台状态还是后台状态

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");

       }

  }

You can use ActivityManager.RunningAppProcessInfo class to check the app status.您可以使用ActivityManager.RunningAppProcessInfo类来检查应用程序状态。

public boolean isForegrounded() {
    ActivityManager.RunningAppProcessInfo appProcessInfo = new ActivityManager.RunningAppProcessInfo();
    ActivityManager.getMyMemoryState(appProcessInfo);
    return (appProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND ||
            appProcessInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE);
}

You can check this using process lifecycle owner.您可以使用流程生命周期所有者检查这一点。

fun isAppOnForeground(): Boolean {
return ProcessLifecycleOwner.get().getLifecycle().getCurrentState()
    .isAtLeast(Lifecycle.State.STARTED);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM