Android之冷启动和热启动,以及代码

     昨天听到一个群里面的人說一些问题。大概提了一下热启动和冷启动的方案,结果那小伙伴不知道。。。。

我这边就简单的说明一下:

        热启动呢:就是你已经打开过APP但是实际上面你使用home键等。就是还存在后台的应用。再次打开的时候算是属于热启动了。

冷启动呢:属于你第一次打开APP,系统在给你开一个进程。

      这个时候我在说明一下热启动的作用。我这边公司想知道他APP开了几次。而且需要准确的数据。这个时候,使用热启动。其实热启动很多地方都可以使用到。

现在贴一下代码:(这个代码是之前在百度上面copy过来的)首先我们要知道这个东西是不是还在前台。

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public boolean isAppOnForeground() {
        // Returns a list of application processes that are running on the
        // device

        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();

        List 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;
    }
我也得知道这个APP什么时候进去后台,对吧~~那么我们得知道安卓的Activity得生命周期。写一个简单版本得

oncreate

onpause

onstop

ondestory

那么这几个里面我应该选哪一个进行记录呢oncreate和onDestory不可能,onpause和onstop俩个。一个是暂停,但是不代表进去了后台页面。但是对于onstop是有的

所以这边的选择是onstop

    @Override
    protected void onStop() {
        super.onStop();
        if (!isAppOnForeground()) {
            //app 进入后台
            isLive = false;
            //全局变量isActive = false 记录当前已经进入后台
        }
    }

那么知道生命周期的应该知道那个onResume这个:

    @Override
    protected void onResume() {
        super.onResume();
        mCurContext = this;
        if (!isLive) {
        //app 从后台唤醒,进入前台
            HttpTwo();
          isLive = true;
        }
    }

那么代码如上了~~



你可能感兴趣的:(android)