我就是这样开始服务的:
public void startService(){
if (!isRunningInForeground()) {
Log.i("#foregroundservice", "Starting service");
bindIntent = new Intent(PSLocationService.this, PSLocationService.class);
startService(bindIntent);
}
}我在onStartCommand上这样做:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
PSLocationService.startId = startId;
if (PSApplicationClass.getInstance().isAutoPilotAllowed() || PSTrip.getActiveTrip() != null) {
Log.i("#foregroundservice", "onStartCommand");
Intent notificationIntent = new Intent(this, PSTimelineFragmentsActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification.Builder(this)
.setPriority(Notification.PRIORITY_MAX)
.setContentTitle(getText(R.string.passenger_name))
.setContentText(getText(R.string.getStarted_switch_on_toplabel))
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(pendingIntent)
.build();
startForeground(1338, notification);
}
return super.onStartCommand(intent, flags, startId);
}当我断开与googleApiClient的连接时,我想这样阻止它:
if (isRunningInForeground()) {
Log.i("#foregroundservice", "Stopping service: " + bindIntent);
stopForeground(true);
stopSelf();
}它总是在stopForeground(true)方法处崩溃,出现此错误:
11-10 12:59:50.026: E/AndroidRuntime(10731): java.lang.NullPointerException: class name is null
11-10 12:59:50.026: E/AndroidRuntime(10731): at android.content.ComponentName.<init>(ComponentName.java:114)
11-10 12:59:50.026: E/AndroidRuntime(10731): at android.app.Service.stopForeground(Service.java:671)
11-10 12:59:50.026: E/AndroidRuntime(10731): at nl.hgrams.passenger.core.tracking.PSLocationService.disconnectLocationClient(PSLocationService.java:272)发布于 2017-11-13 17:48:15
通过调用活动类中的stopForeground(true) (而不是我的ApplicationClass ),确实成功地使其工作。另外,我没有使用stopForeground,而是这样做:
Intent serviceIntent = new Intent(context, PSLocationService.class);
context.stopService(serviceIntent);https://stackoverflow.com/questions/47222334
复制相似问题