简体   繁体   English

如何检查活动是否为前台,并在活动为前台时将其带入后台?

[英]How to check whether a activity is foreground and bring it to background when it is foreground?

I hope to define whether a activity is foreground in Android, and bring it to background when it is foreground. 我希望定义一个活动在Android中是否为前台,并在其为前台时将其置于后台。 How can I do it? 我该怎么做?

You know the <uses-permission android:name="android.permission.GET_TASKS"/> is Deprecated! 您知道<uses-permission android:name="android.permission.GET_TASKS"/>已弃用!

Sample Code 样例代码

private boolean isTopActivity(String activityName){
    ActivityManager manager = (ActivityManager) mContext.getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);
    String cmpNameTemp = null;
    if(runningTaskInfos != null){
        cmpNameTemp = runningTaskInfos.get(0).topActivity.toString();
    }
    if(cmpNameTemp == null){
        return false;
    }
    return cmpNameTemp.equals(activityName);
}

this is supported natively by the Activity lifecycle which is onResume , which will be called after the activity comes in the foreground. 这是由活动生命周期onResume本地支持的,活动生命周期将在活动进入前台后被调用。

public void onResume() {
    // do here what you need
}

Put below code in a file in your application 将下面的代码放在应用程序的文件中

    public class Foreground implements Application.ActivityLifecycleCallbacks {

public static final long CHECK_DELAY = 500;
public static final String TAG = Foreground.class.getName();

public interface Listener {

    public void onBecameForeground();

    public void onBecameBackground();

}

private static Foreground instance;

private boolean foreground = false, paused = true;
private Handler handler = new Handler();
private List<Listener> listeners = new CopyOnWriteArrayList<Listener>();
private Runnable check;

/**
 * Its not strictly necessary to use this method - _usually_ invoking
 * get with a Context gives us a path to retrieve the Application and
 * initialise, but sometimes (e.g. in test harness) the ApplicationContext
 * is != the Application, and the docs make no guarantees.
 *
 * @param application
 * @return an initialised Foreground instance
 */
public static Foreground init(Application application) {
    if (instance == null) {
        instance = new Foreground();
        application.registerActivityLifecycleCallbacks(instance);
    }
    return instance;
}

public static Foreground get(Application application) {
    if (instance == null) {
        init(application);
    }
    return instance;
}

public static Foreground get(Context ctx) {
    if (instance == null) {
        Context appCtx = ctx.getApplicationContext();
        if (appCtx instanceof Application) {
            init((Application) appCtx);
        }
        throw new IllegalStateException(
                "Foreground is not initialised and " +
                        "cannot obtain the Application object");
    }
    return instance;
}

public static Foreground get() {
    if (instance == null) {
        throw new IllegalStateException(
                "Foreground is not initialised - invoke " +
                        "at least once with parameterised init/get");
    }
    return instance;
}

public boolean isForeground() {
    return foreground;
}

public boolean isBackground() {
    return !foreground;
}

public void addListener(Listener listener) {
    listeners.add(listener);
}

public void removeListener(Listener listener) {
    listeners.remove(listener);
}

@Override
public void onActivityResumed(Activity activity) {
    paused = false;
    boolean wasBackground = !foreground;
    foreground = true;

    if (check != null)
        handler.removeCallbacks(check);

    if (wasBackground) {
        Log.i(TAG, "went foreground");
        for (Listener l : listeners) {
            try {
                l.onBecameForeground();
            } catch (Exception exc) {
                Log.e(TAG, "Listener threw exception!", exc);
            }
        }
    } else {
        Log.i(TAG, "still foreground");
    }
}

@Override
public void onActivityPaused(Activity activity) {
    paused = true;

    if (check != null)
        handler.removeCallbacks(check);

    handler.postDelayed(check = new Runnable() {
        @Override
        public void run() {
            if (foreground && paused) {
                foreground = false;
                Log.i(TAG, "went background");
                for (Listener l : listeners) {
                    try {
                        l.onBecameBackground();
                        Intent intent = getPackageManager().getLaunchIntentForPackage("com.package.name");
                        if (intent != null) {
                            // We found the activity now start the activity
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        } else {
                            // Bring user to the market or let them choose an app?
                            intent = new Intent(Intent.ACTION_VIEW);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.setData(Uri.parse("market://details?id=" + "com.package.name"));
                            startActivity(intent);
                        }
                    } catch (Exception exc) {
                        Log.e(TAG, "Listener threw exception!", exc);
                    }
                }
            } else {
                Log.i(TAG, "still foreground");
            }
        }
    }, CHECK_DELAY);
}

@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}

@Override
public void onActivityStarted(Activity activity) {
}

@Override
public void onActivityStopped(Activity activity) {
}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}

@Override
public void onActivityDestroyed(Activity activity) {
}

Now in onCreate method of Application.class put the code: 现在在Application.class的onCreate方法中放入代码:

 @Override
public void onCreate() {
    super.onCreate();
    Foreground.init(this);
}

You can now use Foreground.isBackground() to get application is in background or not. 现在,您可以使用Foreground.isBackground()获取应用程序是否在后台。

You can even perform specific task in one of the overridden lifecycle methods (onActivityPaused, onActivityStopped etc) 您甚至可以使用一种覆盖的生命周期方法(onActivityPaused,onActivityStopped等)执行特定任务。

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

相关问题 如何检查活动是在Android中的前景还是背景? - How to check whether activity is in foreground or background in android? 如何检查应用程序是在前台还是后台 - How to check whether the app is in foreground or background 如何检查活动是在前景中还是在可见背景中? - How to check if activity is in foreground or in visible background? 如何将Android Activity置于前台并检测其是否在后台? - How to Bring Android Activity to the Foreground and Detect if its in background? 通知只有在后台运行时才将Activity带入前台 - Notification to bring Activity into foreground only if it is in background Android-后台活动使自己成为前台 - Android - Background activity bring itself to foreground 如何从活动内部将活动带到前台? - How to bring an activity to the foreground from inside the activity? 接收 voip 呼叫时如何将活动带到前台? - How to bring an activity to foreground when receiving voip call? 当锁屏处于活动状态时,android如何将singleInstance活动置于前台 - android how to bring singleInstance activity to foreground when lockscreen is active 将应用程序带到后台然后到前台 - Bring application to background and then to foreground
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM