嗨,很好,我有以下问题:我有几个切换按钮,当我单击一个调用 AsyncTask 来执行其功能时,但问题是当我返回并单击按钮将其关闭时,我必须停止该线程,我尝试使用我称为“flag”的变量,但当它在 AsyncTask 中分配时也没有分配变量选择。
在这里你有代码:
int falg;
...
btnBoton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0)
{
if(btnBoton.isChecked()){
salir = false;
flag = 1;
verRegistro();}
else{
salir = true;
flag = 0;
}
//accionesScada.desconectar();
}
});
public class conectar extends AsyncTask<String,String,Integer>{
int m;
int startReg;
int count;
String dirIP=new String();
String dirReg=new String();
TextView texto,conectado;
public conectar(String ip,String reg,TextView t,TextView r) {
this.dirIP=ip;
this.dirReg=reg;
this.conectado = t;
this.texto = r;
try {
//IP address;
addr = InetAddress.getByName(dirIP);
startReg = Integer.decode(dirReg).intValue();
} catch (Exception e) {
Log.d("MODBUS","IP error", e);
}
}
protected Integer doInBackground(String... urls) {
m = accionesScada.conectar(addr, port);
resultado = accionesScada.LeerRegistro(startReg, count);
return 0;
}
protected void onPostExecute(Integer bytes) {
if(btnBoton.isChecked() == false){
setFlag(0);
salir = true;
//depurar2.setText(String.valueOf(flag));
depurar.setText("Desconectado");
depurar.setTextColor(Color.RED);
this.cancel(true);
}else{
if(m==1){
conectado.setText("Conectado");
conectado.setTextColor(Color.GREEN);
}
String resul = String.valueOf(resultado);
texto.setText(resul);
}
}
}
public void setFlag(int bandera){
this.abc = bandera;
}
public int getFlag (){
return flag;
}
//tenemos varios tipos de ver registro uno para cada registro que podamos ver simultaneamente en pantalla, para eso esta.
public void verRegistro() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
//accionesScada.desconectar();
try{
String aux = new String();
String aux1 = new String();
try {
//IP address;
aux1 = plc1;
Cursor Creg = (SQLiteCursor)reg.getSelectedItem();
aux = obtenerDireccionRegistro(Creg.getString(0));
} catch (Exception e) {
Log.d("MODBUS","IP error", e);
}
conectar conectamos = new conectar(aux1,aux,depurar,text);
conectamos.execute("");
}catch(Exception e){
Log.d("MODBUS", "Error Timertask");
}
}
});
}
};
//here is the problem, here the flag always what made mark the beginning and at the aynctask not assigned either to the flag value, and do not know why always so here is sending commands to the AsyncTask continuously every second and I I want is to cancel this.
if(flag == 0){
timer.cancel();
depurar2.setText(String.valueOf(flag));}
else if(flag == 1){
depurar2.setText(String.valueOf(flag));
timer.schedule(doAsynchronousTask, 0, 1000);}
}
感谢您的帮助 =)。