我有这个活动拍照并发送到亚马逊,但如果我在上传时关闭互联网,APP崩溃。 我需要暂停异步并将警告发送到下一个活动
活动:
public void takeASelfie() {
selfieController.takeASelfie();
}
public void useCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
if (photoFile != null) {
imageUri = Uri.fromFile(photoFile);
Intent intent = new Intent(SelfieUI.this, PicturePreview.class);
Bundle bundle = new Bundle();
bundle.putSerializable(PicturePreview.NAME, name);
bundle.putSerializable(PicturePreview.STEP, 1);
bundle.putSerializable(PicturePreview.URI_PHOTO, imageUri.toString());
intent.putExtras(bundle);
SelfieUI.this.startActivity(intent);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp;
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
public void sendPicture(Boolean shouldSend) {
if (shouldSend) {
amazon();
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
//now getIntent() should always return the last received intent
}
public void amazon() {
String fileName = photoFile.getName();
long mTotalFileBytes;
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(mTotalFileBytes = photoFile.length());
metadata.setContentType("image/".concat(fileName));
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(),
"us-east-1:d6932c78-dadd-45bc-98d0-f89673a13c31",
Regions.US_EAST_1
);
amazonS3Client = new AmazonS3Client(credentialsProvider);
amazonS3Client.setRegion(Region.getRegion(Regions.SA_EAST_1));
try {
por = new PutObjectRequest(bucket, fileName, new FileInputStream(photoFile), metadata);
postImageAsyncTask = new PostImageAsyncTask(0);
postImageAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
amazonUrl = amazonS3Client.getResourceUrl(bucket, fileName);
Log.e(">>>>>URL", ">>>>>" + amazonUrl);
}
public void finishTakingASelfie(Picture picture) {
if (picture != null) {
Intent intent = new Intent(SelfieUI.this, InformationStatusUI.class);
Bundle bundle = new Bundle();
bundle.putSerializable(InformationStatusUI.NAME, name);
bundle.putSerializable(InformationStatusUI.STAGE, 3);
bundle.putSerializable(InformationStatusUI.SELF_URL, picture.getSelfieURL());
intent.putExtras(bundle);
SelfieUI.this.startActivity(intent);
} else {
Intent intent = new Intent(SelfieUI.this, InformationStatusUI.class);
Bundle bundle = new Bundle();
bundle.putSerializable(InformationStatusUI.NAME, name);
bundle.putSerializable(InformationStatusUI.STAGE, 3);
intent.putExtras(bundle);
SelfieUI.this.startActivity(intent);
}
}
异步任务:
public class PostImageAsyncTask extends AsyncTask<Object, Object, PutObjectResult> {
int backoff = 0;
public PostImageAsyncTask(Integer backoff) {
super();
this.backoff = backoff;
}
@Override
protected void onPreExecute() {
ConnectivityManager cm =
(ConnectivityManager) SelfieUI.this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
if (!isConnected) {
if (postImageAsyncTask != null && postImageAsyncTask.getStatus() != AsyncTask.Status.FINISHED)
postImageAsyncTask.cancel(true);
handler.postDelayed(new Runnable() {
@Override
public void run() {
RECONECT_TIME_DELAY = RECONECT_TIME_DELAY * 2;
postImageAsyncTask = new PostImageAsyncTask(0);
postImageAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}, RECONECT_TIME_DELAY);
}
}
@Override
protected PutObjectResult doInBackground(Object... params) {
return amazonS3Client.putObject(por);
}
@Override
protected void onPostExecute(PutObjectResult result) {
if (!isCancelled()) {
Log.e(">>>>>result", ">>>>>" + result.getContentMd5());
Toast toast = Toast.makeText(SelfieUI.this, result.getContentMd5(), Toast.LENGTH_LONG);
toast.show();
if (result != null) {
selfieController.picturePostedToS3(amazonUrl);
}
} else {
postImageAsyncTask.cancel(true);
}
}
}
}
堆栈追踪:
/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.foregon.forid, PID: 30963
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: com.amazonaws.AmazonClientException: Unable to execute HTTP request: Write error: ssl=0xb8a8cc08: I/O error during system call, Connection timed out
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:421)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:196)
at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4204)
at com.amazonaws.services.s3.AmazonS3Client.putObject(AmazonS3Client.java:1618)
at com.foregon.forid.pictureManagement.boundary.SelfieUI$PostImageAsyncTask.doInBackground(SelfieUI.java:432)
at com.foregon.forid.pictureManagement.boundary.SelfieUI$PostImageAsyncTask.doInBackground(SelfieUI.java:402)
答案 0 :(得分:0)
首先创建一个用于检查网络连接的类,如下所示:
public class ConnectionDetector {
private Context context;
public ConnectionDetector(Context context){
this.context = context;
}
public boolean isConnectedToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
然后在后台调用call方法以检查网络连接,如下所示:
@Override
protected PutObjectResult doInBackground(Object... params) {
if(new ConnectionDetector.isConnectedToInternet()){
return amazonS3Client.putObject(por);
} else{
return null;
}
}
现在在onPostExecute()
检查null。如果结果为null则表示没有网络连接。
答案 1 :(得分:0)
做这样的事情
@Override
protected PutObjectResult doInBackground(Object... params) {
try{
return amazonS3Client.putObject(por);
} catch (AmazonServiceException e){
//code
return null;
} catch (AmazonClientException f) {
//code
return null;
}
}