如何在doInBackground()方法中定期检查isCancelled()

时间:2016-03-08 15:19:26

标签: android android-asynctask

我想取消asynctask并停止其后台执行,我在这个问题中找到了一个解决方案:

  

Android - Cancel AsyncTask Forcefully

但实际上,我在asynctask中的代码是将一些数据上传/发布到服务器,我不知道如何使用循环和根据上述问题的答案打破语句

我的AsyncTask是:

private class Userdataupload extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String[] params) {
        // do above Server call here


        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://www.example.com/example.php");

        int mode = Activity.MODE_PRIVATE;
        SharedPreferences my2 = getSharedPreferences("data", mode);
        String u = my2.getString("name", "error");
        String v = my2.getString("coin", "error");


        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
        nameValuePair.add(new BasicNameValuePair("name", u));
        nameValuePair.add(new BasicNameValuePair("coin", v));

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        try {
            HttpResponse response = httpClient.execute(httpPost);
            // write response to log
            //tdt(response.toString());
            Log.d("Http Post Response:", response.toString());
        } catch (ClientProtocolException e) {
            // Log exception
            e.printStackTrace();
        } catch (IOException e) {
            // Log exception
            e.printStackTrace();
        }

        return null;
    }

   @Override
   protected void onPreExecute()
   {
       pf = new ProgressDialog(MainActivity.this);
       pf.setMessage("Loading User Data...");
       pf.show();
       pf.setCanceledOnTouchOutside(false);
       pf.setCancelable(true);
   }


    @Override
    protected void onPostExecute(String message) {
        //process message
        pf.cancel();

    }
}

1 个答案:

答案 0 :(得分:1)

我想你需要这个

在doinbackground方法中,在带有true值的while循环中运行代码片段。

如果按下iscancelled(),请将其设置为false 打破你的后台进程

这是方式

`int isExecxute=true;
 While(isExecute){
 //run your code
//cancelled break the loop and finish your           execution
 If (iscancelled()) isExecute=false;
  }`