我想停止活动服务。当我不关闭应用程序时它会停止。但是,当我关闭应用程序并再次运行应用程序时,服务不会停止。
流程
- >单击“开启”
- >显示通知/位置监听器
- >杀死应用程序
- >通知仍然存在(服务正在运行)
- >再次打开应用程序和
- >单击Switch OFF
- >服务不会停止,通知仍然存在
服务类
public class locationService extends Service {
NotificationCompat.Builder builder;
NotificationManager notificationManager;
public static final String serviceTag = "LocationServiceTag";
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
SharedPreferences sharedPref = getSharedPreferences("AppPref",Context.MODE_PRIVATE);
userCurrentRoute= sharedPref.getString("RouteNo","");
mDatabase = FirebaseDatabase.getInstance().getReference();
notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
Intent repeating_intent =new Intent(this,MainActivity.class);
PendingIntent pendingIntent= PendingIntent.getActivity(this,10,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT);
builder = new NotificationCompat.Builder(this)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.bus_small)
.setContentTitle("BusBuzz")
.setContentText("Sharing Location to all")
.setAutoCancel(false)
.setOnlyAlertOnce(true)
.setOngoing(true)
;
notificationManager.notify(10,builder.build());
provider = new LocationGooglePlayServicesProvider();
provider.setCheckLocationSettings(true);
return START_NOT_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
notificationManager.cancel(10);
Toast.makeText(this, "App Closed Location Sharing Stopped", Toast.LENGTH_SHORT).show();
SmartLocation.with(this).location().stop();
super.onDestroy();
}
}
活动
if (isChecked) {
startService(new Intent(MainActivity.this,locationService.class).addCategory(locationService.serviceTag));
}
else
{
stopService(new Intent(MainActivity.this,locationService.class).addCategory(locationService.serviceTag));
}
答案 0 :(得分:1)
您写道:
--> Click Switch ON
--> Show Notification / Location Listener
--> Kill App
--> Notification still remains (Service is running means)
仅仅因为通知存在,并不意味着 Service
仍在运行。实际上,它已经死了。您杀死了导致Service
杀死的应用,并且从START_NOT_STICKY
返回onStartCommand()
后,Android将不会重新启动Service
,直到您的应用再次向{{{}}发出呼叫1}}。由于应用程序被终止,因此永远不会调用startService()
,因此通知永远不会被删除。
您可以使用onDestroy()
验证这一点,以便在您杀死应用后查看adb shell dumpsys activity services
是否正在运行。