简体   繁体   English

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

[英]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.我使用 AlarmManager 和服务实现了这一点,但是当我的任务启动时,它会唤醒设备并启动应用程序。 How can I do that like WhatsApp in the background?我怎样才能在后台像WhatsApp一样做到这一点?

service used for it.用于它的service

You have create another class then, you have extend 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);
}
}

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.有时上面的源代码在 API 级别 22 的后台工作。有时它会出错。 Sometimes it doesn't work.有时它不起作用。

Here's the git repo这是git 存储库

You can use WorkManager, that is the best way IMHO.您可以使用 WorkManager,这是恕我直言的最佳方式。 I use it for background processing and it works like a charm.我将它用于后台处理,它就像一个魅力。 https://developer.android.com/topic/libraries/architecture/workmanager https://developer.android.com/topic/libraries/architecture/workmanager

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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