Hasan Kaya
Hasan Kaya

Reputation: 11

How do I prevent my media player from stopping when I switch activities but NOT when I hit HOME?

I have an application that plays music. (Also you can close on options menu.)

But the problem is that when you press the home button, the music keeps playing, I want to stop the music when the user presses the HOME Button.

I tried to put onPause() and onStop() method to music.stop(). But it fails because when I start a new activity, the music also stops but I don't want it to, only when the Home button is pressed.

My code is:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.options);
     it=(RadioButton)findViewById(R.id.radio0);
     ti=(RadioButton)findViewById(R.id.radio1);
     but=(ToggleButton)findViewById(R.id.toggleButton1);
     music=MediaPlayer.create(Options.this, R.raw.avril);
   mainmenu=new Intent("com.KAYA.ingilizce_gelistirme.BASLANGIC");


    but.setOnClickListener(new View.OnClickListener()   {

        @Override
        public void onClick(View v) {
            if(but.isChecked()) {
                if(!music.isPlaying())
            music.start();
            }
            else
            if(music.isPlaying())
            music.pause();

        }
    });
     it.setChecked(true);
     Button menu=(Button)findViewById(R.id.button1);
     menu.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            startActivity(mainmenu);
        }
    });

}

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub


    startActivity(new Intent(mainmenu));
    }


@Override
protected void onPause() {

    if(music.isPlaying()){
    music.pause();
    music.release();
    }
    but.setChecked(false);

    super.onPause();

}



@Override
protected void onResume() {
    super.onResume();

}

Here The OPTIONS ACTIVITY where the music starts to play, But when I pass the menu activity, the music also stops.

Upvotes: 1

Views: 2605

Answers (3)

Nic Smith
Nic Smith

Reputation: 11

The best way I found was to have a static boolean in your Application class called 'active' or something. Set it to false when any of your activities are paused and true when your activities are resumed. Then check the status of 'active' in the onStop method. If it is false, you can safely assume the user has clicked home and no other activities have started. Turn off the Media Player here.

Upvotes: 0

AAnkit
AAnkit

Reputation: 27539

There are two ways i can suggest

1) let it be in onPause(), create a flag/boolean that will set to false by default and will be true in every-case such as new activity startup, on back press etc. so if onPause is called and flag is false you can stop the music.

2) you have background service already, you can keep checking which activity is in foreground, if is homeScreen you can stop the music.

Edit :- to know if your app is not in the foreground. as suggested by Brian in another answer. see here you can find if app is foreground or in background and take action accordingly

Upvotes: 1

Brian Attwell
Brian Attwell

Reputation: 9299

You need to launch a separate service to play the music.

method 1

This method scales better for large applications.

Call the following class periodically (once every 3 seconds, for example) inside your music service to see if your app is in the background. Credit: check android application is in foreground or not?

class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {
    @Override
    protected Boolean doInBackground(Context... params) {
        final Context context = params[0];
        return isAppOnForeground(context);
    }

    private boolean isAppOnForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null) {
            return false;
        }
        final String packageName = context.getPackageName();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
                return true;
            }
        }
        return false;
    }
}

method 2

Next, you need to close your service when you detect that your application has been backgrounded. See here: Checking if an Android application is running in the background. Notice that you don't want to manually override onPause and onResume in every class. You want to use a common ancestor where possible.

Upvotes: 1

Related Questions