直接上代码
@SuppressLint("NewApi")
public class JobHandlerService extends JobService {
private JobScheduler mJobScheduler;
@SuppressLint("WrongConstant")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Logger.e("JobHandlerService onStartCommand");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mJobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
JobInfo.Builder builder = new JobInfo.Builder(startId++,
new ComponentName(getPackageName(), JobHandlerService.class.getName()));
builder.setPeriodic((1000 * 60 * 2));//设置间隔时间
builder.setRequiresCharging(true);// 设置是否充电的条件,默认false
builder.setRequiresDeviceIdle(true);// 设置手机是否空闲的条件,默认false
builder.setPersisted(true);//设备重启之后你的任务是否还要继续执行
if (mJobScheduler.schedule(builder.build()) <= 0) {
Logger.e("JobHandlerService 工作失败");
} else {
Logger.e("JobHandlerService 工作成功");
}
}
return START_STICKY;
}
@Override
public boolean onStartJob(JobParameters params) {
Logger.e("JobHandlerService 服务启动");
if (!isServiceRunning("com.amap.api.location.APSService")) {
init_Aps();
}
return false;
}
@Override
public boolean onStopJob(JobParameters params) {
if (!isServiceRunning("com.amap.api.location.APSService")) {
init_Aps();
}
return false;
}
private void init_Aps() {
LocationUtil.newInstance().open(); // 定位 服务类
}
// 服务是否运行
public boolean isServiceRunning(String serviceName) {
boolean isRunning = false;
ActivityManager am = (ActivityManager) this
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> lists = am.getRunningAppProcesses();
// 获取运行服务再启动
for (ActivityManager.RunningAppProcessInfo info : lists) {
System.out.println(info.processName);
if (info.processName.equals(serviceName)) {
isRunning = true;
}
}
return isRunning;
}
}
清单文件
<service
android:name="com.xxxx.xxxx.service.JobHandlerService"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE">
<intent-filter>
<action android:name="com.onesignal.NotificationExtender" />
</intent-filter>
</service>
为了提高app的保活可能性,项目中使用1px像素Activity ,前台服务,播放无声音乐等方法。
手机设置:进程加锁,自启动,允许后台运行,部分机型有解冻app设置。
网友评论