Android service stops when I exit from application

社会主义新天地 提交于 2019-11-30 14:38:02

Are you starting the Service with startService? If so, when you end your activity, the service is not bound to anything and can be stopped by the system.

If you want to run a background Service regardless of your activities, use startForeground and provide a constant notification.

See the Service reference: http://developer.android.com/reference/android/app/Service.html

UPDATE

Finishing your app with System.exit(0)? Of course your service stops, that kills your process. You should never exit an application like that - just finish() your activity.

Pratikk

Add this code in your onStartCommand() method

  showToast("onStart");

  Intent intent = new Intent(this, NotStickyActivity.class);
  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
  PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

  Notification noti = new Notification.Builder(getApplicationContext())
              .setContentTitle("Pratikk")
              .setContentText("Subject")
              .setSmallIcon(R.drawable.ic_launcher)
              .setContentIntent(pendingIntent)
              .build();

  startForeground(1234, noti);     

  return Service.START_STICKY;

It will not stops your service.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!