我的代码发送数据到服务器我希望取消Asynctask
点击后退按钮我尝试了很多但我无法取消Asynctask
怎么做?
public class sendcomment extends AsyncTask{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pr = ProgressDialog.show(sendques.this, null, null, true);
pr.setContentView(R.layout.progressdialog);
pr.getWindow().setBackgroundDrawable(newColorDrawable(android.graphics.Color.TRANSPARENT));
pr.setCancelable(true);
pr.show();
pr.setOnCancelListener(new ProgressDialog.OnCancelListener() {
@Override
public void onCancel(DialogInterface arg0) {
pr.cancel();
new sendcomment().cancel(true);
}
});
}
@Override
protected Object doInBackground(Object... arg0) {
// TODO Auto-generated method stub
try{
String data=URLEncoder.encode("name","utf8")+"="+URLEncoder.encode(ename.getText().toString()+"","utf8");
data+="&"+URLEncoder.encode("email","utf8")+"="+URLEncoder.encode(eemail.getText().toString()+"","utf8");
data+="&"+URLEncoder.encode("phone","utf8")+"="+URLEncoder.encode(ephone.getText().toString()+"","utf8");
data+="&"+URLEncoder.encode("question","utf8")+"="+URLEncoder.encode(equestion.getText().toString()+"","utf8");
data+="&"+URLEncoder.encode("serial","utf8")+"="+URLEncoder.encode(phoneserialnumber+"","utf8");
data+="&"+URLEncoder.encode("model","utf8")+"="+URLEncoder.encode(devicemodel+"","utf8");
data+="&"+URLEncoder.encode("androidv","utf8")+"="+URLEncoder.encode(androidOS+"","utf8");
URL link=new URL(Main.url+"getquestion.php");
URLConnection connect=link.openConnection();
//send data
connect.setDoOutput(true);
OutputStreamWriter wr=new OutputStreamWriter(connect.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader=new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine()) != null){
sb.append(line);
}
res=sb.toString();
}catch(Exception e){
res=e.toString();
}
return "";
}
@Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(res.equals("ok")){
Builder alert = new AlertDialog.Builder(sendques.this);
alert.setTitle("your code: "+pnom+"");
alert.setMessage("your comment recieved!");
alert.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Finish activity
finish();
}
});;
alert.show();
pr.cancel();
}
}
}`
我的所有代码都是按发送按钮
发送数据和数据谢谢
答案 0 :(得分:0)
new sendcomment().cancel(true);
您尝试取消新任务。
mySendCommentTask = new sendcomment();
mySendCommentTask.cancel(true);
P.S不要使用AsyncTask。
答案 1 :(得分:0)
试试这个
// Initialize and execute
sendcomment mySendCommentTask = new sendcomment();
mySendCommentTask.execute();
// and when you need to cancel
mySendCommentTask.cancel(true);
答案 2 :(得分:0)
取消AsyncTask可能会很痛苦 -
而不是new sendcomment().cancel(true);
尝试sendcomment.this.cancel(true);
要测试它,请知道如果AsyncTask成功取消,onPostExecute()
将无法运行,而onCancelled()
将会运行,因此请在onCancelled()
中放置一些内容以便您可以判断它是否为{{1}}调用,如果这意味着AsyncTask被取消。