我有一个用于将图像上传到服务器的类。 上传时我想显示progressDialog以显示上传的进度。 但不知何故,进度条没有显示出来。 这是我的ImageUploader类:
package com.OBO.Bandenanalyse;
//Imagine Imports here
public class ImageUploader {
private Context context;
private ProgressDialog dialog;
public ImageUploader(Context ctx) {
this.context = ctx;
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
dialog = new ProgressDialog(context);
dialog.setCancelable(false);
dialog.setMessage("Uploading Image... Please wait!");
dialog.show();
}
});
}
private static String serverResponseMessage = "";
private static int serverResponseCode = 0;
public int uploadFile(final String sourceFileUri, final String serverFile) {
Debug.out("SourceFileUri: " + sourceFileUri);
Debug.out("ServerFile: " + serverFile);
Thread thread = new Thread() {
@Override
public void run() {
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();
dialog.dismiss();
}
catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
// Toast.makeText(UploadImageDemo.this,
// "MalformedURLException", Toast.LENGTH_SHORT).show();
Log.e("Upload file to server", "error: " + ex.getMessage(),
ex);
} catch (Exception e) {
dialog.dismiss();
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();
Debug.out("done uploading");
dialog.dismiss();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Debug.out("Message: " + serverResponseMessage.toString());
return serverResponseCode;
}
}
我正在AsyncTask中调用该函数,因为我还需要做其他事务。我这样做:
private class MyAsyncTask extends AsyncTask<Mail, Integer, Double>{
/**
* Private boolean to check if a tire is repairable or not.</br>
*/
boolean _repairable = Step4._isRepairable;
/**
* Private integer which counts how many times we've tried to send the Email.
*/
private int _counter = 0;
private ProgressDialog dialog;
@Override
protected void onPreExecute(){
super.onPreExecute();
if(isPhotoTaken()){
ImageUploader uploader = new ImageUploader(_context);
uploader.uploadFile(getPhotoPath(), "http://obo.nl/android-upload-image.php");
}
}
/**
* Method used to start {@link #postData(Mail)} on a background thread.
*
* @return null
*/
@Override
protected Double doInBackground(Mail... params) {
postData(params[0]);
return null;
}
/**
* Method used to send the mail through a JSON Request in combination with the website.
* If there is no Internet connection the program will try to send the mail every 10 seconds.
*
* @param valueIWantToSend
*/
public void postData(Mail valueIWantToSend) {
if(AppStatus.haveNetworkConnection(_context)){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://obo.nl/android-mailing.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("from", valueIWantToSend.getFrom()));
nameValuePairs.add(new BasicNameValuePair("to", valueIWantToSend.getTo()));
nameValuePairs.add(new BasicNameValuePair("subject", valueIWantToSend.getSubject()));
nameValuePairs.add(new BasicNameValuePair("message", valueIWantToSend.getBody()));
nameValuePairs.add(new BasicNameValuePair("localized", getResources().getConfiguration().locale.getDisplayName()));
if(PathToPDF(_repairable).contains("Goed_Gekeurd_NL")){
nameValuePairs.add(new BasicNameValuePair("outputResult", SERVER_BANDENANALYSE_GOED_GEKEURD_PATH));
} else if(PathToPDF(_repairable).contains("Afgekeurd_NL")){
nameValuePairs.add(new BasicNameValuePair("outputResult", SERVER_BANDENANALYSE_AFGEKEURD_PATH));
} else if(PathToPDF(_repairable).contains("Goed_Gekeurd_FR")){
nameValuePairs.add(new BasicNameValuePair("outputResult", SERVER_ANALYSEPNEUS_GOED_GEKEURD_PATH));
} else if(PathToPDF(_repairable).contains("Afgekeurd_FR")){
nameValuePairs.add(new BasicNameValuePair("outputResult", SERVER_ANALYSEPNEUS_AFGEKEURD_PATH));
} else if(PathToPDF(_repairable).contains("Goed_Gekeurd_DE")){
nameValuePairs.add(new BasicNameValuePair("outputResult", SERVER_REIFENANALYSE_GOED_GEKEURD_PATH));
} else if(PathToPDF(_repairable).contains("Afgekeurd_DE")){
nameValuePairs.add(new BasicNameValuePair("outputResult", SERVER_REIFENANALYSE_AFGEKEURD_PATH));
} else if(PathToPDF(_repairable).contains("Goed_Gekeurd_EN")){
nameValuePairs.add(new BasicNameValuePair("outputResult", SERVER_TYREANALYSE_GOED_GEKEURD_PATH));
} else if(PathToPDF(_repairable).contains("Afgekeurd_EN")){
nameValuePairs.add(new BasicNameValuePair("outputResult", SERVER_TYREANALYSE_AFGEKEURD_PATH));
}
if(isPhotoTaken()){
// ImageUploader uploader = new ImageUploader(_context); // uploader.uploadFile(getPhotoPath(),“http://obo.nl/android-upload-image.php”); nameValuePairs.add(new BasicNameValuePair(“photo”,getPhotoPath())); } httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); ResponseHandler responseHandler = new BasicResponseHandler(); 字符串响应= httpclient.execute(httppost,responseHandler);
//This is the response from a php application
String reverseString = response;
Log.i("info", reverseString);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
} else {
if(_counter == 0){
_counter++;
_activity.runOnUiThread(new Runnable(){
public void run(){
Toast.makeText(_context, getString(R.string.noInternetEmailNotSend), Toast.LENGTH_LONG).show();
}
});
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
postData(valueIWantToSend);
}
}
}
此外_context在活动的onCreate中设置如下:
_context = this;
PostData方法中发生的事情是发送邮件,将拍摄的照片作为附件(但这并不是很有意思,因为它非常有用)。
那么对话框怎么没出现呢?
答案 0 :(得分:0)
你没有在ImageUploader方法中启动你的线程。将您的方法更改为:
public ImageUploader(Context ctx) {
this.context = ctx;
((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();
}
}).start();
}
答案 1 :(得分:0)
首先,当你在AsyncTask的onPreExecute()中为ImageUpLoader创建对象时,你不需要在构造函数中专门调用runOnUIThread()方法,因为onPreExecute在UI Thread上运行并且对话,试试这个...... 删除thread.join()语句,
Thread thread = new Thread() {
public void run() {
// your upload code stuff here
activity.runOnUiThread(new Runnable() {
public void run() {
if(dialog.isShowing()) {
dialog.dismiss();
}
}
}
}
在UI线程中创建UI组件时,最有可能需要在UI线程中处理它们。 (试图在新线程中解除对话框)