【发布时间】:2014-08-05 11:18:03
【问题描述】:
我在一个服务(IntentService 的子类)中使用下面给出的 android 代码,它的线程是独立的,但这段代码有时很酷,但有时却不行。这意味着可靠性问题。调试后我发现代码有时会在 httpClient.execute(httppost) 处挂起。我怎样才能使它在任何条件下都能准确工作?提前致谢。
http响应码
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();
}
});
}
}
}
【问题讨论】:
-
你找到解决办法了吗?
标签: android file-upload http-post httpclient network-protocols