如何 运行 像 WhatsApp 一样在后台提供服务,以便在不唤醒设备的情况下备份聊天?

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

在我的应用程序中,我需要在每天午夜做一些任务。我使用 AlarmManager 和服务实现了这一点,但是当我的任务开始时,它会唤醒设备并启动应用程序。我怎样才能在后台像 WhatsApp 一样做到这一点?

service用于它。

您已经创建了另一个 class 然后,您有 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);
}
}

到运行你写的源代码

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

或者,您可以使用

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

有时上面的源代码在 API 级别 22 的后台工作。有时它会出错。有时候不行。

这是git repo

您可以使用 WorkManager,恕我直言,这是最好的方法。 我将它用于后台处理,它就像一个魅力。 https://developer.android.com/topic/libraries/architecture/workmanager