我的Android应用程序正在初步让我选择一张照片。相反,我希望我的应用程序最初将我带到主页面

时间:2017-09-13 14:14:52

标签: java android android-imageview

当我启动我的应用时,它最初让我选择一张照片。相反,我想让它带我到主屏幕,我可以在那里选择一张照片。当我点击图像视图时,它已被编程为选择照片。只是为了澄清,问题在于它迫使我在启动应用程序时选择一张照片,而不是其他任何时候

    public void getPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent,1);
    }

        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);

            if (requestCode ==1){
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED);{
                getPhoto();
                }
            }
        }

    @Override
            protected void onCreate (Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            } else {
                getPhoto();
            }

        }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode ==1 && resultCode == RESULT_OK && data != null) {
            Uri selectedImage = data.getData();

            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);


                ImageView imageView2 = (ImageView) findViewById(R.id.imageView2);
                imageView2.setImageBitmap(bitmap);


            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void click(View view) {
        if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        } else {
            getPhoto();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

就像Droidman所说的那样。

if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        } else {
            getPhoto();
        }

您正在检查权限。如果您拥有正确的权限,请立即在onCreate中调用getPhoto()。删除此调用即可。