0
我正在使用android開發。我有我想恢復或取決於按鈕按下停止一個線程,但我不知道爲什麼我的線程將不會恢復... 下面是代碼我將如何恢復並暫停此線程?
public class MainActivity extends Activity {
private Thread clientThread;
Boolean running = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clientThread = new Thread(new Client());
clientThread.start();
}
@SuppressLint("NewApi")
class Client implements Runnable {
@Override
public void run()
{
try {
while (running == true) {
//get sensor data here
if (fsensor3 > 200)
{
running = false; //To stop thread from repeating
new MyVoltageAlert().execute(fsensor3);
//What do I do here?
}
runOnUiThread(new Runnable()
{
@Override
public void run() {
//UI stuff here
}
});
}
}
catch(Exception e){
e.printStackTrace();
}
}
}//End Client Thread
class MyVoltageAlert extends AsyncTask<Integer, Void, Integer>{
@Override
protected Integer doInBackground(Integer... params){
return params[0];
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(result + "mv")
.setTitle("Sensor Warning!");
// Add the buttons
builder.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//What do I do here?
// running = true;
}
});
builder.setNegativeButton("Stop", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//What do I do here?
// running = false;
}
});
// Create the AlertDialog
AlertDialog dialog = builder.create();
dialog.show();
}
}
}
我的問題是,當彈出通知並要求用戶停止或繼續,即使再次將運行設置爲true,線程也不會再運行。我知道線程不能等待通知窗口,但爲什麼當用戶將運行的值設置爲true時,代碼是否不再運行?
我敢肯定,你需要改變爲揮發性布爾running = true; –
我改變了它,但是當我點擊繼續通知線程仍然不會再運行。 – user3166938
你不需要使用clientThread MyVoltageAlert是一種背景線程。 –