ynduanlian
2015-02-07 05:49
采纳率: 0%
浏览 1.5k

一个播放铃音的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();
    }
}

}

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • ma477821209 2015-02-10 16:44

    try{
    mMediaPlayer.prepare();
    }catch(IllegalStateException e){
    e.printStackTrace();
    }
    }
    注掉试试

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题