我在服务(IntentService的子类)中使用下面给出的android代码和它的saparate线程,但是这段代码有时很酷,但有时候不行。这意味着可靠性问题。在debuging之后,我发现代码有时会挂起在httpClient.execute(httppost)。如何在任何条件下使其准确无误?提前致谢。
httpresponce code
final HttpResponse resp;
final HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(serverUrl);
try {
ParcelFileDescriptor fileDescriptor = context.getContentResolver().openFileDescriptor(file_uri, "r");
InputStream in = context.getContentResolver().openInputStream(file_uri);
CountingInputStreamEntity entity = new CountingInputStreamEntity(in, fileDescriptor.getStatSize());
entity.setUploadListener(this);
entity.setContentType("application/gpx+xml");
//entity.setContentType("binary/octet-stream");
httpPost.setEntity(entity);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Log.i("FOO", "About to call httpClient.execute");
resp = httpClient.execute(httpPost);
if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
notification.setLatestEventInfo(context, "Uploading Completed", no_rx+" Rx Uploaded", contentIntent);
no_rx = 0;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1, notification);
Log.i("FOO", "All done");
} else {
Log.i("FOO", "Screw up with http - " + resp.getStatusLine().getStatusCode());
}
resp.getEntity().consumeContent();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
完整代码
public class UploadService extends IntentService{
private NotificationManager notificationManager;
private Notification notification;
public UploadService(String name) {
super(name);
}
public UploadService(){
super("UploadService");
}
@Override
protected void onHandleIntent(Intent intent) {
notificationManager = (NotificationManager) getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
//Uri uri = intent.getData();
String[] all_path_sel = intent.getStringArrayExtra("all_path_sel");
for(String s : all_path_sel){
File f = new File(s);
Uri file_uri = Uri.fromFile(f);
String serverUrl = Constants.BASIC_URL+Constants.ACTION_UPLOADFILE
+LoginActivity.user.getUserUniqueId()+"/"+f.getName();
Thread t = new Thread(new BackgroundThread(this, file_uri,serverUrl));
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
int no_rx = 0;
private class BackgroundThread implements Runnable, CountingInputStreamEntity.UploadListener {
Context context;
Uri file_uri;
String serverUrl;
int lastPercent = 0;
public BackgroundThread(Context context, Uri file_uri,String serverUrl) {
this.context = context;
this.file_uri = file_uri;
this.serverUrl = serverUrl;
}
@Override
public void run() {
no_rx++;
Intent notificationIntent = new Intent();
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification = new Notification(R.drawable.ic_launcher,
"Uploading Rx "+no_rx, System.currentTimeMillis());
notification.flags = notification.flags
| Notification.FLAG_ONGOING_EVENT;
notification.contentView = new RemoteViews(getApplicationContext()
.getPackageName(), R.layout.upload_progress_bar);
notification.contentIntent = contentIntent;
notification.contentView.setProgressBar(R.id.progressBar1, 100,0, false);
notificationManager.notify(1, notification);
Log.i("FOO", "Notification started");
final HttpResponse resp;
final HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(serverUrl);
try {
ParcelFileDescriptor fileDescriptor = context.getContentResolver().openFileDescriptor(file_uri, "r");
InputStream in = context.getContentResolver().openInputStream(file_uri);
CountingInputStreamEntity entity = new CountingInputStreamEntity(in, fileDescriptor.getStatSize());
entity.setUploadListener(this);
entity.setContentType("application/gpx+xml");
//entity.setContentType("binary/octet-stream");
httpPost.setEntity(entity);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Log.i("FOO", "About to call httpClient.execute");
resp = httpClient.execute(httpPost);
if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
notification.setLatestEventInfo(context, "Uploading Completed", no_rx+" Rx Uploaded", contentIntent);
no_rx = 0;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1, notification);
Log.i("FOO", "All done");
} else {
Log.i("FOO", "Screw up with http - " + resp.getStatusLine().getStatusCode());
}
resp.getEntity().consumeContent();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onChange(int percent) {
if(percent > lastPercent) {
notification.contentView.setProgressBar(R.id.progressBar1, 100, percent, false);
notificationManager.notify(1, notification);
lastPercent = percent;
}
}
}
}
活动代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_picker);
setTitle("");
initImageLoader();//load image in imageviewer
init();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
mCamera.mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
} else {
mCamera.mAlbumStorageDirFactory = new BaseAlbumDirFactory();
}
}
private void initImageLoader() {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc().imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
.bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
this).defaultDisplayImageOptions(defaultOptions).memoryCache(
new WeakMemoryCache());
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
}
private void init() {
gridGallery = (GridView) findViewById(R.id.gridGallery);
gridGallery.setFastScrollEnabled(true);
adapter = new ImageGridAdapter(getApplicationContext(), imageLoader);
adapter.setMultiplePick(false);
gridGallery.setAdapter(adapter);
viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher);
viewSwitcher.setDisplayedChild(1);
mImageBitmap = null;
gridGallery.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
gridGallery.setMultiChoiceModeListener(new MultiChoiceModeListener() {
@Override
public boolean onActionItemClicked(android.view.ActionMode mode,
MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.delete_file:
SparseBooleanArray selected = adapter.getSelectedIds();
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
ImageItem selecteditem = adapter.getItem(selected.keyAt(i));
//adapter.remove(selecteditem);
mImagePicker.remSelImage_updadr(selecteditem);
}
}
// Close CAB
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
@Override
public boolean onCreateActionMode(android.view.ActionMode mode,
Menu menu) {
// Inflate the menu for the CAB
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_file_picker, menu);
return true;
}
@Override
public void onDestroyActionMode(android.view.ActionMode mode) {
adapter.removeSelection();
}
@Override
public boolean onPrepareActionMode(android.view.ActionMode mode,
Menu menu) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onItemCheckedStateChanged(android.view.ActionMode mode,
int position, long id, boolean checked) {
final int checkedCount = gridGallery.getCheckedItemCount();
mode.setTitle(checkedCount + " Selected");
adapter.toggleSelection(position);
}
});
}
AlertDialog.Builder alert = new AlertDialog.Builder(ImagePickerActivity.this);
alert.setTitle(Constants.ALERT_FILEUPLOAD);
alert.setMessage(Constants.ALERT_CONFIRMATION);
alert.setPositiveButton(Constants.ALERT_CONFIRMATION_OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
new Thread(){
public void run(){
mFileUploader = new FileUploader(mImagePicker.imgArLst);
mFileUploader.uploadFiles_withService();
}
}.start();
}
});
private class FileUploader{
private ArrayList<ImageItem> imgArList;
FileUploader(ArrayList<ImageItem> imgArList){
this.imgArList = imgArList;
}
private void uploadFiles_withService() {
Intent intent = new Intent(ImagePickerActivity.this, UploadService.class);
ArrayList<String> arrStrLstPath = new ArrayList<String>();
for(ImageItem im : mImagePicker.imgArLst){
String path = im.getSdCardPath();
arrStrLstPath.add(path);
}
String[] all_path_sel = arrStrLstPath.toArray(new String[arrStrLstPath.size()]);
intent.putExtra("all_path_sel", all_path_sel);
startService(intent);
runOnUiThread(new Runnable(){
public void run(){
mImagePicker.clearAllImage_updadr();
//prgd.dismiss();
}
});
}
}
}
答案 0 :(得分:0)
使用以下课程上传图片
public class GlobalMultiPart extends AsyncTask<Void, Void, Void> {
private static final String TAG = GlobalMultiPart.class.getSimpleName() ;
Uri uri;
HashMap<String, String> params;
String Url;
InputStream inputStream;
String displayName, imageKey;
boolean isInputStream = false;
public interface OnResponse {
void onResponse(String result);
void onError(String error);
}
OnResponse onResponse;
public GlobalMultiPart(Uri uri, HashMap<String, String> params, String url, OnResponse onResponse, String imageKey) {
if (params == null) {
params = new HashMap<>();
}
this.uri = uri;
this.params = params;
this.Url = url;
this.onResponse = onResponse;
this.imageKey = imageKey;
try {
readMetaData(uri);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected Void doInBackground(Void... params) {
uploadImage();
return null;
}
public void uploadImage() {
String Response = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(Url);
post.setEntity(hashMapToMultipart());
HttpResponse response1 = httpClient.execute(post);
HttpEntity resEntity = response1.getEntity();
Response = EntityUtils.toString(resEntity);
Log.i(SetupProfile.class.getSimpleName(), Response);
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
e.printStackTrace();
}
if (Response == null)
onResponse.onError("An error occurred");
else
onResponse.onResponse(Response);
}
public MultipartEntity hashMapToMultipart() {
MultipartEntity mpEntity = new MultipartEntity();
if (uri != null) {
ContentBody cbFile1 = new InputStreamBody(inputStream, displayName);
mpEntity.addPart(imageKey, cbFile1);
}
try {
for (String key : params.keySet()) {
mpEntity.addPart(key, new StringBody(params.get(key)));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return mpEntity;
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private void readMetaData(Uri uri) {
try {
inputStream = AppController.getInstance().getApplicationContext().getContentResolver().openInputStream(uri);
isInputStream = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
displayName = uri.getLastPathSegment();
Cursor cursor = AppController.getInstance().getApplicationContext().getContentResolver().query(uri, null, null, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst())
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
Log.e(TAG,"Cursor on multipart null");
}
}
}
样品
new GlobalMultiPart(uri, params, url, this, imageTag).execute();
图像的imageTag键
希望它有效