我需要解决方案来停止我的线程并显示Toast。
这是我的班级 StopperThread ,我尝试用blinker线程停止。
public class StopperThread implements Runnable{
private Context context;
private volatile boolean blinker;
public StopperThread(Context context){
this.context = context;
this.blinker = true;
}
@Override
public void run ()
{
Looper.prepare();
try {
while(blinker) {
Log.e("LOG","ACTIVE");
Thread.sleep(1000);
Toast.makeText(context, "success", Toast.LENGTH_SHORT).show();
}
} catch (InterruptedException e) {
e.printStackTrace();
blinker = false;
}
Looper.loop();
}
public void mystop() {
blinker = false;
}
}
这是我创建线程的Activity里面的 clickedButton 方法。
private void clickedButton() {
final StopperThread stopperThread = new StopperThread(this);
Thread t1 = new Thread(stopperThread);
if(click)
{
t1.start();
click = false;
}
else
{
try {
stopperThread.mystop();
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
click = true;
}
}
我尝试更改
/*First Try*/
final StopperThread stopperThread = new StopperThread(getApplicationContext());
/*Second Try*/
runOnUiThread(new Runnable() {
@Override
public void run() {
t1 = new Thread(stopperThread);
}
});