Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

android - 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?

question from:https://stackoverflow.com/questions/65898028/how-to-run-service-in-background-like-whatsapp-does-for-taking-backup-of-the-cha

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...