线程是否在下次运行相同的应用程序时记住它的状态?

时间:2013-08-20 10:04:52

标签: java android

我试图将麦克风处获得的音频样本传递给扬声器
这是我正在使用的代码,使用suggestions I obtained here

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;  // 1024 ORIGINAL
    final int WAV_SAMPLE_MULTIPLICATION_FACTOR = 1;
    int i= 0;
    boolean isPlaying = true;
    class MyThread extends Thread{
        private boolean passThroughMode = true;
        /*
        @Override
        public void run(){
            recordAndPlay(passThroughMode);
        }
        */

        MyThread(){
            super();
        }

        MyThread(boolean newPTV){
            this.passThroughMode = newPTV;
        }

        @Override
        public void run(){
            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 (passThroughMode) {
            while (!isInterrupted()) {
                num = record.read(lin, 0, SIZE_OF_RECORD_ARRAY);
                for(i=0;i<lin.length;i++)
                    lin[i] *= WAV_SAMPLE_MULTIPLICATION_FACTOR; 
                track.write(lin, 0, num);
            }
        }
        /*
        public void stopThread(){
            passThroughMode = false;
        }
        */
    }

    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.MODE_IN_COMMUNICATION);
        init();
        newThread = new MyThread(true);
        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(boolean pTM) {
        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 (pTM) {
            num = record.read(lin, 0, SIZE_OF_RECORD_ARRAY);
            for(i=0;i<lin.length;i++)
                lin[i] *= WAV_SAMPLE_MULTIPLICATION_FACTOR; 
            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");
        }
        else{
           record.stop();
           track.pause();
           isPlaying=false;
           playBtn.setText("Pass through");
        }
        // */
    }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // android.os.Process.killProcess(android.os.Process.myPid());
        // killProcess(android.os.Process.myPid());
        // newThread.stopThread();
        newThread.interrupt();
    }
}

在第一次运行期间,程序运行正常,麦克风的声音传递到扬声器,当我按下返回按钮时线程似乎停止,因此当应用程序退出时,传递停止。但是,如果我再次运行应用程序,则不会发生通过。是

newThread = new MyThread(true);
newThread.start();  

每次执行应用程序时都会启动一个新线程(也就是调用onCreate()),还是出于某种原因记得旧线程的状态?如何完全重置此应用程序,以便每次执行一个全新的应用程序时都会启动?

---编辑---

没有中断的替代版本:

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;  // 1024 ORIGINAL
    final int WAV_SAMPLE_MULTIPLICATION_FACTOR = 1;
    int i= 0;
    boolean isPlaying = true;
    class MyThread extends Thread{
        private volatile boolean passThroughMode = true;
         /*
        @Override
        public void run(){
            recordAndPlay(passThroughMode);
        }
        // */


        // /*
        MyThread(){
            super();
        }

        MyThread(boolean newPTV){
            this.passThroughMode = newPTV;
        }
        // */

        // /*
        @Override
        public void run(){
            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 (passThroughMode) {
            // while (!isInterrupted()) {
                num = record.read(lin, 0, SIZE_OF_RECORD_ARRAY);
                for(i=0;i<lin.length;i++)
                    lin[i] *= WAV_SAMPLE_MULTIPLICATION_FACTOR; 
                track.write(lin, 0, num);
            }
            record.stop();
            track.stop();
            record.release();
            track.release();
        }
        // */

        // /*
        public void stopThread(){
            passThroughMode = false;
        }
        // */
    }

    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.MODE_IN_COMMUNICATION);
        init();
        Log.d("MYLOG", "onCreate() called");

        //Toast.makeText(getApplicationContext(), "HERE", Toast.LENGTH_SHORT).show();
        // newThread = new MyThread(true); // -> Moved this to onResume();
        // newThread = new MyThread();
        // newThread.start(); // -> Moved this to onResume()
        // newThread.run();
    }

    @Override
    protected void onResume(){
        super.onResume();
        // newThread.stopThread();
        Log.d("MYLOG", "onResume() called");
        newThread = new MyThread(true);
        newThread.start(); 
    }

    @Override
    protected void onPause(){
        super.onPause();
        Log.d("MYLOG", "onPause() called");
        newThread.stopThread();
        // android.os.Process.killProcess(android.os.Process.myPid());
    }


    @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(boolean pTM) {
        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 (pTM) {
            num = record.read(lin, 0, SIZE_OF_RECORD_ARRAY);
            for(i=0;i<lin.length;i++)
                lin[i] *= WAV_SAMPLE_MULTIPLICATION_FACTOR; 
            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");
        }
        else{
           record.stop();
           track.pause();
           isPlaying=false;
           playBtn.setText("Pass through");
        }
        // */
    }

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

    // /*
    @Override
    protected void onDestroy() {
        super.onDestroy();
        newThread.stopThread();
        // android.os.Process.killProcess(android.os.Process.myPid());
        // killProcess(android.os.Process.myPid());
        // newThread.interrupt();
         Log.d("MYLOG", "onDestroy() called");
    }
    // */
}  

---编辑2 ---

08-20 20:57:58.266: D/MYLOG(21936): onResume() called
08-20 20:57:58.266: W/dalvikvm(21936): threadid=11: thread exiting with uncaught exception (group=0x416f5700)
08-20 20:57:58.266: E/AndroidRuntime(21936): FATAL EXCEPTION: Thread-897
08-20 20:57:58.266: E/AndroidRuntime(21936): java.lang.IllegalStateException: startRecording() called on an uninitialized AudioRecord.
08-20 20:57:58.266: E/AndroidRuntime(21936):    at android.media.AudioRecord.startRecording(AudioRecord.java:517)
08-20 20:57:58.266: E/AndroidRuntime(21936):    at com.example.mypassthrough.MainActivity$MyThread.run(MainActivity.java:54)
08-20 20:57:58.286: D/MYLOG(21936): onPause() called
08-20 20:57:58.366: D/MYLOG(21936): onDestroy() called

2 个答案:

答案 0 :(得分:1)

不,Thread个实例中没有Activity个对象的状态持久性。 然而,您错误地认为每次运行应用时都会获得新的活动。活动将持续到Android OS决定删除它们为止。只有这样,一旦您再次进入应用程序,就会创建一个新实例 - 否则,您将获得与以前相同的活动,并且在这种情况下不再调用onCreate()

换句话说,您应该使用onResume()onPause()代替init / deinit。有关详细信息,请查看lifecycle page

编辑:另一个问题是您正在使用interrupt()来控制线程的流量。这并不总是一个好主意,因为interrupt()several side effects and may not even set the interrupt status to true depending on what's going with the thread。您应该使用“shouldStop”字段,因为那时语义是由您设置的。

请注意,此“shouldStop”字段应为字段,将其作为参数传递将无效。你应该在MyThread中找到类似的东西:

    @Override
    public void run(){
        short[] lin = new short[SIZE_OF_RECORD_ARRAY];
        int num = 0;
        record.startRecording();
        track.play();
        while (passThroughMode) {
            num = record.read(lin, 0, SIZE_OF_RECORD_ARRAY);
            for(i=0;i<lin.length;i++)
                lin[i] *= WAV_SAMPLE_MULTIPLICATION_FACTOR; 
            track.write(lin, 0, num);
        }
    }

onPause()

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

如果线程仍未停止,则调用将阻止它,这对于I / O操作来说是典型的。

编辑2:另一个问题是,当玩家线程为stop()release()时你没有AudioTrackAudioRecord关闭(在while循环之后)。 使用与I / O相关的东西时的经验法则是它经常附加到“本机”资源,这需要明确的“手动”释放(有时候是分配)。在这些情况下,您应该始终检查类API。

编辑3: ... MyThread实例以及所有其他资源应在onResume()中初始化完全 ,包括在onCreate()上创建新鲜的实例,

答案 1 :(得分:0)

您的线程是一个内部类,它具有并使用对外部类MainActivity的引用。这样,即使新线程对象本身不从先前实例继承任何内容,线程的第二个实例也可能与第一个实例的运行方式不同。正如@TheTerribleSwiftTomato所说,你的活动可能会持续存在。