Android Stop Background Music

Android Stop Background Music

I'm very happy today, and still have hair :)
I've tested this and it works!!!

First, add this to your Manifest:

<uses-permission android:name="android.permission.GET_TASKS"/>

Second, add this to your 'Home/Main' Activity/Class:

  @Override
protected void onPause() {
if (this.isFinishing()){ //basically BACK was pressed from this activity
player.stop();
Toast.makeText(xYourClassNamex.this, "YOU PRESSED BACK FROM YOUR 'HOME/MAIN' ACTIVITY", Toast.LENGTH_SHORT).show();
}
Context context = getApplicationContext();
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
if (!taskInfo.isEmpty()) {
ComponentName topActivity = taskInfo.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
player.stop();
Toast.makeText(xYourClassNamex.this, "YOU LEFT YOUR APP", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(xYourClassNamex.this, "YOU SWITCHED ACTIVITIES WITHIN YOUR APP", Toast.LENGTH_SHORT).show();
}
}
super.onPause();
}

And obviously replace xYourClassNamex with, well, Your Class Name :)

Now obviously you do not need the "Toasts" but it will tell you what is going on.
The very intersting thind is when you press BACK from your 'Home/Main' activity, you obviously get 2 Toasts, "YOU PRESSED BACK FROM YOUR 'HOME/MAIN' ACTIVITY", and the 2nd Toast is "YOU SWITCHED ACTIVITIES WITHIN YOUR APP". I believe I know why this happens, but it doesn;t matter because I call "player.stop();" from the 2 scenarios that mean my app is no longer being 'used'. Obviously do more work than "player.stop();" if you need to :) And also obvious you dont need the "else" for "YOU SWITCHED ACTIVITIES WITHIN YOUR APP", because there is no reason to "stop/pause" the background music, which is what i needed, but if you DO need to do something when new activities are started, well here you go :)

Hope this helps anyone looking to know when the user "leaves/exits/is done with" the app :)

THANKS FOR ALL OF THE COMMENTS POSTS AND HELP EVERYONE!!! YAY!

EDIT-

This part has to be in EVERY activity's onPause:

Context context = getApplicationContext();
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
if (!taskInfo.isEmpty()) {
ComponentName topActivity = taskInfo.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
player.stop();
Toast.makeText(xYourClassNamex.this, "YOU LEFT YOUR APP", Toast.LENGTH_SHORT).show();
}
}

so you'll know if the user left your app from ANY of the activities. this is good to know :)

Stop music of from Other APP

You will have to implement Mediaplayer's AudioFocus. To do this you need to get an instance of the AudioManager. Once you have the instance you can then use requestAudioFocus.

AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);    
// Request audio focus for playback
int result = am.requestAudioFocus(focusChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);

if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
Log.d("AudioFocus", "Audio focus received");
return true;
} else {
Log.d("AudioFocus", "Audio focus NOT received");
return false;
}
}

AudioFocus is assigned to each application that requests it. When your app receives focus it can pass an AudioManager.OnAudioFocusChangeListener which provides callbacks for when an focus change happens.

If app gains audio focus, and another app requests audio focus, the focus will be given to the other app. Android will notify your app via an OnAudioFocusChangeListener so that your app can respond to the change. To receive focus events, you need to pass an instance of AudioManager.OnAudioFocusChangeListener like this.

private OnAudioFocusChangeListener focusChangeListener =
new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
AudioManager am =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
switch (focusChange) {

case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) :
// Lower the volume while ducking.
mediaPlayer.setVolume(0.2f, 0.2f);
break;
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) :
pause();
break;

case (AudioManager.AUDIOFOCUS_LOSS) :
stop();
ComponentName component =new ComponentName(AudioPlayerActivity.this,MediaControlReceiver.class);
am.unregisterMediaButtonEventReceiver(component);
break;

case (AudioManager.AUDIOFOCUS_GAIN) :
// Return the volume to normal and resume if paused.
mediaPlayer.setVolume(1f, 1f);
mediaPlayer.start();
break;
default: break;
}
}
};

Reference Documentation: https://developer.android.com/guide/topics/media-apps/volume-and-earphones.html

android- How to stop music when the app is on background?

Anand, you need to stop your music, when activity goes to background.

@Override
protected void onPause() {
super.onPause();
//stop or pause your music here.
}

and you need to play your music, when activity resumes.

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

how to stop background music on button click android

Make MedaiPlayer a global variable declare it out side onCreate().

MediaPlayer player;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// YOUR CODE
}

Change yout stop method like this:

protected void stopmus(View view) {

if(player!=null)
{
player.stop();
player = null;
}
super.onStop();
}

background music doesn't stop if app is onStop Android

Judging by what you want you need a more fine grained control over the starting and stopping of your MediaPlayer object. An easy solution would be to add intent-filters and actions like so:

public class BackgroundMusicService extends Service {

public static final String ACTION_START_MUSIC = "package_name.action_start_music";
public static final String ACTION_STOP_MUSIC = "package_name.action_stop";

private MediaPlayer player;

public IBinder onBind(Intent arg0) {

return null;
}

@Override
public void onCreate() {
super.onCreate();

player = MediaPlayer.create(this, R.raw.game_music);
player.setLooping(true);
player.setVolume(10, 10);

}

public int onStartCommand(Intent intent, int flags, int startId) {
if(intent.getAction() != null){
switch (intent.getAction()){
case ACTION_START_MUSIC :
if(!player.isPlaying()){
player.start();
}
break;
case ACTION_STOP_MUSIC :
if(player.isPlaying()) {
player.stop();
}
break;
default: break;
}
}
return START_STICKY;
}

@Override
public void onDestroy() {
player.release();
}

@Override
public void onLowMemory() {

}
}

Update your manifest :

<service android:name=".BackgroundMusicService"
android:exported="false">
<intent-filter>
<action android:name="package_name.action_start_music" />
<action android:name="package_name.action_stop" />
</intent-filter>
</service>

To use:

startService(new Intent(BackgroundMusicService.ACTION_START_MUSIC));

startService(new Intent(BackgroundMusicService.ACTION_STOP_MUSIC));

How to stop all music playing in background with Android (Java)?

Use following code:

   AudioManager.OnAudioFocusChangeListener focusChangeListener =
new AudioManager.OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
AudioManager am = (AudioManager)
getSystemService(AUDIO_SERVICE);
switch (focusChange) {

case
(AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK):
// Lower the volume while ducking.
player.setVolume(0.2f, 0.2f);
break;
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT):
player.pause();
break;

case (AudioManager.AUDIOFOCUS_LOSS):
player.stop();
break;

case (AudioManager.AUDIOFOCUS_GAIN):

player.setVolume(1f, 1f);

break;
default:
break;
}
}
};

AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);

// Request audio focus for playback
int result = am.requestAudioFocus(focusChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);

if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
player.setSource(video);

}


Related Topics



Leave a reply



Submit