【发布时间】:2014-09-02 23:01:07
【问题描述】:
我写了以下代码:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
private TextToSpeech mTTS;
@Override
protected void onPause() {
super.onPause();
if (mTTS != null) {
mTTS.stop();
mTTS.shutdown();
}
}
@Override
protected void onResume() {
super.onResume();
mTTS = new TextToSpeech(getApplicationContext(),
new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
mTTS.setLanguage(Locale.ENGLISH);
mTTS.speak("Hello!", TextToSpeech.QUEUE_FLUSH, null);
}
}
});
}
public void onButtonClick(View view) {
mTTS.speak("Hello!", TextToSpeech.QUEUE_FLUSH, null);
}
}
但是这段代码:mTTS = new TextToSpeech(... 将 UI 线程冻结 5-8 秒。
我注意到延迟发生在 logcat 中的这一行(第一行):
07-13 11:51:11.304 5296-5296/com.example.TextToSpeachTest I/TextToSpeech﹕ Connected to ComponentInfo{com.google.android.tts/com.google.android.tts.service.GoogleTTSService}
07-13 11:51:17.317 5296-5296/com.example.TextToSpeachTest I/Choreographer﹕ Skipped 391 frames! The application may be doing too much work on its main thread.
我试图把它放在 AsyncTask 中:
@Override
protected void onResume() {
super.onResume();
MyAsyncTask newTask = new MyAsyncTask() {
protected void onPostExecute(Boolean result) {
}
};
newTask.context = getApplicationContext();
newTask.execute();
}
...
class MyAsyncTask extends AsyncTask<Void, Integer, Boolean> {
private TextToSpeech mTTS;
public Context context;
@Override
protected Boolean doInBackground(Void... arg0) {
mTTS = new TextToSpeech(context,
new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
mTTS.setLanguage(Locale.ENGLISH);
mTTS.speak("Hello!", TextToSpeech.QUEUE_FLUSH, null);
}
}
});
return true;
}
}
但没有任何改变。您能否提出一个合适的解决方案/想法?
此延迟出现在我的手机 LG L4 II (E440) 上。在 Nexus 10 上 – 没有延迟。 我在我的 LG L4 上尝试了来自 Play Store 的不同通话应用程序。在某些应用程序上也存在 UI 阻塞,但有些应用程序没有阻塞。这意味着——可以实施。但是怎么做呢?
【问题讨论】:
-
这个问题解决了吗?现在已经 4 年了。
标签: android multithreading user-interface blocking