onActivityResult实现无法按预期运行

时间:2014-04-24 13:38:39

标签: android android-intent android-gallery mediastore onactivityresult

我尝试使用onActivityResult来启动Android图库,以便根据所选的ImageButton显示照片或视频。

问题是当试图打开照片时,它试图启动视频播放器并且我不确定原因。

P.S。

可以使用视频ImageButton成功播放视频。

private static final int SELECT_PHOTO = 1;
private static final int SELECT_VIDEO = 1;


ImageButton pb = (ImageButton) findViewById(R.id.photos);
    pb.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, SELECT_PHOTO);
        }
    });

    ImageButton vb = (ImageButton) findViewById(R.id.video);
    vb.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            Intent intentGallery = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intentGallery.setType("video/*");
            startActivityForResult(intentGallery, 1);

        }

    });
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if (resultCode == Activity.RESULT_OK) {
    if (requestCode == SELECT_VIDEO) {
        {
            Uri selectedVideo = data.getData();
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(selectedVideo, "video/*");
            startActivity(intent);

        }
    } else if (requestCode == SELECT_PHOTO) {

        Uri selectedImage = data.getData();
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(selectedImage, "image/*");
        startActivity(intent);
    }

2 个答案:

答案 0 :(得分:0)

private static final int SELECT_PHOTO = 1;
private static final int SELECT_VIDEO = 1;  

他们需要有所不同,有价值" 1"意味着他们进入同一个"如果" onActivityResult()

此外,它只播放视频,因为这是你的第一个"如果" onActivityResult()内的条件,总是最终成为:

startActivityForResult(intentGallery, 1);  
startActivityForResult(intent, SELECT_PHOTO);  

比较它们时正确传递两者。试试吧:

private static final int SELECT_PHOTO = 1;
private static final int SELECT_VIDEO = 2;

startActivityForResult(intentGallery, SELECT_VIDEO);  
startActivityForResult(intent, SELECT_PHOTO);   

应该获得some help from this

答案 1 :(得分:0)

SLECT_VIDEO和SELECT_PHOTO不能相同....