在Android中杀死/关闭线程时崩溃

时间:2015-09-03 11:42:13

标签: android multithreading audio-recording audiotrack

我正在制作一个录制和播放音频的程序。它运作良好。但是,问题是当我按下后退按钮(右下角)时程序崩溃。让我看看我干净的代码,请帮我修复它。提前致谢

  private void cleanUp()
  {
    if (track != null)
    {
      mVisualizerView.release();
      track.release();
      track = null;
    }
    if (mWakeLock.isHeld()) { 
        mWakeLock.release();
    }
    if(mIsRecording)
    {       
    mRecorder.stop();
    try {
        //Write file audio
    } catch (IOException e) {

    }
    /////////////////Stop audio service
     _audioManager.stopBluetoothSco();
    }
    mRecorder.release();
  }

@Override
public void onDestroy() {
    cleanUp();
    super.onDestroy();
}

@Override
protected void onPause()
{
    cleanUp();     
    super.onPause();
}

其中,这些变量被构造/用作波纹管代码

private boolean mIsRecording = false;
AudioTrack track =null;
private AudioManager _audioManager;
private VisualizerView mVisualizerView;
protected PowerManager.WakeLock mWakeLock;
private AudioRecord mRecorder;

// Prevent phone from sleeping
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "My Tag"); 
this.mWakeLock.acquire();
//Record audio
private void startBufferedWrite(final File file) {  
    new Thread(new Runnable() {
        @Override
        public void run() {
            DataOutputStream output = null;
            try {
                    output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
                    ///////////Play during recording
                    track.play();                  
                    mVisualizerView = (VisualizerView) findViewById(R.id.visualizerView);
                    mVisualizerView.link(track);
                    while (mIsRecording) {
                    //Write to track
                    }
                }
        }
    }).start();
}

错误就是

FATAL EXCEPTION: Thread-35897
at java.lang.Thread.run(Thread.java:856)

1 个答案:

答案 0 :(得分:1)

你正试图在非UI线程中使用UI元素。这就是崩溃的原因。

你可以尝试这样的事情。

new Thread() {
        public void run() {
            DataOutputStream output = null;
        try {
                output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
                ///////////Play during recording
                track.play();  
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                      mVisualizerView =(VisualizerView) findViewById(R.id.visualizerView);
                     mVisualizerView.link(track);
                     while (mIsRecording) {
                       //Write to track
                       }
                      }
                    });

        }
    }.start();