[英]How to know if my application is in foreground or background, android?
我需要檢查我的應用程序是在后台還是前台運行,然后執行一些相對於它的操作。
我搜索了很多,但沒有明確的解決方案。
在其 onPause() 和 onResume() 方法中創建一個父活動,保留一些變量以相應地更新它們。 當您創建任何新活動時,繼承您的父活動。 雖然這是我覺得完成我的任務的最佳解決方案,但有時如果即使應用程序在后台單擊電源按鈕,也會調用 onResume()。
使用 GETTASKS 權限 - 這個解決方案也很好。 但它只能用於調試目的。 如果您想將您的應用程序放在 Google Play 商店中,則不會。
任何其他首選解決方案?
嗯,這解決了我的問題:
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;
}
原始答案: 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()
使用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 中添加任何權限
您可以使用此代碼獲取應用程序的前台( 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;
}
使用以下函數檢查您的應用程序是在后台還是前台
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;
}
只想在活動/片段中使用以下代碼:
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);
}
}
如果您想在每一秒后檢查一次,請在 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);
}
};
在 onCreate() 中只需調用一次,例如:
appIsRuningHandler.postDelayed(CheckAppIsRunning, 1000);
檢查應用程序處於前台狀態還是后台狀態
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");
}
}
您可以使用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);
}
您可以使用流程生命周期所有者檢查這一點。
fun isAppOnForeground(): Boolean {
return ProcessLifecycleOwner.get().getLifecycle().getCurrentState()
.isAtLeast(Lifecycle.State.STARTED);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.