退出App后,有没有办法访问类中的AsyncTask对象?

时间:2015-07-24 15:31:31

标签: java android facebook android-asynctask

我是Android和Java的新手,我想知道退出App后如何访问AsyncTask对象。任何人都可以帮忙吗?我需要在退出应用程序后点击进度条通知时取消在AsyncTask后台进行的图片上传(如facebook图片上传)。我已经搜索过了,但我找不到可能的解决方案。

private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
    @Override
    protected void onPreExecute() {
        // Displays the progress bar for the first time.
        pd = new ProgressDialog(ImageUploadActivity.this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("Uploading Picture...");
        pd.setCanceledOnTouchOutside(true);

        pd.setCancelable(true);
        pd.show();
        pd.setProgress(0);

        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        // updating progress bar value
        mBuilder.setProgress(100, progress[0], false);
        mNotifyManager.notify(MY_NOTIFICATION_ID, mBuilder.build());
        pd.setProgress((int) (progress[0]));
    }


    @Override
    protected String doInBackground(Void... params) {
        return uploadFile();
    }

    @SuppressWarnings("deprecation")
    private String uploadFile() {
        String responseString = null;
        HttpClient httpclient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
        try {
            AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                    new AndroidMultiPartEntity.ProgressListener() {

                        @Override
                        public void transferred(long num) {
                            publishProgress((int) ((num / (float) totalSize) * 100));
                        }
                    });

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            byte[] data = bos.toByteArray();
            /* entity.addPart("uploaded_file", new ByteArrayBody(data,
                        "myImage.jpg"));*/

            File sourceFile = new File(picturePath);
            entity.addPart("uploaded_file",  new FileBody(sourceFile));
            totalSize = entity.getContentLength();
            httppost.setEntity(entity);

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity r_entity = response.getEntity();
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // Server response
                responseString = EntityUtils.toString(r_entity);
            } else {
                responseString = "Error occurred! Http Status Code: "
                        + statusCode;
            }

        } catch (ClientProtocolException e) {
            responseString = e.toString();
        } catch (IOException e) {
            responseString = e.toString();
            response=responseString;
        }
        return responseString;
        // return response;
    }


    @Override
    protected void onPostExecute(String result) {
        Log.e(TAG, "Response from server: " + result);

        // showing the server response in an alert dialog
        //showAlert(result);
        serverCheck(result);
        if(isInternetPresent==false) {
            mBuilder.setContentText("Turn on Internet");
        }
        else {
            mBuilder.setContentText("Upload Complete");

            playSound();
            mBuilder.setAutoCancel(true);
            progressBarNotificationComplete();
        }
        // mBuilder.setContentText("Upload Complete");
        // Removes the progress bar
        mBuilder.setProgress(0, 0, false);
        mNotifyManager.notify(MY_NOTIFICATION_ID, mBuilder.build());
        pd.dismiss();

        super.onPostExecute(result);

    }
}

我有一个进度条通知,会在上传开始时通知。

我的通知

 public void progressBarNotificationComplete() {
    mBuilder = new NotificationCompat.Builder(ImageUploadActivity.this);
    mBuilder.setContentTitle("Upload")
            .setContentText("Upload Completed")
            .setSmallIcon(R.drawable.ic_launcher);

    // mBuilder.setProgress(100, 0, false);

    Intent notificationIntent = new Intent(this, ImageUploadActivity.class);
    notificationIntent.putExtra("FROM_NOTIFICATION", true);
    // notificationIntent.putExtra("first_state", 2);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,  PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(contentIntent);
    Toast.makeText(getApplicationContext(),
            "pendingintent", Toast.LENGTH_SHORT).show();

    mNotifyManager.notify(MY_NOTIFICATION_ID, mBuilder.build());
}

此处待处理的意图将调用上传活动,我在上传活动中有一个警报对话框以取消上传。在我退出应用程序之前,此功能正常。但是,如果我退出应用程序,我知道活动将被销毁,上传将在后台完成。如果要取消上传,该怎么办?我尝试了意向服务,但意图服务仅在完成每个意图请求后停止。我也尝试过后台服务。所以我在一个线程中编写了网络连接的代码,我试图在点击取消按钮时停止该线程,但它不起作用。我非常失望。这个问题的解决方案是什么?

1 个答案:

答案 0 :(得分:0)

在活动的onStop方法中取消您的任务。

在此处阅读有关活动生命周期的更多信息:

http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

另一种方法是将长时间运行的进程移动到一个服务,该服务将在后台继续,即使应用程序已关闭,使您可以更好地控制长时间运行的进程(例如,当活动死亡时取消长时间运行的进程)。 p>