03.app保活解决方案

简介: 最近针对我们项目中app经常收不到推送的问题作了一些处理,增加app的保活管理。我们知道当安卓进程退到后台之后,很容易被系统杀死,这个时候推送消息一般都是收不到的。

最近针对我们项目中app经常收不到推送的问题作了一些处理,增加app的保活管理。我们知道当安卓进程退到后台之后,很容易被系统杀死,这个时候推送消息一般都是收不到的。我也观察了一些比较主流的app,像同花顺,钉钉,甚至是支付宝我都很少在后台收到过消息,尤其是支付宝计步功能老是不准,很有可能就是这种问题导致的

当然没有百分之百可以实现保活的解决方案,即便是从ndk层面去进行,但至少我们要尽一些努力,我采用的是双进程守护+1像素Activity的实现方式

双进程守护:

开启两个service,分别在两个进程中运行,启动一个service时,通过aidl的方式将它和另一个service绑定在一起,当其中一个service被杀掉的时候,另一个service中重新将它启动

service1启动绑定service2

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //提高进程优先级
        startForeground(GuardServiceId2,new Notification());
        //绑定建立链接
        bindService(new Intent(getApplicationContext(),GuardService2.class),connection, Context.BIND_IMPORTANT);
        return START_STICKY;
    }

service1和service2的链接断开时,说明service2被杀死,这时重新绑定

private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            ArLog.i("TAG", "connect to guardservice2");
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            // 断开链接 ,重新启动,重新绑定
            startService(new Intent(getApplicationContext(), GuardService2.class));
            bindService(new Intent(getApplicationContext(),GuardService2.class),connection, Context.BIND_IMPORTANT);
            ArLog.i("TAG", "disconnect from guardservice2");
        }
    };

service2绑定service1的逻辑同上

这样一来,基本上在一定程度上可以保证app常驻内存了,保险起见,我们再加一层保护,创建两个JobService
分别位于上边两个进程中(安卓5.0以上适用),开启一个轮巡任务不断的检查service存活情况,如果不在了,启动它,注意JobService需要权限

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 开启一个轮寻
        JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        JobInfo.Builder jobBuilder = new JobInfo.Builder(jobId,new ComponentName(this,JobWakeUpService1.class));
        //设置每两秒钟一次
        jobBuilder.setPeriodic(2000);
        jobScheduler.schedule(jobBuilder.build());
        ArLog.i("TAG", "start JobWakeUpService1");
        return START_STICKY;
    }

    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        // 开启定时任务,定时轮寻 , 看MessageService有没有被杀死
        // 如果杀死了启动  轮寻onStartJob

        // 判断服务有没有在运行
        boolean messageServiceAlive = serviceAlive(GuardService1.class.getName());
        if(!messageServiceAlive){
            ArLog.i("TAG", "GuardService1 is killed ,restart it");
            startService(new Intent(this,GuardService1.class));
        }
        boolean JobWakeUpService2Alive = serviceAlive(JobWakeUpService2.class.getName());
        if(!JobWakeUpService2Alive){
            ArLog.i("TAG", "JobWakeUpService2 is killed ,restart it");
            startService(new Intent(this,JobWakeUpService2.class));
        }
        return false;
    }

1像素Activity:

监听系统锁屏消息,在屏幕锁定的时候开启一个Activity,这个Activity只有一个像素大小,当屏幕开启的时候再关闭这个Activity,达到app一直位于前台进程的目的,提高进程的优先级,降低系统杀死app的概率,在这个Activity启动时设置app只有一个像素大小,既可以减少占用空间,也可以防止开锁屏期间被用户发现这个奇怪的页面

        Window window = getWindow();
        window.setGravity(Gravity.LEFT & Gravity.TOP);
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.x = 0;
        attributes.y = 0;
        attributes.width = 1;
        attributes.height = 1;
        window.setAttributes(attributes);

在AndroidManifest中配置

<activity android:name=".general.guard.DaemonActivity"
            android:configChanges="keyboardHidden|orientation|screenSize|navigation|keyboard"
            android:excludeFromRecents="true"
            android:exported="false"
            android:finishOnTaskLaunch="false"
            android:launchMode="singleInstance"
            android:theme="@style/DaemonActivityStyle"/>

完整代码:

GuardService1

public class GuardService1 extends Service {
    private final int GuardServiceId2 = 2;
    @Override
    public void onCreate() {
        super.onCreate();
        ArLog.i("TAG", "GuardService1 wait for signal");
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //提高进程优先级
        startForeground(GuardServiceId2,new Notification());
        //绑定建立链接
        bindService(new Intent(getApplicationContext(),GuardService2.class),connection, Context.BIND_IMPORTANT);
        return START_STICKY;
    }
    @Override
    public IBinder onBind(Intent intent) {
        return new GuardAIDL.Stub(){};
    }
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            ArLog.i("TAG", "connect to guardservice2");
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            // 断开链接 ,重新启动,重新绑定
            startService(new Intent(getApplicationContext(), GuardService2.class));
            bindService(new Intent(getApplicationContext(),GuardService2.class),connection, Context.BIND_IMPORTANT);
            ArLog.i("TAG", "disconnect from guardservice2");
        }
    };
    @Override
    public void onDestroy() {
        ArLog.i("TAG", "guardservice2 is onDestroy");
        unbindService(connection);
        super.onDestroy();
    }
}

GuardService2

public class GuardService2 extends Service {
    private final int GuardServiceId1 = 1;
    @Override
    public void onCreate() {
        super.onCreate();
        ArLog.i("TAG", "GuardService2 wait for signal");
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //提高进程优先级
        startForeground(GuardServiceId1,new Notification());
        //绑定建立链接
        bindService(new Intent(getApplicationContext(),GuardService1.class),connection, Context.BIND_IMPORTANT);
        return START_STICKY;
    }
    @Override
    public IBinder onBind(Intent intent) {
        return new GuardAIDL.Stub(){};
    }
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            ArLog.i("TAG", "connect to guardservice1");
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            // 断开链接 ,重新启动,重新绑定
            startService(new Intent(getApplicationContext(), GuardService1.class));
            bindService(new Intent(getApplicationContext(),GuardService1.class),connection, Context.BIND_IMPORTANT);
            ArLog.i("TAG", "disconnect from guardservice1");
        }
    };
    @Override
    public void onDestroy() {
        ArLog.i("TAG", "guardservice1 is onDestroy");
        unbindService(connection);
        super.onDestroy();
    }
}

JobWakeUpService1

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class JobWakeUpService1 extends JobService {
    private int jobId = 12;
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 开启一个轮寻
        JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        JobInfo.Builder jobBuilder = new JobInfo.Builder(jobId,new ComponentName(this,JobWakeUpService1.class));
        //设置每两秒钟一次
        jobBuilder.setPeriodic(2000);
        jobScheduler.schedule(jobBuilder.build());
        ArLog.i("TAG", "start JobWakeUpService1");
        return START_STICKY;
    }
    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        // 开启定时任务,定时轮寻 , 看MessageService有没有被杀死
        // 如果杀死了启动  轮寻onStartJob
        // 判断服务有没有在运行
        boolean messageServiceAlive = serviceAlive(GuardService1.class.getName());
        if(!messageServiceAlive){
            ArLog.i("TAG", "GuardService1 is killed ,restart it");
            startService(new Intent(this,GuardService1.class));
        }
        boolean JobWakeUpService2Alive = serviceAlive(JobWakeUpService2.class.getName());
        if(!JobWakeUpService2Alive){
            ArLog.i("TAG", "JobWakeUpService2 is killed ,restart it");
            startService(new Intent(this,JobWakeUpService2.class));
        }
        return false;
    }
    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        return false;
    }
    /**
     * 判断某个服务是否正在运行的方法
     * @param serviceName
     *            是包名+服务的类名(例如:net.loonggg.testbackstage.TestService)
     * @return true代表正在运行,false代表服务没有正在运行
     */
    private boolean serviceAlive(String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(100);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }
}

JobWakeUpService2

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class JobWakeUpService2 extends JobService {
    private int jobId = 13;
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 开启一个轮寻
        JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        JobInfo.Builder jobBuilder = new JobInfo.Builder(jobId,new ComponentName(this,JobWakeUpService2.class));
        //设置每两秒钟一次
        jobBuilder.setPeriodic(2000);
        jobScheduler.schedule(jobBuilder.build());
        ArLog.i("TAG", "start JobWakeUpService2");
        return START_STICKY;
    }
    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        // 开启定时任务,定时轮寻 , 看MessageService有没有被杀死
        // 如果杀死了启动  轮寻onStartJob
        // 判断服务有没有在运行
        boolean messageServiceAlive = serviceAlive(GuardService2.class.getName());
        if(!messageServiceAlive){
            ArLog.i("TAG", "GuardService2 is killed ,restart it");
            startService(new Intent(this,GuardService1.class));
        }
        boolean JobWakeUpService1Alive = serviceAlive(JobWakeUpService1.class.getName());
        if(!JobWakeUpService1Alive){
            ArLog.i("TAG", "JobWakeUpService1 is killed ,restart it");
            startService(new Intent(this,JobWakeUpService1.class));
        }
        return false;
    }
    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        return false;
    }
   /**
     * 判断某个服务是否正在运行的方法
     * @param serviceName
     *            是包名+服务的类名(例如:net.loonggg.testbackstage.TestService)
     * @return true代表正在运行,false代表服务没有正在运行
     */
    private boolean serviceAlive(String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(100);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }
}

DaemonActivity

public class DaemonActivity extends AppCompatActivity {
    private static final java.lang.String TAG = "DaemonActivity";
    private static DaemonActivity context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.context = this;
        Window window = getWindow();
        window.setGravity(Gravity.LEFT & Gravity.TOP);
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.x = 0;
        attributes.y = 0;
        attributes.width = 1;
        attributes.height = 1;
        window.setAttributes(attributes);
    }
    /**
     * 监听手机的锁屏和开屏广播,锁屏后调用start开启这个activity
     * 调用此方法时,activity未启动,不能使用this.context,只能用application的
     */
    public static void startDaemon(){
        Intent intent = new Intent(SightPlusApplication.getContext(),DaemonActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        SightPlusApplication.getContext().startActivity(intent);
        ArLog.i(TAG,"startDaemon");
    }
    /**
     * 监听手机的锁屏和开屏广播,开屏后调用stop销毁这个activity
     * 调用此方法时,可以使用activity的context
     */
    public static void stopDaemon(){
        if (context != null){
            ArLog.i(TAG,"stopDaemon");
            context.finish();
        }
    }
}

AndroidManifest配置

<!--双进程守护-->
        <service
            android:name="cn.easyar.sightplus.general.guard.GuardService1"
            android:enabled="true"
            android:exported="true"
            android:process=":Service1" />
        <service
            android:name="cn.easyar.sightplus.general.guard.GuardService2"
            android:enabled="true"
            android:exported="true"
            android:process=":Service2" />
        <service
            android:name="cn.easyar.sightplus.general.guard.JobWakeUpService1"
            android:enabled="true"
            android:exported="true"
            android:process=":Service1"
            android:permission="android.permission.BIND_JOB_SERVICE" />

        <service
            android:name="cn.easyar.sightplus.general.guard.JobWakeUpService2"
            android:enabled="true"
            android:exported="true"
            android:process=":Service2"
            android:permission="android.permission.BIND_JOB_SERVICE" />
        <!--1像素Activity-->
        <activity android:name=".general.guard.DaemonActivity"
            android:configChanges="keyboardHidden|orientation|screenSize|navigation|keyboard"
            android:excludeFromRecents="true"
            android:exported="false"
            android:finishOnTaskLaunch="false"
            android:launchMode="singleInstance"
            android:theme="@style/DaemonActivityStyle"/>

增加一个管理类GuardAppManager一键启动和关闭

public class GuardAppManager {
    private GuardAppManager(){}
    private static volatile GuardAppManager mInstance;
    private BootCompleteReceiver mReceiver;

    public static GuardAppManager getInstance(){
        if (mInstance == null){
            synchronized (GuardAppManager.class){
                if (mInstance == null){
                    return new GuardAppManager();
                }
            }
        }
        return mInstance;
    }
    public class BootCompleteReceiver extends BroadcastReceiver {
        @Override public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                ArLog.i("TAG","ACTION_SCREEN_OFF");
                DaemonActivity.startDaemon();
            }
            else if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
                ArLog.i("TAG","ACTION_SCREEN_ON");
                DaemonActivity.stopDaemon();
            }
        }
    }
    /**
     * 开启守护
     * @param context
     */
    public void start(Context context){
        context.startService(new Intent(context, GuardService1.class));
        context.startService(new Intent(context, GuardService2.class));
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            //必须大于5.0
            context.startService(new Intent(context,JobWakeUpService2.class));
            context.startService(new Intent(context,JobWakeUpService1.class));
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        mReceiver = new BootCompleteReceiver();
        context.registerReceiver(mReceiver,filter);
    }
    /**
     * 关闭守护
     * @param context
     */
    public void stop(Context context){
        if (mReceiver != null){
            context.unregisterReceiver(mReceiver);
        }
    }
}

开启守护

GuardAppManager.getInstance().start(this);

关闭守护

GuardAppManager.getInstance().stop(this);
相关文章
|
9月前
|
Web App开发 iOS开发
无法安装此app,因为无法验证其完整性 ,解决方案
无法安装此app,因为无法验证其完整性 ,解决方案
|
XML Java Android开发
Android Studio开发APP启动程序时开屏简单动画效果快速有效解决方案
Android Studio开发APP启动程序时开屏简单动画效果快速有效解决方案
1486 0
Android Studio开发APP启动程序时开屏简单动画效果快速有效解决方案
|
2月前
|
移动开发 网络协议 安全
HTML5页面被运营商DNS问题及解决方案,app中h5页面源码的获取
HTML5页面被运营商DNS问题及解决方案,app中h5页面源码的获取
92 4
|
2月前
|
监控 数据库 数据安全/隐私保护
第三方授权的应用苹果审核被驳回解决方案和app版本更新
第三方授权的应用苹果审核被驳回解决方案和app版本更新
36 0
|
2月前
|
iOS开发
app启动时的闪屏页显示不全问题的两种解决方案
app启动时的闪屏页显示不全问题的两种解决方案
30 0
|
2月前
|
定位技术 开发工具 iOS开发
ios9定位服务的app进入后台三分钟收不到经纬度,应用被挂起问题及解决方案
ios9定位服务的app进入后台三分钟收不到经纬度,应用被挂起问题及解决方案
27 0
|
2月前
|
移动开发 JavaScript 前端开发
APP的HTML5页面经过运营商网络被植入手机管家问题及分析,解决方案见新文章
APP的HTML5页面经过运营商网络被植入手机管家问题及分析,解决方案见新文章
30 0
|
2月前
|
网络协议 定位技术 数据安全/隐私保护
APP审核驳回和重大版本问题经典案例及解决方案
APP审核驳回和重大版本问题经典案例及解决方案
54 0
|
2月前
|
Web App开发 iOS开发
无法安装此 app, 因为无法验证其完整性 ,解决方案
无法安装此 app, 因为无法验证其完整性 ,解决方案
|
11月前
|
Android开发
Android > Project with path ‘:audiovisualize‘ could not be found in project ‘:app‘. 异常解决方案
Android > Project with path ‘:audiovisualize‘ could not be found in project ‘:app‘. 异常解决方案
58 0