我正在制作用于听希腊语 .mp3 单词的应用程序,所以我有媒体播放器,在 1000 毫秒后它应该显示下一个单词取决于 .mp3 文件,所以我有 3 个功能播放、暂停和停止。我需要暂停线程然后继续当它结束时。在我的线程中没有通过调用通知来工作暂停方法我根本不知道如何在调用通知()之前锁定对象..这是我的代码我会很高兴每一个帮助..
class MyinnerThread implements Runnable {
String name;
Thread tr;
boolean suspendFlag;
int i = 0;
MyinnerThread(String threadname) {
name = threadname;
tr = new Thread(this, name);
suspendFlag = false;
tr.start();
}
public void run() {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
if(i == 0){tv1.setText("trhead1");}
if(i == 1){tv2.setText("trhead2");}
if(i == 2){tv3.setText("trhead3");}
if(i == 3){tv4.setText("trhead4");}
if(i == 4){tv5.setText("trhead5");}
if(i == 5){tv6.setText("trhead6");}
if(i == 6){tv7.setText("trhead7");}
if(i == 7){tv8.setText("trhead8");}
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(this) {
while(suspendFlag) {
try {
tr.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
i++;
}
});
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
}
void mysuspend() {
suspendFlag = true;
}
synchronized void myresume() {
suspendFlag = false;
tr.notify();
}
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.play:
if(mp.isPlaying()){
mp.pause();
play.setBackgroundResource(R.drawable.play);
t.mysuspend();
Toast.makeText(getApplicationContext(), "Pause", Toast.LENGTH_SHORT).show();
}
else if(!mp.isPlaying()){
mp.start();
if(runningThread){
t.myresume();
}
if(!runningThread){
runningThread = true;
t = new MyinnerThread("name");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(), "Play", Toast.LENGTH_SHORT).show();
play.setBackgroundResource(R.drawable.pause);
}
break;
case R.id.stop:
Toast.makeText(getApplicationContext(), "Stop", Toast.LENGTH_SHORT).show();
mp.release();
Thread.currentThread().interrupt();
t = null;
runningThread = false;
setPlayer();
play.setBackgroundResource(R.drawable.play);
break;
}
}