简体   繁体   中英

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?

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

You can use WorkManager, that is the best way IMHO. I use it for background processing and it works like a charm. https://developer.android.com/topic/libraries/architecture/workmanager

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM