应用程序停止按下后退按钮而不选择图库意图中的图像

时间:2017-11-21 04:59:00

标签: android android-intent android-gallery android-camera-intent

如果我想在没有从图库/相机意图中选择图像的情况下返回,我的应用程序会停止。如果我选择图像或拍摄照片,它可以正常工作。我搜索了很多东西,但没有任何作用。请帮忙......

这是onActivityResult方法

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    //super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode) {
        case PICK_IMAGE_ID:
            Bitmap bitmap = ImagePicker.getImageFromResult(getContext(), resultCode, data);
            // TODO use bitmap
            civ_profile_image.setImageBitmap(bitmap);

             image_as_byte = imageToByte(bitmap);

            break;

        default:
            bitmap = ImagePicker.getImageFromResult(getContext(), resultCode, data);
            image_as_byte = imageToByte(bitmap);
            break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

ImagePicker.java

public class ImagePicker {
private static final int DEFAULT_MIN_WIDTH_QUALITY = 400;        // min pixels
private static final String TAG = "ImagePicker";
private static final String TEMP_IMAGE_NAME = "tempImage";       //temp image

public static int minWidthQuality = DEFAULT_MIN_WIDTH_QUALITY;


public static Intent getPickImageIntent(Context context) {
    Intent chooserIntent = null;

    List<Intent> intentList = new ArrayList<>();

    Intent pickIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    takePhotoIntent.putExtra("return-data", true);
    takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(context)));
    intentList = addIntentsToList(context, intentList, pickIntent);
    intentList = addIntentsToList(context, intentList, takePhotoIntent);

    if (intentList.size() > 0) {
        chooserIntent = Intent.createChooser(intentList.remove(intentList.size() - 1),
                context.getString(R.string.pick_image_intent_text));
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new Parcelable[]{}));
    }

    return chooserIntent;
}

private static List<Intent> addIntentsToList(Context context, List<Intent> list, Intent intent) {
    List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(intent, 0);
    for (ResolveInfo resolveInfo : resInfo) {
        String packageName = resolveInfo.activityInfo.packageName;
        Intent targetedIntent = new Intent(intent);
        targetedIntent.setPackage(packageName);
        list.add(targetedIntent);
        //Log.d(TAG, "Intent: " + intent.getAction() + " package: " + packageName);
    }
    return list;
}


public static Bitmap getImageFromResult(Context context, int resultCode,
                                        Intent imageReturnedIntent) {
    //Log.d(TAG, "getImageFromResult, resultCode: " + resultCode);
    Bitmap bm = null;
    File imageFile = getTempFile(context);
    if (resultCode == Activity.RESULT_OK) {
        Uri selectedImage;
        boolean isCamera = (imageReturnedIntent == null ||
                imageReturnedIntent.getData() == null ||
                imageReturnedIntent.getData().toString().contains(imageFile.toString()));
        if (isCamera) {     /** CAMERA **/
            selectedImage = Uri.fromFile(imageFile);
        } else {            /** ALBUM **/
            selectedImage = imageReturnedIntent.getData();
        }
        //Log.d(TAG, "selectedImage: " + selectedImage);

        bm = getImageResized(context, selectedImage);
        int rotation = getRotation(context, selectedImage, isCamera);
        bm = rotate(bm, rotation);
    }
    return bm;
}


private static File getTempFile(Context context) {
    File imageFile = new File(context.getExternalCacheDir(), TEMP_IMAGE_NAME);
    imageFile.getParentFile().mkdirs();
    return imageFile;
}

private static Bitmap decodeBitmap(Context context, Uri theUri, int sampleSize) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = sampleSize;

    AssetFileDescriptor fileDescriptor = null;
    try {
        fileDescriptor = context.getContentResolver().openAssetFileDescriptor(theUri, "r");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    Bitmap actuallyUsableBitmap = BitmapFactory.decodeFileDescriptor(
            fileDescriptor.getFileDescriptor(), null, options);

//        Log.d(TAG, options.inSampleSize + " sample method bitmap ... " +
//                actuallyUsableBitmap.getWidth() + " " + actuallyUsableBitmap.getHeight());

    return actuallyUsableBitmap;
}

/**
 * Resize to avoid using too much memory loading big images (e.g.: 2560*1920)
 **/
private static Bitmap getImageResized(Context context, Uri selectedImage) {
    Bitmap bm;
    int[] sampleSizes = new int[]{5, 3, 2, 1};
    int i = 0;
    do {
        bm = decodeBitmap(context, selectedImage, sampleSizes[i]);
        //Log.d(TAG, "resizer: new bitmap width = " + bm.getWidth());
        i++;
    } while (bm.getWidth() < minWidthQuality && i < sampleSizes.length);
    return bm;
}


private static int getRotation(Context context, Uri imageUri, boolean isCamera) {
    int rotation;
    if (isCamera) {
        rotation = getRotationFromCamera(context, imageUri);
    } else {
        rotation = getRotationFromGallery(context, imageUri);
    }
    //Log.d(TAG, "Image rotation: " + rotation);
    return rotation;
}

private static int getRotationFromCamera(Context context, Uri imageFile) {
    int rotate = 0;
    try {

        context.getContentResolver().notifyChange(imageFile, null);
        ExifInterface exif = new ExifInterface(imageFile.getPath());
        int orientation = exif.getAttributeInt(
                ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL);

        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_270:
                rotate = 270;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                rotate = 180;
                break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                rotate = 90;
                break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return rotate;
}

public static int getRotationFromGallery(Context context, Uri imageUri) {
    int result = 0;
    String[] columns = {MediaStore.Images.Media.ORIENTATION};
    Cursor cursor = null;
    try {
        cursor = context.getContentResolver().query(imageUri, columns, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int orientationColumnIndex = cursor.getColumnIndex(columns[0]);
            result = cursor.getInt(orientationColumnIndex);
        }
    } catch (Exception e) {
        //Do nothing
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }//End of try-catch block
    return result;
}


private static Bitmap rotate(Bitmap bm, int rotation) {
    if (rotation != 0) {
        Matrix matrix = new Matrix();
        matrix.postRotate(rotation);
        Bitmap bmOut = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
        return bmOut;
    }
    return bm;
}

}

图像到byteArray方法

private byte[] imageToByte(Bitmap image) {

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
    return outputStream.toByteArray();

}

我在onActivityResult

中尝试了这样和其他人
    if (resultCode != RESULT_OK) {
        if (requestCode == PICK_IMAGE_ID) {
            if (data.getExtras() == null) {
                Bitmap bitmap = ImagePicker.getImageFromResult(getContext(), resultCode, data);
                // TODO use bitmap
                civ_profile_image.setImageBitmap(bitmap);

                image_as_byte = imageToByte(bitmap);
            } else {
                Bitmap bitmap = (Bitmap) data.getExtras().get("data");
                civ_profile_image.setImageBitmap(bitmap);
                image_as_byte = imageToByte(bitmap);
                Toast.makeText(getContext(), "No image is selected", Toast.LENGTH_SHORT).show();
            }
        }
    }

这是Logcat。不幸的是,Logcat现在没有任何事情发生(没有消息)。有一个&#34; DEAD&#34;在logcat中我的项目名称旁边标记。我不知道发生了什么。在此之前我复制了这个logcat。

01-01 05:30:14.680 246-246/? I/auditd: type=1403 audit(0.0:2): policy loaded auid=4294967295 ses=4294967295

01-01 05:30:14.680 246-246 /? W / auditd:type = 1404 audit(0.0:3):enforcing = 1 old_enforcing = 0 auid = 4294967295 ses = 4294967295 01-01 05:30:15.200 1-1 /? W / init:type = 1400 audit(0.0:4):avc:denied {create} for name =&#34; preload&#34; scontext = u:r:init:s0 tcontext = u:object_r:system_file:s0 tclass = dir permissive = 0 01-01 05:30:15.210 1-1 /? W / init:type = 1400 audit(0.0:5):avc:denied {create} for name =&#34; preload&#34; scontext = u:r:init:s0 tcontext = u:object_r:system_file:s0 tclass = dir permissive = 0 01-01 05:30:15.720 1-1 /? W / init:type = 1400 audit(0.0:6):avc:denied {create} for name =&#34; root_channel&#34; scontext = u:r:init:s0 tcontext = u:object_r:root_execute_file:s0 tclass = dir permissive = 0

                             --------- beginning of system

01-01 05:30:15.876 247-247 /? I / vold:Vold 3.0(觉醒)开火 01-01 05:30:15.876 247-256 /? D / NVRAM:检查nvram恢复是否准备就绪! 01-01 05:30:15.876 247-247 /? V / vold:检测到支持:exfat ext4 vfat exfat 01-01 05:31:09.079 862-1834 /? V / ActivityManager:广播:意图{act = android.intent.action.ACTION_SUBINFO_CONTENT_CHANGE flg = 0x10} ordered = false userid = 0 callerApp = ProcessRecord {6fce49f 1505:com.android.phone/1001} 01-01 05:31:09.080 862-1559 /? V / ActivityManager:广播粘性:Intent {act = android.intent.action.ACTION_SUBINFO_RECORD_UPDATED flg = 0x10(有额外内容)} ordered = false userid = 0 callerApp = ProcessRecord {6fce49f 1505:com.android.phone / 1001}

3 个答案:

答案 0 :(得分:0)

在您的lenArg-1方法中,您没有检查我认为没有选择图像的情况。你应该相应地安排你的开关盒,可能会调整下面的代码部分。

onActivityResult

答案 1 :(得分:0)

请处理onActivityResult中的RESULT_OK和RESULT_CANCELED两种情况,无需使用默认情况。

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    //super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        switch (requestCode) {
            case PICK_IMAGE_ID:
                Bitmap bitmap = ImagePicker.getImageFromResult(getContext(), resultCode, data);
                // TODO use bitmap
                civ_profile_image.setImageBitmap(bitmap);

                image_as_byte = imageToByte(bitmap);

                break;

          }
    } else {
        Toast.makeText(this, "Result Canceled", Toast.LENGTH_LONG).show();
    }
    super.onActivityResult(requestCode, resultCode, data);
}

答案 2 :(得分:0)

使用

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
        case PICK_IMAGE_ID:
            if (resultCode != RESULT_OK) {
                return;
            }
            Bitmap bitmap = ImagePicker.getImageFromResult(getContext(), resultCode, data);
            ...

        break;
    }
   super.onActivityResult(requestCode, resultCode, data);
}