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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…