I am learning services these days and just experimenting around it and I don't have any intention to make Music player but just to learn about how do services work. So let me explain what I am doing.
My application is having one Activity
and one Service
extending Service
class in which I have
@Override
public void onCreate()
{
mediaPlayer=MediaPlayer.create(this,R.raw.serenity);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
mediaPlayer.start();
return 0;
}
And in my MainActivity
class I am starting the Service
on the main thread by
startService(intent);
And also I have added the attribute
<service
android:name=".MusicService"
android:process=":music"/>
To run the service in another process. Now I want to say that when I am starting the service with a button on activity class the service starts playing music although when i press back button the activity destroys and also music still play yeah that what I want but when I remove this app from recents then The music stops and get start with the beginning. Please tell me why this is happening. I don't want to music stop I want it to just play independent of activity or process of the application.
If the service is currently executing code in its onCreate(), onStartCommand(), or onDestroy() methods, then the hosting process will be a foreground process to ensure this code can execute without being killed.
see:
https://developer.android.com/reference/android/app/Service.html#ServiceLifecycle
I know this thing but my question is that although being a foreground process as you said executing onStartCommand() it is getting stopped when I am clearing the application from recents the service it getting stopped once and getting started again from beginning. – Dushyant Suthar 14 hours ago
as shows example:
example enable/start:
A foreground service is a service that's considered to be something the user is actively aware of and thus not a candidate for the system to kill when low on memory.
A foreground service must provide a notification for the status bar, which is placed under the "Ongoing" heading, which means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.