AsyncTask中的ProgressDialog中有一个线程 [英] ProgressDialog in AsyncTask which has a thread in it

查看:98
本文介绍了AsyncTask中的ProgressDialog中有一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将图像上传到我的服务器.因此,我已经构建好了并将其发送到服务器,效果很好.但是缺少一件事,那就是ProgressDialog. 我尝试了很多方法,但不知道如何正确进行. 我现在在preExecute方法的AsyncTask中调用ImageUploader.uploadFile().

I want to upload an image to my server. Therfore i've build this and sending to the server works quite well. Yet one thing is missing, which is ProgressDialog. I tried a lot of ways but don't know how to do it the right way. I call ImageUploader.uploadFile() in an AsyncTask in the preExecute method at the moment.

如同在doInBackground中一样,我必须发送一封带有照片附件的电子邮件.因此,在将照片附加到电子邮件之前,需要先将其上传. 那么如何执行此操作以及如何显示ProgressDialog?

As within the doInBackground i have to send an E-mail which has the photo as attachment with it. So the photo needs to be uploaded before it's attached to the email. So how to do this and how to show the ProgressDialog?

这就是我调用函数的方式:

This is how I Call the function:

       @Override
        protected void onPreExecute(){
            super.onPreExecute();
            if(isPhotoTaken()){
                ImageUploader.uploadFile(getPhotoPath(), "http://www.example.com/upload.php", Step4.this);              
            }
        }

这是我的ImageUploader类

This is my ImageUploader class

    public class ImageUploader {

    private static String serverResponseMessage = "";
    private static int serverResponseCode = 0;
    private static ProgressDialog dialog;

    public static int uploadFile(final String sourceFileUri, final String serverFile, final Context context) {

        Debug.out("SourceFileUri: " + sourceFileUri);
        Debug.out("ServerFile: " + serverFile);
        Thread thread = new Thread() {
            @Override
            public void run() {
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialog = new ProgressDialog(context);
                        dialog.setCancelable(false);
                        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                        dialog.setMessage("Uploading Image... Please wait!");
                        dialog.show();
                    }
                });
                String upLoadServerUri = serverFile;
                String fileName = sourceFileUri;
                HttpURLConnection conn = null;
                DataOutputStream dos = null;
                String lineEnd = "\r\n";
                String twoHyphens = "--";
                String boundary = "*****";
                int bytesRead, bytesAvailable, bufferSize;
                byte[] buffer;
                int maxBufferSize = 1 * 1024 * 1024;
                File sourceFile = new File(sourceFileUri);
                if (!sourceFile.isFile()) {
                    Log.e("uploadFile", "Source File Does not exist");
                }
                try { // open a URL connection to the Servlet
                    Debug.out("in the try");
                    FileInputStream fileInputStream = new FileInputStream(
                            sourceFile);
                    URL url = new URL(upLoadServerUri);
                    conn = (HttpURLConnection) url.openConnection(); // Open a
                                                                        // HTTP
                                                                        // connection
                                                                        // to
                                                                        // the
                                                                        // URL
                    conn.setDoInput(true); // Allow Inputs
                    conn.setDoOutput(true); // Allow Outputs
                    conn.setUseCaches(false); // Don't use a Cached Copy
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Connection", "Keep-Alive");
                    conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                    conn.setRequestProperty("Content-Type",
                            "multipart/form-data;boundary=" + boundary);
                    conn.setRequestProperty("uploaded_file", fileName);
                    dos = new DataOutputStream(conn.getOutputStream());
                    Debug.out("Set Properties and Datastream");
                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                            + fileName + "\"" + lineEnd);
                    dos.writeBytes(lineEnd);
                    Debug.out("Writes data");
                    bytesAvailable = fileInputStream.available(); // create a
                                                                    // buffer of
                                                                    // maximum
                                                                    // size

                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    buffer = new byte[bufferSize];
                    Debug.out("Buffer done");
                    // read file and write it into form...
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    Debug.out("Read Bytes");
                    while (bytesRead > 0) {
                        dos.write(buffer, 0, bufferSize);
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    }

                    // send multipart form data necesssary after file data...
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                    Debug.out("After sendData");
                    // Responses from the server (code and message)
                    serverResponseCode = conn.getResponseCode();
                    serverResponseMessage = conn.getResponseMessage();
                    Debug.out("Server Response: " + serverResponseCode);
                    Log.i("uploadFile", "HTTP Response is : "
                            + serverResponseMessage + ": " + serverResponseCode);
                    Debug.out("HTTP Response is : " + serverResponseMessage
                            + ": " + serverResponseCode);
                    // close the streams //
                    fileInputStream.close();
                    dos.flush();
                    dos.close();
                }

                catch (MalformedURLException ex) {
                    ex.printStackTrace();
                    // Toast.makeText(UploadImageDemo.this,
                    // "MalformedURLException", Toast.LENGTH_SHORT).show();
                    Log.e("Upload file to server", "error: " + ex.getMessage(),
                            ex);
                } catch (Exception e) {
                    e.printStackTrace();
                    // Toast.makeText(UploadImageDemo.this, "Exception : " +
                    // e.getMessage(), Toast.LENGTH_SHORT).show();
                    Log.e("Upload file to server Exception",
                            "Exception : " + e.getMessage(), e);
                }

            }
        };
        thread.start();

        try {
            thread.join();      
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Debug.out("Message: " + serverResponseMessage.toString());
        return serverResponseCode;
    }
}

推荐答案

根据您的评论:" @Tarsem,我想在上传图像时显示进度对话框.因此,当ImageUploader中的线程处于活动状态时."

尝试以下方法:

class imageupload extends AsyncTask<Void, Void, Void> {    
            Dialog dialog;    
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context, "Uploading Image","Please Wait...");
            }    
            @Override
            protected Void doInBackground(Void... params) {
                // Upload Image HERE                    
                return null;
            }
            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                dialog.dismiss();                   
                // You can Call another AsynTask here (achieve sending email work here)             
             }
        }

这篇关于AsyncTask中的ProgressDialog中有一个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆