我当前正在尝试在前台服务上执行一些代码。 我的手机在android 6和android 7上一切正常。 但是,当我在android 5设备上尝试使用该服务时,该活动被破坏了。
在调用bindService之前,我正在手动启动服务。 我在onStart上调用bindService,在onStop方法上调用unbindService。
这是我的服务
public class ExecutionService extends Service {
private final IBinder binder = new ExecutionBinder();
private static final int NOTIFICATION_ID = 1;
private static final String STOP_ACTION = "STOP_ACTION";
private Notification.Builder builder;
private boolean timerHeaderVisible;
private NotificationManager nm;
private Intent notificationIntent;
private PendingIntent contentIntent;
public class ExecutionBinder extends Binder {
public ExecutionService getService() {
return ExecutionService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
@Override
public void onCreate() {
super.onCreate();
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
builder = new Notification.Builder(this);
Intent stopSelf = new Intent(this, ExecutionService.class);
stopSelf.setAction(STOP_ACTION);
PendingIntent closePendingIntent = PendingIntent.getService(this, 0, stopSelf,PendingIntent.FLAG_CANCEL_CURRENT);
builder.setSmallIcon(R.drawable.ic_time)
.setContentTitle(getString(R.string.app_name))
.addAction(R.drawable.ic_stop, getString(R.string.stop), closePendingIntent)
.setVibrate(new long[]{0L});
Notification notification = builder.build();
notification.flags |= Notification.FLAG_NO_CLEAR;
startForeground(NOTIFICATION_ID, notification);
}
@Override
public void onDestroy() {
super.onDestroy();
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
if(notificationManager != null)
notificationManager.cancelAll();
isStarted = false;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent != null && intent.getAction() != null && intent.getAction().equals(STOP_ACTION)) {
stopForeground(true);
stopSelf();
}
return START_STICKY;
}
}
我注意到从不调用onDestroy方法,但是两次调用onCreate方法。
如何使其在Android 5设备上正常工作? 感谢您的帮助。
答案 0 :(得分:0)
尝试删除此方法
@Override
public void onDestroy() {
super.onDestroy();
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
if(notificationManager != null)
notificationManager.cancelAll();
isStarted = false;
}
答案 1 :(得分:0)
最后,我发现了问题所在。我正在活动的onDestroy中的空对象上调用方法。然后服务崩溃了(仅适用于android吗?)。 我没有注意到控制台中的错误,因为该应用程序正在重新启动。