我正在使用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();
}
}
}
我的问题是,当弹出通知并要求用户停止或继续时,即使再次将running设置为true,线程也不再运行。我知道线程不能在通知窗口上等待,但为什么当用户将running值设置为true时,代码是否会再次运行?
答案 0 :(得分:0)
看看这些代码:
if (fsensor3 > 200)
{
running = false; //To stop thread from repeating
new MyVoltageAlert().execute(fsensor3);
//What do I do here?
}
也许你的问题的原因是,上面的逻辑再次将running设置为false。