Android停止asynctask

时间:2013-08-04 18:02:44

标签: android android-asynctask

我创建了一个asynctask来显示进度对话框,同时解决用户位置问题。我想运行这个asynctask 30秒,如果在这30秒内我没有找到用户位置,我只想杀死任务并显示错误信息。

到目前为止我的代码是这样的:

userLocation = new AsyncTask<Void, Void, Void>() {

            private ProgressDialog locationDialog = new ProgressDialog(MainActivity.this);

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                locationDialog.setMessage(getResources().getString(R.string.getting_location));
                locationDialog.setCancelable(false);
                locationDialog.setIndeterminate(true);
                locationDialog.show();
            }

            @Override
            protected Void doInBackground(Void... params) {
                    try {
                        latitude = locationProvider.getLatitude();
                        longitude = locationProvider.getLongitude();
                        Thread.sleep(10000);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
            //  getLocation.cancel(true);
                if (latitude != 0 && longitude != 0) {
                    locationDialog.dismiss();
                    getData();
                } else {
                    locationDialog.dismiss();

                    alertDialog.show();

                    Log.d("Couldn't get location", "Couldn't get location");
                }
            }
        };
        userLocation.execute((Void[])null);

如何编辑我的代码,以便如果30秒后的纬度和经度为0,则只需删除asynctask并显示某种错误消息。有什么想法吗?

1 个答案:

答案 0 :(得分:5)

你应该创建一个取消Asynctask(http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean)

的处理程序

向此处理程序发送延迟消息,如:

Handler.sendMessageDelayed(msg, delayMillis)

private android.os.Handler mHandler = new android.os.Handler() {

  @Override
  public void handleMessage(Message msg) {
      (Your AsyncTask object).cancel(true);
  }
}