需求:app程序进入后台或者手机屏幕关闭,开启的定时器任务(使用timers的计数任务)继续执行
问题:调试手机usb连接电脑,程序进入后台或手机屏幕关闭,开启的定时器任务正常执行;但是,如果拔掉usb数据线,定时器任务被阻塞。无法达到正常计数的效果。
方案:新建TimersService,在Service中实现定期是任务
问题:此时只能解决程序进入后台情况
public class TimersService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent,int flags, int startId) {
long currTime = intent.getLongExtra("currTime",System.currentTimeMillis());
Logger.i("DemoLog","currTime:"+currTime);
LocalQRCodeUtil.getInstance().calculTime(currTime);//定时器任务开启
return START_STICKY;
}
@Override
public void onDestroy() {
LocalQRCodeUtil.getInstance().stopTimer();//定时器任务关闭
super.onDestroy();
}
}
问题:添加TimersService,关闭手机屏幕,定时器任务仍然被阻塞
方案:确保关闭屏幕,定时器任务正常执行,需要在TimersService添加PowerManager.WakeLock 在屏幕休眠后保持cpu唤醒状态以使得service继续运行。
参考:http://blog.youkuaiyun.com/sinat_33285127/article/details/76131349
public class TimersService extends Service {
*private PowerManager.WakeLock wakeLock = null;*
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
//保持cpu唤醒状态以使得service继续运行。
*PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TimersService.class.getName());
wakeLock.acquire();*
super.onCreate();
}
@Override
public int onStartCommand(Intent intent,int flags, int startId) {
long currTime = intent.getLongExtra("currTime",System.currentTimeMillis());
Logger.i("DemoLog","currTime:"+currTime);
LocalQRCodeUtil.getInstance().calculTime(currTime);
return START_STICKY;
}
@Override
public void onDestroy() {
//service关闭处理
*if (wakeLock != null) {
wakeLock.release();
wakeLock = null;
}*
LocalQRCodeUtil.getInstance().stopTimer();
super.onDestroy();
}
}
问题:在Aactvity启动Service,在Bactivity关闭启动的Service
使用Service的startService启动方式
启动service代码:
public void calculTime(Activity mActivity,long time){
Logger.e(“启动服务”);
stopService(mActivity);
currentTime = time;
Intent intent = new Intent(mActivity, TimersService.class);
intent.putExtra(“currTime”,currentTime);
mActivity.startService(intent);
}
关闭service代码:
public void stopService(Activity mActivity){
Logger.e(“关闭服务”);
Intent intent = new Intent(mActivity, TimersService.class);
mActivity.stopService(intent);
}
注:启动service的mActivity与关闭service的mActivity可以不是同一个activity类
service的两种启动模式
1 startService(全局模式)
区别于绑定模式,一处开启service,任一activity关闭service
2 bindService(绑定模式)
绑定在一个acitivty上,activty销毁service也跟随着销毁
具体service理解和使用
参考:http://blog.youkuaiyun.com/zjws23786/article/details/51800929