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?
Asked
Active
Viewed 1,022 times
0
-
Please have a look at the official [doc](https://developer.android.com/guide/components/foreground-services) and [implementing startForeground for a service?](https://stackoverflow.com/questions/6397754/android-implementing-startforeground-for-a-service) – rahat Jan 26 '21 at 08:39
2 Answers
1
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
-
Note : I ran a music from `raw`. You have to replace it with your source code. – Jan 26 '21 at 09:22
0
You can use WorkManager, that is the best way IMHO. I use it for background processing and it works like a charm. https://developer.android.com/topic/libraries/architecture/workmanager

KotlinIsland
- 799
- 1
- 6
- 25