2012-05-30 25 views
5

Dưới đây là mã của tôi để tải tệp lên máy chủ. Nhưng tôi nhận được ngoại lệ mạng ngay cả sau nhiều lần thử và thậm chí sau khi thêm chế độ nghiêm ngặt.Tôi làm cách nào để sử dụng Tác vụ không đồng bộ để tải tệp lên máy chủ?

Tôi mới sử dụng Android và không biết làm cách nào tôi có thể sử dụng tác vụ không đồng bộ, mà nhiều người đã khuyên dùng cho loại hoạt động mạng như vậy. Bất cứ ai có thể cho tôi biết rằng tôi là sai trong mã và nơi tôi nên sử dụng công việc async?

package de.fileuploader; 

import java.io.BufferedReader; 
import java.io.File; 
import java.io.InputStreamReader; 

import org.apache.http.HttpResponse; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.mime.HttpMultipartMode; 
import org.apache.http.entity.mime.MultipartEntity; 
import org.apache.http.entity.mime.content.ByteArrayBody; 
import org.apache.http.entity.mime.content.FileBody; 
import org.apache.http.entity.mime.content.StringBody; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.protocol.BasicHttpContext; 
import org.apache.http.protocol.HttpContext; 

import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.DialogInterface; 
import android.os.Bundle; 
import android.os.StrictMode; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 

@SuppressWarnings("unused") 
public class Android_helloActivity extends Activity { 

private String newName = "SMSBackup.txt"; 
private String uploadFile = "/mnt/sdcard/SMSBackup.txt"; 
private String actionUrl = "http://192.168.1.8:8080/admin/admin/uploads"; 
// private String 
// actionUrl="http://upload-file.shcloudapi.appspot.com/upload"; 
private TextView mText1; 
private TextView mText2; 
private Button mButton; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() 
     .detectDiskReads() 
     .detectDiskWrites() 
     .detectNetwork() // or .detectAll() for all detectable problems 
     .penaltyLog() 
     .build()); 
     StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() 
     .detectLeakedSqlLiteObjects() 
     .detectLeakedClosableObjects() 
     .penaltyLog() 
     .penaltyDeath() 
     .build()); 

     mText1 = (TextView) findViewById(R.id.myText2); 
     mText1.setText("Upload\n" + uploadFile); 
     mText2 = (TextView) findViewById(R.id.myText3); 
     mText2.setText("To Server Location\n" + actionUrl); 

     mButton = (Button) findViewById(R.id.myButton); 
     mButton.setOnClickListener(new View.OnClickListener() { 
       public void onClick(View v) { 
         /* uploadFile(); */ 
         try { 
           HttpClient httpClient = new DefaultHttpClient(); 
           HttpContext localContext = new BasicHttpContext(); 
           HttpPost httpPost = new HttpPost(actionUrl); 

           MultipartEntity entity = new MultipartEntity(
               HttpMultipartMode.BROWSER_COMPATIBLE); 
           entity.addPart("name", new StringBody(newName)); 
           File file=new File(uploadFile); 
           entity.addPart("file", new FileBody(file)); 
           //entity.addPart("file", new 
           ByteArrayBody(data,"myImage.jpg")); 
           entity.addPart("gps", new StringBody("35.6,108.6")); 
           httpPost.setEntity(entity); 
           HttpResponse response = httpClient.execute(httpPost, 
               localContext); 
           BufferedReader reader = new BufferedReader(
               new 
           InputStreamReader(response.getEntity().getContent(), 
           "UTF-8")); 

           String sResponse = reader.readLine(); 
           Log.i("info", "test"); 
            } catch (Exception e) { 
           // Log.e("exception", e.printStackTrace()); 
           e.printStackTrace(); 
           showDialog("" + e); 
           } 
           } 
           }); 
           } 


          private void showDialog(String mess) { 
       new AlertDialog.Builder(Android_helloActivity.this).setTitle("Message") 
         .setMessage(mess) 
         .setNegativeButton("Exit", new DialogInterface.OnClickListener() { 
           public void onClick(DialogInterface dialog, int which)  { 
           } 
         }).show(); 
} 
} 

Trả lời

6
mButton.setOnClickListener(new View.OnClickListener() { 
       public void onClick(View v) { 

new UploadImageTask().execute(); // initialize asynchronous task 

}}); 

//Now implement Asynchronous Task 


public class Get_User_Data extends AsyncTask<Void, Void, Void> { 

      private final ProgressDialog dialog = new ProgressDialog(
      MyActivity.this); 

    protected void onPreExecute() { 
     this.dialog.setMessage("Loading..."); 
     this.dialog.setCancelable(false); 
     this.dialog.show(); 
    } 
     @Override 
     protected Void doInBackground(Void... params) { 

        uploadImage(); // inside the method paste your file uploading code 
      return null; 
     } 

     protected void onPostExecute(Void result) { 

      // Here if you wish to do future process for ex. move to another activity do here 

      if (dialog.isShowing()) { 
       dialog.dismiss(); 
      } 

     } 
    } 

Để biết thêm thông tin tham khảo liên kết này http://vikaskanani.wordpress.com/2011/01/29/android-image-upload-activity/

-3
/** 
* *******Async Task for Use this UTILITY CLASS * 
* pass the file which need to upload * 
* Progress dialog commente/ Uncomment according requirment*******/ 

private class ImageUploaderTask extends AsyncTask<String, Integer, Void> { 
    @Override 
    protected void onPreExecute(){ 
     // simpleWaitDialog = ProgressDialog.show(BlogPostExamplesActivity.this, "Wait", "Uploading Image"); 
    } 
    @Override 
    protected Void doInBackground(String... params) { 
     new ImageUploadUtility().uploadSingleImage(params[0]); 
     return null; 
    } 
    @Override 
    protected void onPostExecute(Void result){ 
     // simpleWaitDialog.dismiss(); 
    } 

    /** 
    * Method uploads the image using http multipart form data. 
    * We are not using the default httpclient coming with android we are using the new from apache 
    * they are placed in libs folder of the application 
    * 
    * @param imageData 
    * @param filename 
    * @return 
    * @throws Exception 
    */ 
    static boolean doUploadinBackground(final byte[] imageData, String filename) throws Exception{ 
     String responseString = null; 
     PostMethod method; 
     method = new PostMethod("your url to upload"); 
     org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(); 
     client.getHttpConnectionManager().getParams().setConnectionTimeout(
                      100000); 
     FilePart photo = new FilePart("userfile", new ByteArrayPartSource(
                      filename, imageData)); 
     photo.setContentType("image/jpeg"); 
     photo.setCharSet(null); 
     String s = new String(imageData); 
     Part[] parts = { 
      new StringPart("latitude", "123456"), 
      new StringPart("longitude","12.123567"), 
      new StringPart("imei","1234567899"), 
      new StringPart("to_email","some email"), 
      photo 
     }; 
     method.setRequestEntity(new MultipartRequestEntity(parts, method 
                  .getParams())); 
     client.executeMethod(method); 
     responseString = method.getResponseBodyAsString(); 
     method.releaseConnection(); 
     Log.e("httpPost", "Response status: " + responseString); 
     if (responseString.equals("SUCCESS")) { 
      return true; 
     } else { 
      return false; 
     } 
    } 
    /** 
    * Simple Reads the image file and converts them to Bytes 
    * 
    * @param file name of the file 
    * @return byte array which is converted from the image 
    * @throws IOException 
    */ 
    public static byte[] getBytesFromFile(File file) throws IOException { 
     InputStream is = new FileInputStream(file); 
     // Get the size of the file 
     long length = file.length(); 
     // You cannot create an array using a long type. 
     // It needs to be an int type. 
     // Before converting to an int type, check 
     // to ensure that file is not larger than Integer.MAX_VALUE. 
     if (length > Integer.MAX_VALUE) { 
      // File is too large 
     } 
     // Create the byte array to hold the data 
     byte[] bytes = new byte[(int)length]; 
     // Read in the bytes 
     int offset = 0; 
     int numRead = 0; 
     while (offset < bytes.length 
       && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { 
      offset += numRead; 
     } 
     // Ensure all the bytes have been read in 
     if (offset < bytes.length) { 
      throw new IOException("Could not completely read file "+file.getName()); 
     } 
     // Close the input stream and return bytes 
     is.close(); 
     return bytes; 
    } 
} 
+0

này không thể đọc được. Vui lòng định dạng mã của bạn bằng cách thụt lề bằng bốn dấu cách. – aliteralmind

Các vấn đề liên quan