简体   繁体   English

Android在UI线程中等待而不冻结它

[英]Android wait in UI thread without freezing it

In my application when user presses a button MediaRecorder starts recording the audio then it continues recording for 50sec and stops automatically.I am starting the recorder from UI Thread but how to wait for 50s without freezing the UI.Here is my code : 在我的应用程序中,当用户按下按钮时MediaRecorder开始记录音频,然后继续记录50秒并自动停止。我从UI Thread启动记录器,但是如何等待50s而不会冻结UI。这是我的代码:

MediaRecorder recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
recorder.setOutputFile(path);
recorder.prepare();
recorder.start();
Thread.sleep(40000);
recorder.stop();
recorder.reset();
recorder.release();

I don't know much about threads.Please help 我对线程了解不多,请帮助

For something like this, Android provides some tools so you don't need a thread. 对于这样的事情,Android提供了一些工具,因此您不需要线程。 If you have a handy View object (or if this code is in a View subclass), you can use View.postDelayed(Runnable, long) to schedule a Runnable to execute after a specific delay (in milliseconds). 如果您有方便的View对象(或者此代码在View子类中),则可以使用View.postDelayed(Runnable, long)安排Runnable在特定的延迟(毫秒)后执行。

// need to make recorder final so it can be referenced from anonymous Runnable
final MediaRecorder recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
recorder.setOutputFile(path);
recorder.prepare();
recorder.start();
postDelayed(new Runnable() {
    @Override
    public void run() {
        recorder.stop();
        recorder.reset();
        recorder.release();
    }
}, 40000);

If you don't have a handy View , just create a Handler and use it's postDelayed method. 如果您没有方便的View ,则只需创建一个Handler并使用它的postDelayed方法即可。 It works the same. 它的工作原理相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM