1

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.

Yevgeny Simkin
  • 27,946
  • 39
  • 137
  • 236
Hasan Kaya
  • 11
  • 1
  • 4

3 Answers3

1

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

Community
  • 1
  • 1
AAnkit
  • 27,299
  • 12
  • 60
  • 71
  • how can i check background service is homeScreen? i tried your your first advise but there are a problem, i thought all the possibility but the boolean flag was useless, i think only solution is checking homescreen but i cannot find any code to check – Hasan Kaya Feb 02 '13 at 20:16
  • Because, if you passs another Activity, your flag also will be false. And this will crash. – Hasan Kaya Feb 02 '13 at 20:24
  • how come it be false? make it global. handle all possiblities then home screen, as HomeScreen event can not be listen? – AAnkit Feb 02 '13 at 20:26
  • bro, if you call a new Activity, onPause() is also called. and this is not difference between pressing the home and passing the other activity – Hasan Kaya Feb 02 '13 at 20:34
  • yeah, but cant u change the flag to true if calling another activity, Ok, use edited answer, that is better with less chances of leaks? – AAnkit Feb 02 '13 at 20:40
  • oh it is ok, Thank you veryMuch, i ll try it, i wish i will reach the solution, i tireed to thinking :D – Hasan Kaya Feb 02 '13 at 20:43
  • it happens most of the time with me too, that is why we have SO, cheers happy coding, let us know how it goes! – AAnkit Feb 02 '13 at 20:45
1

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.

Community
  • 1
  • 1
Brian Attwell
  • 9,239
  • 2
  • 31
  • 26
0

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.

Nic Smith
  • 11
  • 1
  • 2