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
  • 12

4 Answers4

0

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

Roman
  • 149
  • 7
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
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
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!