这就是我开始服务的方式:
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)