Stopping Background Service Music
Solution 1:
You need to launch separate service (different intent filter in the Manifest for the same serivce) in onStartCommand()
you'll check the action of the intent i.e if the action has the same value as the one you specified for intent action in the manifest file and if the action matches the intent filter action name then just stop the service.
Example from one of my projects:
In the manifest file:
<service android:name=".MyPlayerService" android:permission="android.permission.MODIFY_AUDIO_SETTINGS">
<intent-filter >
.... some other filters
<action android:name="com.my.player.EXIT"/>
....
</intent-filter>
</service>
In the onStartCommand(): Here we can see the need of specifying action name, which is used to distinguish numerous actions within the same service.
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.i("ON START COMMAND", "Huston, we have a lift off!");
if(intent.getAction().equals("com.my.player.EXIT")
{ // means that you have envoked action that will has to stop the service
MyPlayerService.this.stopSelf(); // See the note below
}else if(//some other actions that has to be done on the service)
}
Note:
Note that here you can simply stop the MediaPlayer from playing or pause it using .stop()
or .pause()
,or just terminate the service as I provided above.
Now back to the activity. Catching Home button
is not good idea. But this you can do in the onDestroy()
method, where the activity is not in the stack i.e just before it is destroyed. Here you just launch intent that will signal the service to stop working.
Example:
Intent exit = new Intent("com.my.player.EXIT"); //intent filter has to be specified with the action name for the intent
this.startService(exit);
Read more on Android Dev about stopSelf()
If you are trying this approach starting the MediaPlayer good practice will be to make the playing has its own action name in the intent filter, and do the same checking in the onStartCommand()
Post a Comment for "Stopping Background Service Music"