我正在开发一个应用程序,它提供了将图像上传到带有注释的服务器,但我担心的是图像上传方法需要一段时间,我使用了AsyncTasking,我想的是一个更像Facebook的方法,当上传开始时,用户可以离开活动但上传仍然在后台继续,任何人都可以帮助我如何做到这一点?
@Override
public void onClick(View v) {
new PostComment().execute();
// new UploadFileToServer().execute();
}
class PostComment extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddComment.this);
pDialog.setMessage("Posting Isampo...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
int success;
String post_title = title.getText().toString();
String post_message = message.getText().toString();
String post_condition = condition.getText().toString();
String post_make = make.getText().toString();
String post_method_of_sell= samposell.getText().toString();
String post_post_identifier = generated;
generatedgone = generated;
//We need to change this:
sp = PreferenceManager.getDefaultSharedPreferences(AddComment.this);
String post_username = sp.getString("username", "anon");
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", post_username));
params.add(new BasicNameValuePair("title", post_title));
params.add(new BasicNameValuePair("make", post_make));
params.add(new BasicNameValuePair("condition", post_condition));
params.add(new BasicNameValuePair("purchase_method", post_method_of_sell));
params.add(new BasicNameValuePair("message", post_message));
params.add(new BasicNameValuePair("image_tag",post_post_identifier));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
POST_COMMENT_URL, "POST", params);
// full json response
Log.d("Post post attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("post Added!", json.toString());
// finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("post Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(AddComment.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
/**
* Checking device has camera hardware or not
* */
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/**
* Launching camera app to capture image
*/
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Launching camera app to record video
*/
/**
* Launching camera app to record video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Receiving activity result method will be called after closing the camera
* */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// launching upload activity
launchUploadActivity(true);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// launching upload activity
launchUploadActivity(false);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
//Loading Image From Gallery
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
// Set the Image in ImageView
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgPath));
//setting Image View
if (imgView != null & imgView.getDrawable() != null) {
imgView.setVisibility(View.VISIBLE);
} else {
imgView.setVisibility(View.VISIBLE);
}
// Get the Image's file name
String fileNameSegments[] = imgPath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
File f = new File(imgPath);
imagepath = imgPath;
filename = f.getName();
// Put file name in Async Http Post Param which will used in Php web app
//important ---> params.put("filename", fileName);
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
private void launchUploadActivity(boolean isImage){
// boo
// lean flag to identify the media type, image or video
if(fileUri.getPath() !=null & isImage==true) {
filePath = fileUri.getPath();
if (filePath != null) {
// Displaying the image or video on the screen
previewMedia(isImage);
} else {
Toast.makeText(getApplicationContext(),
"Sorry, file path is missing!", Toast.LENGTH_LONG).show();
}
}
}
// Displaying captured image/video on the screen
private void previewMedia(boolean isImage) {
// Checking whether captured media is image or video
if (isImage) {
imgView.setVisibility(View.VISIBLE);
videoPreview.setVisibility(View.INVISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// down sizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
imgView.setImageBitmap(bitmap);
} else {
imgView.setVisibility(View.INVISIBLE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(filePath);
// start playing
videoPreview.start();
}
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Config.IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("Error", "Oops! Failed create "
+ Config.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
/ 独特的图片和帖子标记 / public void randInt(){
Random rand = new Random();
int Random = rand.nextInt((1000001 - 1) + 1) +1;
generated = Integer.toString(Random);
}
//stats uploading
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
@Override
protected void onPreExecute() {
// setting progress bar to zero
progressbar.setProgress(0);
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressbar.setVisibility(View.VISIBLE);
// updating progress bar value
progressbar.setProgress(progress[0]);
// updating percentage value
percentagetxt.setText(String.valueOf(progress[0]) + "%");
}
@Override
protected String doInBackground(Void... params) {
return uploadFile();
}
@SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
@Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
//Adding image_identifier
entity.addPart("image_identifier", new StringBody(generatedgone.toString()));
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) {
Log.e("RESPONSE", "Response from server: " + result);
// showing the server response in an alert dialog
showAlert(result);
super.onPostExecute(result);
}
}
/*** Method to show alert dialog
**/
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setTitle("Response from Servers")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
}
});
AlertDialog alert = builder.create();
alert.show();
}