在我的应用中,我使用了一个IntentService,我从一个活动管理:
Intent intent = new Intent(this, LogData.class);
if(isMyServiceRunning()){
stopService(intent);
}else{
startService(intent);
}...
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (LogData.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
我在服务中使用唤醒锁和通知,在onStartCommand中初始化:
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MyBGWakelockTag");
wakeLock.acquire();
Notification noti = new Notification.Builder(this)
.setContentTitle("Title goes here")
.setContentText("").setSmallIcon(R.drawable.ic_launcher).build();
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
noti.flags |= Notification.FLAG_ONGOING_EVENT;
notificationManager.notify(0, noti);
并在onDestroy中关闭它:
try{
if(wakeLock.isHeld()){
wakeLock.release();
}
}catch(Exception e){
e.printStackTrace();
}
notificationManager.cancel(0);
super.onDestroy();
我在某些设备上对它进行了测试,它在大部分设备上运行得很完美,但在HTC One X上没有,它首先在NullpointerException
上抛出一个wakeLock.release()
,然后我把它放在try-catch中,现在在线notificationManager.cancel(0)
。当然我也可以把它放在try-catch中,但是我不明白后台会发生什么,为什么会产生这个错误以及为什么只是在HTC上呢?在我的代码之前关闭唤醒锁和通知的东西?有没有人有同样的问题,我怎么能纠正它并肯定关闭唤醒锁和通知。