Guest User

Untitled

a guest
Nov 16th, 2018
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. private void stopForegroundService() {
  2.  
  3. // Stop foreground service and remove the notification.
  4. stopForeground(true);
  5.  
  6. // Stop the foreground service.
  7. stopSelf();
  8. }
  9.  
  10. Intent intent = new Intent(this, MyForeGroundService.class);
  11. intent.setAction(MyForeGroundService.ACTION_STOP_FOREGROUND_SERVICE);
  12. startService(intent);
  13.  
  14. private static final String TAG_FOREGROUND_SERVICE = "FOREGROUND_SERVICE";
  15.  
  16. public static final String ACTION_START_FOREGROUND_SERVICE = "ACTION_START_FOREGROUND_SERVICE";
  17.  
  18. public static final String ACTION_STOP_FOREGROUND_SERVICE = "ACTION_STOP_FOREGROUND_SERVICE";
  19.  
  20. @Override
  21. public int onStartCommand(Intent intent, int flags, int startId) {
  22. if (intent != null) {
  23. String action = intent.getAction();
  24.  
  25. switch (action) {
  26. case ACTION_START_FOREGROUND_SERVICE:
  27. startForegroundService();
  28. break;
  29. case ACTION_STOP_FOREGROUND_SERVICE:
  30.  
  31. stopForegroundService();
  32. break;
  33. }
  34. }
  35. return START_STICKY;
  36. }
  37.  
  38. private void stopForegroundService() {
  39. Log.d(TAG_FOREGROUND_SERVICE, "Stop foreground service.");
  40.  
  41. // Stop foreground service and remove the notification.
  42. stopForeground(true);
  43.  
  44. // Stop the foreground service.
  45. stopSelf();
  46. }
  47.  
  48. <service
  49. android:enabled="true"
  50. android:name=".ExampleService"
  51. android:exported="false"
  52. android:stopWithTask="true" />
  53.  
  54. @Override
  55. public void onTaskRemoved(Intent rootIntent) {
  56. System.out.println("onTaskRemoved called");
  57. super.onTaskRemoved(rootIntent);
  58. //do something you want
  59. //stop service
  60. this.stopSelf();
  61. }
Add Comment
Please, Sign In to add comment