MediaPlayer崩溃onStop()

时间:2014-09-26 21:51:50

标签: android android-mediaplayer

我刚刚制作了一个播放声音的示例应用。播放工作,但如果我按下按钮我的应用程序崩溃。代码似乎在我看来是正确的:

public class MainActivity extends Activity {

private MediaPlayer mediaPlayer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    playAlarm();
    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new ButtonClick());
}

private void playAlarm() {
    Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
    try {
        mediaPlayer.setDataSource(this, alert);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        mediaPlayer.setLooping(true);
        mediaPlayer.prepare();
        mediaPlayer.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private class ButtonClick implements View.OnClickListener {
    @Override
    public void onClick(View v) {
        mediaPlayer.stop(); //Getting a NullPointerException
        finish();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

我不知道如何解决这个问题。 提前谢谢!

1 个答案:

答案 0 :(得分:1)

如果您在点击按钮之前确实发生了playAlarm()。你需要在mediaPlayer.setDataSource(this,alert)之前使用mediaPlayer = new MediaPlayer(); (这里还有其他错误,但这是NPE的原因)。您还应该删除e.printstackTrace()并让它发生。