Search code examples
androidservicetaskrestart

android (Service & PhoneStateListener) - service does restart but not working when app is killed by task manager, killer or shortage of memory


This is onStartCommand()

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // Notification creation code

    telMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
    telMgr.listen(new PSL(), PhoneStateListener.LISTEN_CALL_STATE);

    return super.onStartCommand(intent, flags, startId);
}

and PhoneStateListener class (under service class)

public class PSL extends PhoneStateListener {
    public void onCallStateChanged(int state, String incomingNum) {
        switch(state) {
        case TelephonyManager.CALL_STATE_IDLE:
        case TelephonyManager.CALL_STATE_OFFHOOK:
            //Work1
            break;
        case TelephonyManager.CALL_STATE_RINGING:
            //Work2
            break;
        }
    }
}

both of them are in same .java file

I have these code on one service class.

when I call startService() from main activity, it works well. but when my app is killed by Task Manager, Killer or automatically by shortage of memory on device, Service does restarts but not working. when i go to Setting - Application - Running, it shows process 1 and service 1, before/after killed.but after killed, memory share goes 1/10. I have tried startForeground() not to be killed easily with my notification - it didn't work. (doesn't show any notification) and also tried return of onStartCommand(): START_STICKY, START_REDELIVER_INTENT - shows same result is there any way I can restart completely or make it not killed?


Solution

  • I solved it by startForeground()

    It didn't work because I had not used Notification.FLAG_FOREGROUND_SERVICE on Notification