3

I want to kill an Activity when the user presses the Home button. For this I'm using the following code:

public void onPause() {
    super.onPause();
    this.finish();
}

It works fine. But instead of Home if the user presses the Back button it also kills the activity. I want the back button to perform as usual i.e it should take the user to the previous activity. Any thoughts?

The following is the code of my Activity class:

public class HomeScreen extends Activity {
    /** Called when the activity is first created. */
        private Button btn_play;
        private MediaPlayer mp = new MediaPlayer();
        private static int AUDIO_NO = 1;
        public static String isVideoSelected = "";
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            try{
                btn_play = (Button)findViewById(R.id.btn_play);
                btn_play.setOnClickListener(btn_listener);
                if(isVideoSelected!="") isVideoSelected="";
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        play_audio(AUDIO_NO);
                    }
                }, 1000);
            } catch(Exception e) {

            }
        }
        private void play_audio(int slno) {
            try {
                if(slno == 1) mp = MediaPlayer.create(getBaseContext(), R.raw.audio_1);
                else if(slno == 2) mp = MediaPlayer.create(getBaseContext(), R.raw.audio_2);
                mp.setLooping(false);
                mp.setOnCompletionListener(audio_listener);
                mp.start();
            } catch(Exception e) {
                // do nothing
            }
        }
        private MediaPlayer.OnCompletionListener audio_listener = new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                // TODO Auto-generated method stub
                try{
                    mp.release();
                    if(AUDIO_NO == 1) {
                        play_audio(2);
                        AUDIO_NO++;
                    }
                } catch(Exception e) {

                }
            }
        };
        private View.OnClickListener btn_listener = new View.OnClickListener() {        
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                try{
                    if(mp.isPlaying()) {
                        mp.stop();
                        mp.release();
                    }
                    Intent intent = new Intent(getApplicationContext(), ScreenTwo.class);
                    startActivity(intent);
                } catch(Exception e) {

                } finally {
                }
            }
        };
        public void onUserLeaveHint() {
            super.onUserLeaveHint();
            try{
                if(mp.isPlaying()) {
                    mp.stop();
                    mp.release();
                }
                btn_play = null;
            } catch(Exception e) {

            }
        }
        @Override
        public void onDestroy() {
            super.onDestroy();
            try{
                if(mp.isPlaying()) {
                    mp.stop();
                    mp.release();
                }
                btn_play = null;
            } catch(Exception e) {

            }
        }
    }
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Sourav
  • 1,214
  • 14
  • 24

2 Answers2

2

I think you need to give a bit more information about your motivation here: why do you want to kill your activity on Home presses instead of letting the system manage it? What are you trying to accomplish that isn't happening on its own? If it's just a matter of not wanting users task-switching back into a specific activity, check out the various flags you can use for the task stack.

EDIT: In this case, you're probably causing the problem with your catch-all exception handling. Try moving these lines into the finally clause, instead of in the try, and have your Exception handler at least log the exception it's catching (Log.e("tag", "Exception caught; ignoring:", e)). Catch-alls are generally bad programming practice, especially if you're not at least logging the exception so you can see what goes wrong.

        Intent intent = new Intent(getApplicationContext(), ScreenTwo.class);
        startActivity(intent);
Yoni Samlan
  • 37,905
  • 5
  • 60
  • 62
  • @Yoni Samlan I've a button called "play" on the home screen pressing on which takes the user to the 2nd screen. I'm also playing an audio in background in the Home screen. Now, whenever the user presses the Home button to quit the app and comes back again to the homescreen the "Play" button does not work. The log entries reads as follows: `03-07 19:47:36.062: WARN/AudioFlinger(3256): write blocked for 221 msecs, 170 delayed writes, thread 0xbec0`. Therefore I tried to kill the activity on Home presses. – Sourav Mar 07 '11 at 14:18
  • Instead of Home if the user presses Back button to quit the app & starts it again the "play" button on the home screen works fine. – Sourav Mar 07 '11 at 14:26
  • There's probably more to the log than that? But you should look into using a Service to play your music if you want it to play across Activity boundaries. There's also a good amount of information missing here -- how are you playing the audio right now, for example? MediaPlayer? SoundPool? – Yoni Samlan Mar 07 '11 at 20:05
  • @Yoni Samlan I'm playing the audio using MediaPlayer. I don't intend to play it across activities, but only on the homescreen. (The user comes to the homescreen, hears the audio, taps on the button & moves to the 2nd screen). The only other significant log entry I get after the previous one is: `03-08 11:12:38.445: DEBUG/dalvikvm(1635): GC freed 6588 objects / 517232 bytes in 145ms`. Do you think killing the activity might be a good solution in this case? – Sourav Mar 08 '11 at 05:49
  • @Yoni Samlan If I keep on tapping the button on the home screen, then I get the same log entries: `03-08 11:39:53.296: WARN/AudioFlinger(1094): write blocked for 221 msecs, 12 delayed writes, thread 0xbec0 03-08 11:40:05.195: DEBUG/dalvikvm(1748): GC freed 477 objects / 21920 bytes in 115ms 03-08 11:40:08.405: DEBUG/dalvikvm(1178): GC freed 13337 objects / 799288 bytes in 301ms 03-08 11:40:08.405: INFO/dalvikvm-heap(1178): Grow heap (frag case) to 7.416MB for 73112-byte allocation` – Sourav Mar 08 '11 at 06:08
  • so the issue is really that the user can't get to the second screen anymore by clicking the button after backing into the home screen? Please post your code, I'm finding this hard to follow because the problem you're trying to solve seems to have very little bearing on what you're trying to do to solve it. – Yoni Samlan Mar 08 '11 at 16:04
  • @yoni I moved the following lines into the finally clause: `Intent intent = new Intent(getApplicationContext(), ScreenTwo.class); startActivity(intent);` and it worked! I'm able to move into the 2nd screen even after Home presses. However, I don't hear the audio in background when I return to the application after Home press. – Sourav Mar 10 '11 at 06:41
  • 1
    @yoni I created a new Handler to run the audio within an onResume() method. Now it working fine. Many Thanks! – Sourav Mar 10 '11 at 08:13
0

onPause() is called anytime the user leaves your Activity so that is not the place to call finish(). Also I'm not sure if you can override the Home button or if that is something you should really do anyway.

Robby Pond
  • 73,164
  • 16
  • 126
  • 119
  • FYI Google has not implemented any means to override Home Button due to security reasons ,though you can implement it by designing your own HomeScreen App (but that's not the suggested way to get just 'OnPause' Action) – 100rabh Mar 07 '11 at 14:15