I want to keep running one service which reads incoming messages even after app is closed [clicking on recent apps button and then close it]. I have tried using START_STICKY, isolated process but nothing is working. Is it possible in latest android versions ?
Asked
Active
Viewed 839 times
0
-
You can run your service in a separate process. – Christopher Jun 12 '17 at 10:16
-
I tried doing that my putting process name and isolated as true, but app gets killd. – NooB8374 Jun 12 '17 at 10:17
-
If your service onstartcommand return START_STICKY, than if application process got killed it will restart service again. Check here - https://developer.android.com/reference/android/app/Service.html#START_STICKY – Keyur Thumar Jun 12 '17 at 10:18
-
@ Christopher Running service in separate process with not work, as it will get terminated once application process is killed. – Keyur Thumar Jun 12 '17 at 10:19
-
START_STICKY doesn't work. – NooB8374 Jun 12 '17 at 10:20
-
I am killing app by clicking on recent apps icon. – NooB8374 Jun 12 '17 at 10:21
4 Answers
0
private void startForground(){
Intent notificationIntent = new Intent(this,MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
Notification notification=new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentText("App Name")
.setContentIntent(pendingIntent)
.build();
startForeground(NOTIFICATION_ID, notification);
}
If you don't want to show notification or icon but still want to run in background try this answer

Sai
- 15,188
- 20
- 81
- 121
-
I don't want to show any icon. Want to run this as a background service. – NooB8374 Jun 12 '17 at 10:17
0
Making a sticky service, will ensure you restarting after app is closed, but you need to call your methods in onStartComand()
.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// do your job here
// start reading your incoming messages
readMessages();
return START_STICKY;
}

Cătălin Florescu
- 5,012
- 1
- 25
- 36
-
START_STICKY doesn't work. Service gets killed when i swipe it from recent used apps. – NooB8374 Jun 12 '17 at 11:24
-
Yes, but should start after is killed. You can't keep a service running all the time. – Cătălin Florescu Jun 12 '17 at 14:30
0
try
public int onStartCommand(Intent intent, int flags, int startId)
{
..........
return super.onStartCommand(intent, flags, startId);
}
but when you close the application onStartCommand restart from the beginning whether it has finished it's job or not!

Mostafa Yadegari
- 1
- 1