Search code examples
androidandroid-serviceandroid-alarms

How to run service in background like WhatsApp does for taking backup of the chat without wake up device?


In my application, I need to do some task at midnight of the everyday. I achieved this using AlarmManager and service, but when my task starts it wakeup the device and launches the app. How can I do that like WhatsApp in the background?


Solution

  • service used for it.

    You have create another class then, you have extend Service

    public class service extends Service {
    
    // declaring object of MediaPlayer
    private MediaPlayer player;
    
    public service() {
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        onTaskRemoved(intent);
        Toast.makeText(getApplicationContext(),"This is a Service running in Background",
                Toast.LENGTH_SHORT).show();
        player = MediaPlayer.create(getApplicationContext(),R.raw.ringtone);
        player.start();
        startForegroundService(intent);
        return START_STICKY;
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Intent restartServiceIntent = new Intent(getApplicationContext(),this.getClass());
        restartServiceIntent.setPackage(getPackageName());
        startService(restartServiceIntent);
        super.onTaskRemoved(rootIntent);
    }
    @Override
    public ComponentName startForegroundService(final Intent service) {
        return startForegroundService(service);
    }
    }
    

    To run the source code you have write

    Intent intent = new Intent(this, service.class);
    ContextCompat.startForegroundService(this,intent);
    

    Alternatively, you can use

    startService(new Intent(getApplicationContext(),service.class));
    

    Sometimes above source code works in background in API level 22. Sometimes it gives error. Sometimes it doesn't work.

    Here's the git repo