android app保活

时向文
2023-12-01

app处于后台或者杀死自动拉起,服务监听

ActivityLifecycleService

public class ActivityLifecycleService extends Service {
    private int count = 0;

    public void isBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    LogUtils.d("service", "app处于后台,back " + count);
                    if (count > 0) {
//                        if (BuildConfig.isPro){
                        count = 0;
                        LogUtils.d("service", "重新拉起app回到前台");
                        Intent newIntent = context.getPackageManager().getLaunchIntentForPackage(appProcess.processName);
                        context.startActivity(newIntent);
//                        }
                    } else {
                        count++;
                    }
                } else {
                    count = 0;
//                    LogUtils.d("service", "front" );
                }
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //适配8.0service
        NotificationManager notificationManager = (NotificationManager) App.getInstance().getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel mChannel = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel("1", getString(R.string.app_name),
                    NotificationManager.IMPORTANCE_LOW);
            notificationManager.createNotificationChannel(mChannel);
            Notification notification = new Notification.Builder(getApplicationContext(), "1").build();
            startForeground(1, notification);
        }
        executeFixedRate();
    }

    @SuppressLint("WrongConstant")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        flags = START_STICKY;

        return super.onStartCommand(intent, flags, startId);
    }

    public void executeFixedRate() {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        executor.scheduleAtFixedRate(
                new EchoServer(), 0,
                1000 * 5,
                TimeUnit.MILLISECONDS);
    }

    class EchoServer implements Runnable {
        @Override
        public void run() {
            isBackground(App.getInstance());
        }
    }

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

manifest添加权限,注册服务

<uses-permissionandroid:name="android.permission.FOREGROUND_SERVICE" />

<service android:name=".service.ActivityLifecycleService" />

app崩溃拉起
引入第三方库

    implementation 'com.jakewharton:process-phoenix:2.0.0'

	//腾旭bugly
    implementation 'com.tencent.bugly:crashreport:4.0.4'

App.java

public class App extends LitePalApplication {

    private static Context context;

	//RefreshLayout构建器
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.blue, android.R.color.black);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header,默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer,默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        //腾讯bugly
        CrashReport.initCrashReport(getApplicationContext(), "28c3838e9b", true);
       	//开启线程监听程序崩溃
        Thread.setDefaultUncaughtExceptionHandler(new CrashHandler());
        //判断程序是否正在运行
        if (!isRunningService(this, ActivityLifecycleService.class.getName())) {
            Intent intent = new Intent(this, ActivityLifecycleService.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent);
            } else {
                context.startService(intent);
            }
        }
    }
    public static Context getInstance(){
        return context;
    }

    public static class CrashHandler implements Thread.UncaughtExceptionHandler {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            ProcessPhoenix.triggerRebirth(App.getInstance());
        }
    }

    private boolean isRunningService(Context context, String name) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServices = am.getRunningServices(100);
        for (ActivityManager.RunningServiceInfo info : runningServices) {
            if (TextUtils.equals(info.service.getClassName(), name)) {
                return true;
            }
        }
        return false;
    }

}
 类似资料: