相关疑难解决方法(0)

Android - 强力取消AsyncTask

我在我的一个活动中实现了AsyncTask:

 performBackgroundTask asyncTask = new performBackgroundTask();
 asyncTask.execute();
Run Code Online (Sandbox Code Playgroud)

现在,我需要实现"取消"按钮功能,所以我必须停止执行正在运行的任务.我不知道如何停止运行任务(后台任务).

所以请建议我,如何有力地取消AsyncTask?

更新:

我找到Cancel()了相同的方法,但我发现调用cancel(boolean mayInterruptIfRunning)不一定会停止执行后台进程.似乎发生的一切是AsyncTask将执行onCancelled(),并且在完成时不会运行onPostExecute().

android android-asynctask

62
推荐指数
4
解决办法
9万
查看次数

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 …
Run Code Online (Sandbox Code Playgroud)

android android-asynctask

3
推荐指数
1
解决办法
6579
查看次数

标签 统计

android ×2

android-asynctask ×2