问题描述
- 一个播放铃音的Helloworld,手机上一运行就崩溃,请帮看看问题在哪?
-
几乎是照抄网上文章的代码,想实际点击button1播放手机铃音,点button2停止,结果在在手机上测试,一点击,APP就崩溃关闭了,请问是哪里不对?import java.io.IOException;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;public class MainActivity extends Activity {
MyThread m;@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button b1=(Button)findViewById(R.id.button1); Button b2=(Button)findViewById(R.id.button2); m=new MyThread(this); b1.setOnClickListener(new OnClickListener(){ public void onClick(View v){ m.start(); } }); b2.setOnClickListener(new OnClickListener(){ public void onClick(View v){ if (m.isAlive()) m.StopAlarmRing(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } class MyThread extends Thread{ MediaPlayer mMediaPlayer; Context mContext; public MyThread(Context context){ mMediaPlayer=new MediaPlayer(); this.mContext=context; } @Override public void run(){ Uri alert=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); try{ mMediaPlayer.setDataSource(mContext,alert); final AudioManager audioManager=(AudioManager) getSystemService(Context.ACCOUNT_SERVICE); if (audioManager.getStreamVolume(AudioManager.STREAM_RING)!=0){ mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING); mMediaPlayer.setLooping(true); try{ mMediaPlayer.prepare(); }catch(IllegalStateException e){ e.printStackTrace(); } } }catch(IOException e){ e.printStackTrace(); } mMediaPlayer.start(); } private void StopAlarmRing(){ mMediaPlayer.stop(); } }
}
解决方案
try{
mMediaPlayer.prepare();
}catch(IllegalStateException e){
e.printStackTrace();
}
}
注掉试试
时间: 2024-09-19 10:11:13