Playing Bg Music Across Activities in Android

Android backround music across multiple activities; How to catch Home button presses

I'm a bit new to Android Programming (few months) and today, I faced the same problem you did (maybe you still do?)

I made it work as the following :

Lets say I have MainActivity, and in MainActivity I have Btn2 which leads to SecondActivity, and Btn3 which leads to ThirdActivity.

I declared at the beginning of MainActivity :

public static boolean shouldPlay = false;

I then implemented my onStop() method :

public void onStop() {
super.onStop();
if (!shouldPlay) { // it won't pause music if shouldPlay is true
player.pause();
player = null;
}
}

If the boolean shouldPlay is set to true, then my onStop() won't be called entirely and my music won't turn off. I then have to decide when I set it to true. When I switch from MainActivity to SecondActivity, I do it through an Intent and that's when I'll set shouldPlay to true :

Button Btn2 = (Button) findViewById(R.id.Btn2);
Btn2.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
shouldPlay = true;
startActivity(intent);
}
});

And the same is done for Btn3.

Now, the last thing we want to be looking for is that if I was to go back to MainActivity after visiting SecondActivity or ThirdActivity, shouldPlay would then have been set to true. The first thing I tried was to set it to false as soon as Second and ThirdActivity are called (in their onCreate()) but it want to work, maybe because the onStop() from Main and onCreate() from others are called simultaneously (frankly I don't really get life cycle for now).
What worked is simply to set shouldPlay to false every time we launch onCreate() of Main :

shouldPlay = false;

This works properly for me.
Let me know if it does for you,
Cheers,
bRo.

Android - play background music that will play across all activities

create a base activity and extend all other other activities from base activity and play bg music or whatever you want

public class BaseActivty extends AppCompatActivity{

@Override
protected void onPause() {
super.onPause();
// pause music
}

@Override
protected void onResume() {
super.onResume();
// play music
}
}

public class FirstActivty extends BaseActivty{

// perform other stuff here
}

hope that will help you...

How to play music in background for all activities?

In order for media to be played in the background of your app location when the user is interacting with it you must start a Service from your application's main activity and the service shall contain all the methods related to playback. To allow activity to interact with the service, a service connection is also required. In short, we need to implement a bounded service.

Refer

http://www.codeproject.com/Articles/258176/Adding-Background-Music-to-Android-App

Play background music across all my activities, and stop it only when my app is not displayed

Maybe i found a way mixing the suggestions all of you gave me.

WITH THIS CODE THE BACKGROUND MUSIC (IN THIS CASE MANAGED WITH A SERVICE) STOPS ONLY WHEN USERS CLOSE THE APP WITH THE BACK BUTTON, WHEN USERS CLOSE THE APP WITH THE HOME BUTTON AND WHEN SCREENS TURN OFF BECAUSE USERS LOCK THE SCREEN WITH THE LOCK BUTTON OF THE DEVICES.

I'd like someone more expert and good at programming than me to confirm this is correct

in this class i check if my current activity is in foreground or not

public class GestioneApplicazioneInBackground{
public static boolean applicazioneInBackground(final Context context) {
ActivityManager am = (ActivityManager) MainActivity.context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}

return false;
}
}

in onStop() and onPause() methods of all my activities i have this code

/// if my app and his activities are in background i stop the service i started in my main/first activity////
if(GestioneApplicazioneInBackground.applicazioneInBackground(this) ){
context_of_the_Intent.stopService(intent);
}
else{
// if my app and his activities are NOT in background i check if user turned off the screen with the lock button of the device//////
PowerManager kgMgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
boolean showing = kgMgr.isScreenOn();
if(!showing){
context_of_the_Intent.stopService(intent);
}

}

The same background music playing in all activities

This is happened because the Service is still bounded in the activity. To terminate the service when multiple activity is bound to the service, you need to unbind the service from all of them as in the documentation says:

The service lifecycle—from when it's created to when it's
destroyed—can follow either of these two paths:

A started service

The service is created when another component calls startService().
The service then runs indefinitely and must stop itself by calling
stopSelf(). Another component can also stop the service by calling
stopService(). When the service is stopped, the system destroys it.

A bound service

The service is created when another component (a client) calls
bindService(). The client then communicates with the service through
an IBinder interface. The client can close the connection by calling
unbindService(). Multiple clients can bind to the same service and
when all of them unbind, the system destroys the service. The service
does not need to stop itself.

These two paths are not entirely separate. You can bind to a service
that is already started with startService(). For example, you can
start a background music service by calling startService() with an
Intent that identifies the music to play. Later, possibly when the
user wants to exercise some control over the player or get information
about the current song, an activity can bind to the service by calling
bindService(). In cases such as this, stopService() or stopSelf()
doesn't actually stop the service until all of the clients unbind.

Then call Context.stopService() to stop it:

context.stopService(new Intent(context, BackgroundSoundService.class));

How to play background music through all activities using Kotlin?

Here' code in kotlin code Play background music in all activities

class BackgroundSoundService : Service() {
internal lateinit var player: MediaPlayer
override fun onBind(arg0: Intent): IBinder? {

return null
}

override fun onCreate() {
super.onCreate()
val afd = applicationContext.assets.openFd("backgroundsound1.wav") as AssetFileDescriptor
val player = MediaPlayer()
player.setDataSource(afd.fileDescriptor)
player.isLooping = true // Set looping
player.setVolume(100f, 100f)

}

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
player.start()
return 1
}

override fun onStart(intent: Intent, startId: Int) {
// TO DO
}

fun onUnBind(arg0: Intent): IBinder? {
// TO DO Auto-generated method
return null
}

fun onStop() {

}

fun onPause() {

}

override fun onDestroy() {
player.stop()
player.release()
}

override fun onLowMemory() {

}

companion object {
private val TAG: String? = null
}
}


Related Topics



Leave a reply



Submit