I am developing an entertainment app in android. I want to play background music, and I want to use service for that. App have 3 activities and music must be played across all activities. Also, when activity is paused, music must PAUSE and stopped when destroyed. Can anyone tell me how to do this ? any links or examples ?
Thank you.
Service is an Android wrapper around active resources. You can of course play music from a background thread in your Activity or even your Application, but unless you have an Activity or Service in foreground your app process can be killed at any time. And so dies your music.
From the Home screen, tap Apps > Music Player . Tap a song in your library to listen to it. Tap the Menu Key > Settings and checkmark the Show notification option so that the music controller is displayed on the Notifications panel.
Do it without service
https://web.archive.org/web/20181116173307/http://www.rbgrn.net/content/307-light-racer-20-days-61-64-completion
If you are so serious about doing it with services using mediaplayer
Intent svc=new Intent(this, BackgroundSoundService.class); startService(svc);
public class BackgroundSoundService extends Service { private static final String TAG = null; MediaPlayer player; public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { super.onCreate(); player = MediaPlayer.create(this, R.raw.idil); player.setLooping(true); // Set looping player.setVolume(100,100); } public int onStartCommand(Intent intent, int flags, int startId) { player.start(); return 1; } public void onStart(Intent intent, int startId) { // TO DO } public IBinder onUnBind(Intent arg0) { // TO DO Auto-generated method return null; } public void onStop() { } public void onPause() { } @Override public void onDestroy() { player.stop(); player.release(); } @Override public void onLowMemory() { } }
Please call this service in Manifest Make sure there is no space at the end of the .BackgroundSoundService string
<service android:enabled="true" android:name=".BackgroundSoundService" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With