1,从官网上可以看出google为了系统更加流畅以及优化内存,Google做了很大的处理,在手机暗屏或者睡眠状态就停止后台运行;若要保持service的常驻,需要做一些前端的活动,Notification重要属性:notification.flags = Notification.FLAG_NO_CLEAR|Notification.FLAG_ONGOING_EVENT;然后startForeground(setClass().hashCode(), notification);使得服务能挂在通知栏。
2,通过wakelock占用CPU,若一直占用CPU的话,当然这是比较耗电的,要是耗电太高的话系统会直接回收,杀死程序进程。
我是使用定时器唤醒cpu 后台服务将接收到定时任务执行未完成的任务:下面是我实现的代码
在mainfest中注册
<uses-permission android:name="android.permission.WAKE_LOCK"/><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>复制代码
<receiver android:name=".receiver.WakeCPUAlarmReceiver"/><service
android:name="com.txtws.wakeloackdemo.service.WakecpuIntentService" ></service>复制代码
关键代码定时任务:
public void startAlarm(Context context){
Intent intent = new Intent(context, WakeCPUAlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmMgr = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmMgr.setExactAndAllowWhileIdle(
AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + chekcTime, alarmIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmMgr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + chekcTime, alarmIntent);
} else {
alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + chekcTime, alarmIntent);
FileLogUtil.e(TAG , "startAlarm 设置定时任务");
}复制代码
接收到定时任务:
public class WakeCPUAlarmReceiver extends WakefulBroadcastReceiver { private AlarmManager alarmMgr; private PendingIntent alarmIntent; private final long chekcTime = 30* 1000;
public static boolean isCheckFlag = false; private static String TAG = WakeCPUAlarmReceiver.class.getSimpleName(); @Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, WakecpuIntentService.class); FileLogUtil.e(TAG , "onReceive 接收定时任务");
startWakefulService(context, service);
}复制代码
在service中执行需要执行的任务:
public class WakecpuIntentService extends IntentService { private static String TAG = WakecpuIntentService.class.getSimpleName() + " :"; private NotificationManager mNotificationManager; private PowerManager.WakeLock wl; NotificationCompat.Builder builder;
public WakecpuIntentService() { super("WakecpuIntentService");
} @Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras(); FileLogUtil.e(TAG, "Service接收到WakeLock定时任务。"); PollService.startService(getApplicationContext()); FileLogUtil.e(TAG, "Service接收到WakeLock定时任务在定时任务中启动轮询Service。");
WakeCPUAlarmReceiver.completeWakefulIntent(intent);
WakeCPUAlarmReceiver.setCheckFlag(false); WakeCPUAlarmReceiver mAlarmReceiver = new WakeCPUAlarmReceiver();
mAlarmReceiver.startAlarm(WakecpuIntentService.this); FileLogUtil.e(TAG, "Service释放wakelock后设置定时任务。");
}复制代码
service在后台也能够打印log 保持一直执行,最重要的是不耗电也不会卡机的问题。欢迎大家一起讨论学习。
关注公众号:
Dominic本尊44826
Android开发 @ 绿网天下