我是android編程中的新手。 所以我有一個ArrayList<String>
,我想循環演講,當我點擊一個按鈕時,演講停止,如果我點擊相同的按鈕,演講再次開始。android中的多線程編程
我的佈局是這樣的:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btnPauseResume"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pause" />
</LinearLayout>
和我的Java代碼是這樣的:
public class Activity_test extends Activity {
Button btnPauseResume = null;
boolean IsPaused = false;
private TextToSpeech tts = null;
ArrayList<String> Texts = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
btnPauseResume = (Button) findViewById(R.id.btnPauseResume);
Texts = new ArrayList<String>();
btnPauseResume.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
Activity_test.this.runOnUiThread(new Runnable() {
@Override
public void run() {
IsPaused = !IsPaused;
if (IsPaused) {
btnPauseResume.setText("Resume");
} else {
btnPauseResume.setText("Pause");
Start();
}
}
});
}
}).start();
}
});
Start();
}
public void Start() {
new Thread(new Runnable() {
public void run() {
Texts.clear();
Texts.add("Long Text 1");
Texts.add("Long Text 2");
Texts.add("Long Text 3");
Speech();
}
}).start();
}
public void Speech() {
tts = new TextToSpeech(Activity_test.this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.ENGLISH);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(Activity_test.this, "This Language is not supported", Toast.LENGTH_SHORT).show();
} else {
for (String Text : Texts) {
if (!IsPaused) {
tts.speak(Text, TextToSpeech.SUCCESS, null);
while (tts.isSpeaking()) {
//wait till speech finish
}
}
}
if (!IsPaused) {
Start();
}
}
} else
Toast.makeText(Activity_test.this, "Initilization Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}
實時代碼
文本的數組列表被改變,這就是我所說的原因方法Speach()
將新的ArrayList
加載到語音中。
所以問題是當我點擊按鈕它不工作(和後退按鈕)。
你需要所有這些線程爲什麼? – Egor
我試着點擊一個按鈕,當文本正在講話,它不適用於任何rate.so我試過各種線程和結果是一樣的。 – ehsan
http://www.vogella.com/tutorials/android.html –