android守护进程,进入后台或异常后再次启动app

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_26075861/article/details/79428758

当前做的app要求开机启动,并且退出后或异常闪退时也要重新打开app。下面说一下进入后台后或闪退后重启进入前台方法

方法1、缺点:出现异常闪退时,不会重启,因为没来及进onActivityStopped

private int mFinalCount;

    /**
     * 在application中调用,进入一个activity时执行onActivityStarted,离开一个activity时执行onActivityStopped
     */
    private void ActivitiesLifeCallbacks()
    {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle bundle) {

            }

            @Override
            public void onActivityStarted(Activity activity) {
                mFinalCount++;
                //如果mFinalCount ==1,说明是从后台到前台
                Log.e("onActivityStarted", mFinalCount +"");
                if (mFinalCount == 1){
                    //说明从后台回到了前台
                }
            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {
                mFinalCount--;

                //如果mFinalCount ==0,说明是前台到后台
                Log.i("onActivityStopped", mFinalCount +"");
                if (mFinalCount == 0){
                    //说明从前台回到了后台
                    try {
                        //此处需加延时几秒,否则按home键后回不到前台
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    toFront();
                }
            }

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

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
    }

    /**
     * 由后台进入前台
     */
    private void toFront()
    {
        //获取ActivityManager
        ActivityManager mAm = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        //获得当前运行的task
        List<ActivityManager.RunningTaskInfo> taskList = mAm.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo rti : taskList) {
            //找到当前应用的task,并启动task的栈顶activity,达到程序切换到前台
            if (rti.topActivity.getPackageName().equals(getPackageName())) {
                mAm.moveTaskToFront(rti.id, 0);
                return;
            }
        }
        //若没有找到运行的task,用户结束了task或被系统释放,则重新启动mainactivity
        Intent resultIntent = new Intent(this, SplashActivity.class);
        resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(resultIntent);
    }

方法2、缺点需要创建service,以及线程,暂用大量CPU时间;切换至后台运行时会有延迟。不过没多大影响,而且闪退时可以重启,目前用这个

import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.rb.esc.activity.SplashActivity;

import java.util.List;

/**
 * 监听前后台
 * Created by Administrator on 2018/3/3.
 */

public class AppService extends Service implements Runnable
{
    public static boolean isOnForeground = true;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        new Thread(this).start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void run() {
        while(true){
            boolean isOnForegroundNew = isRunningOnForeground(this);

            if(isOnForegroundNew != isOnForeground){
                toFront();
            }
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static boolean isRunningOnForeground(Context context){

        ActivityManager acm = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if(acm != null){
            List<ActivityManager.RunningAppProcessInfo> runApps = acm.getRunningAppProcesses();
            if(runApps != null && !runApps.isEmpty()){
                for(ActivityManager.RunningAppProcessInfo app : runApps){
                    if(app.processName.equals(context.getPackageName())){
                        if(app.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    private void toFront()
    {
        //获取ActivityManager
        ActivityManager mAm = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        //获得当前运行的task
        List<ActivityManager.RunningTaskInfo> taskList = mAm.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo rti : taskList) {
            //找到当前应用的task,并启动task的栈顶activity,达到程序切换到前台
            if (rti.topActivity.getPackageName().equals(getPackageName())) {
                mAm.moveTaskToFront(rti.id, 0);
                return;
            }
        }
        //若没有找到运行的task,用户结束了task或被系统释放,则重新启动mainactivity
        Intent resultIntent = new Intent(this, SplashActivity.class);
        resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(resultIntent);

    }
}

xml中

<service android:name=".service.AppService"
            android:enabled="true"
            android:exported="true"></service>

启动时

Intent intent = new Intent(this, AppService.class);
        startService(intent);

展开阅读全文

没有更多推荐了,返回首页