如何像 WhatsApp 那样在后台运行服务以在没有唤醒设备的情况下备份聊天?

问题描述

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

解决方法

service 用于它。

然后你创建了另一个类,你有 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