开发者

Player getting null after Home button pressed Android

I am creating a streaming player and so far its working fine. I can manage to start and stop the streaming. When I press the home button, the activity is closed but the sound is still playing. I am fine with that, the problem is that when I start the application again and hit the stop button, the object is null. Thats my code:

public class Main extends Activity {

private MediaPlayer player;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

}

public void onPlayClick(View v) {

    try {
        player = new MediaPlayer();
        player.setDataSource("*****");
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);           
        player.setOnPreparedListener(new OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                Log.i("In", "Prepared Listener");
                player.start();
            }
        });
        player.prepareAsync();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

public void onStopClick(View v) {

    if (player != null && player.isPlaying()) {
        player.stop();
        player.release();
        player = null;
    }
}

}

Does anyone know what could be wrong with this simple 开发者_高级运维code? Many Thanks T


You want to put the player in a Service: http://developer.android.com/reference/android/app/Service.html

That way its still valid when you reload the Activity.


I think it is also worth noting that if you are going to go the activity route as opposed to the service, you should probably put

if (player != null && player.isPlaying()) {
    player.stop();
    player.release();
    player = null;
}

inside your onStop(), or onDestroy() method of your activity also. If you put it in onStop() the audio would stop when the home button is pressed(or anytime another activity takes over phone rings perhaps). If you put it in onDestroy() it would keep playing until the system needs the resources that your application is using. Either way it is a good idea so that your app is not holding on the the MediaPlayer resources incase the user doesn't hit the stop button for whatever reason.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜