我已经使用asynctask使用进度条实现了上传文件,但是大文件或上传多个文件使我的活动挂起,我现在想做同样的事情,但要使用服务而不是使用asynctask.这是我的代码.
private class UploadFileToServer extends AsyncTask {
@Override
protected void onPreExecute() {
// setting progress bar to zero
mBuilder.setProgress(100, 0, false);
mNotifyManager.notify(0, mBuilder.build());
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... progress) {
mBuilder.setProgress(100,
Integer.parseInt(String.valueOf(progress[0])), false);
mNotifyManager.notify(0, mBuilder.build());
}
@Override
protected String doInBackground(Void... params) {
return uploadFile();
}
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(***);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(orignal1);
entity.addPart("image", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
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();
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
mBuilder.setContentText("Upload complete").setProgress(0, 0,false);
mNotifyManager.notify(6532365, mBuilder.build());
mNotifyManager.cancel(6532365);
super.onPostExecute(result);
}
}