Android手机图片上传 选择不了本地照片 解决方案

来源:互联网 发布:智慧农业大数据云平台 编辑:程序博客网 时间:2024/06/11 18:36

问题描述:在实现Android端向服务器上传图片过程中,本人采用的是Android4.4版本,最初选择图片的代码是这样写的:

//        Intent intent = new Intent();
//        intent.setType("image/*");
//        intent.setAction(Intent.ACTION_GET_CONTENT);
//        startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);


调用方法为:

private void doPhoto(int requestCode,Intent data)
    {
        if(requestCode == SELECT_PIC_BY_PICK_PHOTO )  //从相册取图片,有些手机有异常情况,请注意
        {
            if(data == null)
            {
                Toast.makeText(this, "请选择本地相册照片", Toast.LENGTH_LONG).show();
                return;
            }
            photoUri = data.getData();
            
            if(photoUri == null )
            {
                Toast.makeText(this, "请选择本地相册照片", Toast.LENGTH_LONG).show();
                return;
            }
        }
        String[] pojo = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(photoUri, pojo, null, null,null);   
        if(cursor != null )
        {
            int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
            cursor.moveToFirst();
            picPath = cursor.getString(columnIndex);
            cursor.close();
        }
        Log.i(TAG, "imagePath = "+picPath);
        if(picPath != null && ( picPath.endsWith(".png") || picPath.endsWith(".PNG")|| picPath.endsWith(".jpeg") ||picPath.endsWith(".jpg") ||picPath.endsWith(".JPG")||picPath.endsWith(".gif")||picPath.endsWith(".bmp")
                ||picPath.endsWith(".tiff")))
        {
            lastIntent.putExtra(KEY_PHOTO_PATH, picPath);
            setResult(Activity.RESULT_OK, lastIntent);
            finish();
        }else{
            Toast.makeText(this, "请选择本地相册照片", Toast.LENGTH_LONG).show();
        }
    }

结果发现无法选中本地手机的图片。后查阅之后了解到,Android4.4与之前版本是有差别的。


解决方案:

所以选择图片部分可以这样写:

Intent intent;
        intent = new Intent(
                            Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);


调用方法不变。问题就得到了解决。本人Android菜鸟一枚,遇到问题便记录下来,希望对各位有所帮助。

2 1
原创粉丝点击