参考

https://github.com/fanqieVip/keeplive

步骤

  1. app/build.gradle

    1
    implementation 'com.fanjun:keeplive:1.1.22'
  2. 在application中启动保活服务

    AndroidManifest.xml application 添加 android:name=".ContextUtil"

    ContextUtil.java 类中添加如下代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    //定义前台服务的默认样式。即标题、描述和图标
    ForegroundNotification foregroundNotification = new ForegroundNotification("测试","描述", R.mipmap.ic_launcher,
    //定义前台服务的通知点击事件
    new ForegroundNotificationClickListener() {

    @Override
    public void foregroundNotificationClick(Context context, Intent intent) {
    }
    });
    //启动保活服务
    KeepLive.startWork(this, KeepLive.RunMode.ENERGY, foregroundNotification,
    //你需要保活的服务,如socket连接、定时任务等,建议不用匿名内部类的方式在这里写
    new KeepLiveService() {
    /**
    * 运行中
    * 由于服务可能会多次自动启动,该方法可能重复调用
    */
    @Override
    public void onWorking() {

    }
    /**
    * 服务终止
    * 由于服务可能会被多次终止,该方法可能重复调用,需同onWorking配套使用,如注册和注销broadcast
    */
    @Override
    public void onStop() {

    }
    }
    );