启动时线程崩溃的代码(android初学者)

时间:2013-08-19 10:02:26

标签: java android

我正在尝试制作一个应用程序,将通过麦克风获得的音频样本传递给扬声器。这是源代码:

public class MainActivity extends Activity {
    AudioManager am = null;
    AudioRecord record =null;
    AudioTrack track =null;
    final int SAMPLE_FREQUENCY = 44100;
    final int SIZE_OF_RECORD_ARRAY = 1024;
    boolean isPlaying = false;
    class MyThread extends Thread{
        @Override
        public void run(){
            recordAndPlay();
        }
    }

    MyThread newThread;

    private void init() {
        int min = AudioRecord.getMinBufferSize(SAMPLE_FREQUENCY, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
        record = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION, SAMPLE_FREQUENCY, AudioFormat.CHANNEL_IN_MONO,
                                 AudioFormat.ENCODING_PCM_16BIT, min);
        int maxJitter = AudioTrack.getMinBufferSize(SAMPLE_FREQUENCY, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
        track = new AudioTrack(AudioManager.MODE_IN_COMMUNICATION, SAMPLE_FREQUENCY, AudioFormat.CHANNEL_OUT_MONO,
                               AudioFormat.ENCODING_PCM_16BIT, maxJitter, AudioTrack.MODE_STREAM);
     }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        init();
        newThread.start();
    }

    @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;
    }

    private void recordAndPlay() {
        short[] lin = new short[SIZE_OF_RECORD_ARRAY];
        int num = 0;
        am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        am.setMode(AudioManager.MODE_IN_COMMUNICATION);
        record.startRecording();
        track.play();
        while (true) {
            num = record.read(lin, 0, SIZE_OF_RECORD_ARRAY);
            track.write(lin, 0, num);
        }
    }

    public void passStop(View view){
        Button playBtn = (Button) findViewById(R.id.playBtn);  
        // /*
        if(!isPlaying){
            record.startRecording();
            track.play();
            isPlaying = true;
            playBtn.setText("Pause");
        }
        if(isPlaying){
           record.stop();
           track.pause();
           isPlaying=false;
           playBtn.setText("Pass through");
        }
        // */
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onDestroy(){
        newThread.stop();
    }
}  

不幸的是,一旦我尝试通过eclipse运行它,这个程序就会停止。这是我在logcat中得到的,但我不确定这一切意味着什么:

08-19 18:58:43.365: D/AndroidRuntime(27915): Shutting down VM
08-19 18:58:43.365: W/dalvikvm(27915): threadid=1: thread exiting with uncaught exception (group=0x4161f700)
08-19 18:58:43.365: E/AndroidRuntime(27915): FATAL EXCEPTION: main
08-19 18:58:43.365: E/AndroidRuntime(27915): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mypassthrough/com.example.mypassthrough.MainActivity}: java.lang.NullPointerException
08-19 18:58:43.365: E/AndroidRuntime(27915):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
08-19 18:58:43.365: E/AndroidRuntime(27915):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
08-19 18:58:43.365: E/AndroidRuntime(27915):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-19 18:58:43.365: E/AndroidRuntime(27915):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
08-19 18:58:43.365: E/AndroidRuntime(27915):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-19 18:58:43.365: E/AndroidRuntime(27915):    at android.os.Looper.loop(Looper.java:137)
08-19 18:58:43.365: E/AndroidRuntime(27915):    at android.app.ActivityThread.main(ActivityThread.java:5103)
08-19 18:58:43.365: E/AndroidRuntime(27915):    at java.lang.reflect.Method.invokeNative(Native Method)
08-19 18:58:43.365: E/AndroidRuntime(27915):    at java.lang.reflect.Method.invoke(Method.java:525)
08-19 18:58:43.365: E/AndroidRuntime(27915):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-19 18:58:43.365: E/AndroidRuntime(27915):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-19 18:58:43.365: E/AndroidRuntime(27915):    at dalvik.system.NativeStart.main(Native Method)
08-19 18:58:43.365: E/AndroidRuntime(27915): Caused by: java.lang.NullPointerException
08-19 18:58:43.365: E/AndroidRuntime(27915):    at com.example.mypassthrough.MainActivity.onCreate(MainActivity.java:46)
08-19 18:58:43.365: E/AndroidRuntime(27915):    at android.app.Activity.performCreate(Activity.java:5133)
08-19 18:58:43.365: E/AndroidRuntime(27915):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-19 18:58:43.365: E/AndroidRuntime(27915):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
08-19 18:58:43.365: E/AndroidRuntime(27915):    ... 11 more  

这段代码崩溃的原因是什么,以及如何调试?我很确定它与Thread有关,因为我的其他版本的代码我没有包含Thread,所以在启动时不会崩溃。

3 个答案:

答案 0 :(得分:4)

变量newThread未在oncreate() method中初始化,这就是它提供nullpointer exception

的原因

在你的init()方法中添加它将起作用

newThread=new Thread();

答案 1 :(得分:2)

您正在获取空指针异常,因为尚未初始化newThread,并且当您尝试启动它时它为null。该线程也没有任何事情可做。您应该考虑在您的活动而不是线程中实现runnable,handler和timer。

答案 2 :(得分:0)

使用子类扩展AsyncTask类

class TestActivity extends AsyncTask <String, Void, String > {
  protected String doInBackground(String... urls) {
    // execution
  }
  protected void onPostExecute(String result) {
    // post execution
  }
  protected void onPreExecute() {
    super.onPreExecute();
    // initial activities
  }
}