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



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

service用于它。

你创建了另一个类然后是extendService

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

最新更新