Image from Gallery in Android 6(Marshmallow)

后端 未结 5 1788
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 16:39

In My Application I am trying to Pick image from galley, so as to pass that image to server.

Code is working fine on Android 5 and below, but for Android 6 on Nexus

5条回答
  •  独厮守ぢ
    2020-12-05 17:04

    Try this

    This is the simple method that i have created with other examples

    1. call CHECKGALLERYPERMISSION() method where you want and paste the code inside method

       private void CHECKGALLERYPERMISSION()
       {
          int MY_READ_PERMISSION_REQUEST_CODE =1 ;
          int PICK_IMAGE_REQUEST = 2;
          if (ContextCompat.checkSelfPermission(YourActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED)
          {
              Intent intent = new Intent();
              intent.setType("image/*");
              intent.setAction(Intent.ACTION_GET_CONTENT);
              startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
          }
          else
          {
              if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
              {
                  requestPermissions(
                          new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
                          MY_READ_PERMISSION_REQUEST_CODE);
              }
              else
              {
              }
          }
        }
        @Override
        public void onRequestPermissionsResult(int requestCode, String[] 
        permissions, int[] grantResults) {
         if (requestCode == MY_READ_PERMISSION_REQUEST_CODE
              && grantResults[0] == PackageManager.PERMISSION_GRANTED)
         {
          Intent intent = new Intent();
          intent.setType("image/*");
          intent.setAction(Intent.ACTION_GET_CONTENT);
          startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
      }
         }
        @Override
         public void onActivityResult(int requestCode, int resultCode, Intent data)
        {
      super.onActivityResult(requestCode, resultCode, data);
      if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null)
      {
          Uri uri = data.getData();
          try
          {
              Bitmap bitmap = MediaStore.Images.Media.getBitmap(YourActivity.this.getContentResolver(), uri);
              imageview.setImageBitmap(bitmap);
          }
          catch (IOException e)
          {
              e.printStackTrace();
          }
      }
        }
      

    Note

    1. in fragement use getactivity() instead of activity.this
    2. if android.Manifest.permission.READ_EXTERNAL_STORAGE not working change this to Manifest.permission.READ_EXTERNAL_STORAGE in all places

提交回复
热议问题