應用程序在後臺運行,在後臺執行startActivity後會強制把界面帶到前端解決方案

在項目中,不免會遇到耗時操做,咱們都將其寫入子線程,但耗時操做結束後則可能須要跳轉,但若是用戶此前已經將app調成後臺程序,此時在進行跳轉,Android5.0以後會將app提高爲前臺應用,也就是用戶在操做其餘應用是,咱們的app會忽然蹦出來,這樣的體驗天然很差。在咱們項目中,解決方法是:java

一、耗時操做結束後,進行斷定,應用是不是前臺應用,若是是,可進行耗時操做app

二、若是耗時操做結束後,應用已經被用戶調整爲後臺應用,則在onRestart中進行跳轉操做(在此處還需添加一個標記,跳轉後標記失效,以避免跳轉頁面關閉後,從新展示該頁面,又會再次跳轉),這樣用戶在下次再次開啓app的時候,直接跳轉到對應的頁面。this

判斷是否爲前臺應用的方法:線程

/**
 * 程序是否在前臺運行
 *
 * @return
 */
public static boolean isAppOnForeground() {
    // Returns a list of application processes that are running on the
    // device
    ActivityManager activityManager = (ActivityManager) CommUtils.getContext().getSystemService(Context.ACTIVITY_SERVICE);
    String packageName =  CommUtils.getContext().getPackageName();

    List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
            .getRunningAppProcesses();
    if (appProcesses == null)
        return false;
    for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
        // The name of the process that this object is associated with.
        if (appProcess.processName.equals(packageName)
                && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
            return true;
        }
    }
    return false;
}
相關文章
相關標籤/搜索