0

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 ?

NooB8374
  • 99
  • 11

4 Answers4

0

Try startForeground(notitficationId, notificationObject); command in onStartCommand()

Roman
  • 129
  • 6
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
  • 14,089
  • 18
  • 76
  • 114
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;
}
Florescu Cătălin
  • 4,684
  • 1
  • 23
  • 33
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!