【问题标题】:Marshmallow Permission Error棉花糖权限错误
【发布时间】:2017-05-12 14:38:08
【问题描述】:

我正在开发音乐播放器应用程序,因此我必须从存储卡中获取所有歌曲,并且我成功地从存储卡应用程序中获取了歌曲,并且在棒棒糖上运行良好。

问题 Marshmallow 运行时权限我还为 Marshmallow 添加了运行时权限,但应用程序仍然崩溃..

这是我的完整代码,请告诉我我必须在哪里为 Marshmallow 编写运行时权限。

public class MainActivity extends AppCompatActivity {

    private int STORAGE_PERMISSION_CODE = 23;
    ListView musiclist;
    Cursor musiccursor;
    int music_column_index;
    int count;
    MediaPlayer mMediaPlayer;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init_phone_music_grid();
        if(isReadStorageAllowed()){
            //If permission is already having then showing the toast
            Toast.makeText(MainActivity.this,"You already have the permission",Toast.LENGTH_LONG).show();
            //Existing the method with return
            return;
        }

        //If the app has not the permission then asking for the permission
        requestStoragePermission();
    }

    private void requestStoragePermission() {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.READ_EXTERNAL_STORAGE)){
            //If the user has denied the permission previously your code will come to this block
            //Here you can explain why you need this permission
            //Explain here why you need this permission
        }

        //And finally ask for the permission
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},STORAGE_PERMISSION_CODE);
    }

    //This method will be called when the user will tap on allow or deny
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        //Checking the request code of our request
        if(requestCode == STORAGE_PERMISSION_CODE){

            //If permission is granted
            if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

                //Displaying a toast
                Toast.makeText(this,"Permission granted now you can read the storage",Toast.LENGTH_LONG).show();
            }else{
                //Displaying another toast if permission is not granted
                Toast.makeText(this,"Oops you just denied the permission",Toast.LENGTH_LONG).show();
            }
        }
    }



    private boolean isReadStorageAllowed() {
        int result = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);


        if (result == PackageManager.PERMISSION_GRANTED)
            return true;


        return false;

    }


    private void init_phone_music_grid() {
        System.gc();
        String[] proj = { MediaStore.Audio.Media._ID,
                MediaStore.Audio.Media.DATA,
                MediaStore.Audio.Media.DISPLAY_NAME,
                MediaStore.Video.Media.SIZE };

        musiccursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                proj, null, null, null);
        count = musiccursor.getCount();
        musiclist = (ListView) findViewById(R.id.PhoneMusicList);
        musiclist.setAdapter(new MusicAdapter(getApplicationContext()));

        musiclist.setOnItemClickListener(musicgridlistener);
        mMediaPlayer = new MediaPlayer();
    }

    private AdapterView.OnItemClickListener musicgridlistener = new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView parent, View v, int position,
                                long id) {
            System.gc();
            music_column_index = musiccursor
                    .getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
            musiccursor.moveToPosition(position);
            String filename = musiccursor.getString(music_column_index);

            try {
                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.reset();
                }
                mMediaPlayer.setDataSource(filename);
                mMediaPlayer.prepare();
                mMediaPlayer.start();
            } catch (Exception e) {

            }
        }

    };



    public class MusicAdapter extends BaseAdapter {
        private Context mContext;

        public MusicAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
            return count;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {


            System.gc();
            TextView tv = new TextView(mContext.getApplicationContext());
            String id = null;
            if (convertView == null) {
                music_column_index = musiccursor
                        .getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
                musiccursor.moveToPosition(position);
                id = musiccursor.getString(music_column_index);
                music_column_index = musiccursor
                        .getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE);
                musiccursor.moveToPosition(position);
                id += " Size(KB):" + musiccursor.getString(music_column_index);
                tv.setText(id);
            } else
         tv.setTextColor(Integer.parseInt(String.valueOf(R.color.colorAccent)));
                tv = (TextView) convertView;
            return tv;
        }
    }}

请不要标记重复只是更正我的许可 谢谢

崩溃报告: E/AndroidRuntime: 致命异常: main 进程:com.example.j.musicapp,PID:28606 java.lang.RuntimeException:无法启动活动 ComponentInfo{com.example.j.musicapp/com.example.j.musicapp.MainActivity}:java.lang.SecurityException:权限拒绝:读取 com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=28606, uid=10161 需要 android.permission.READ_EXTERNAL_STORAGE 或 grantUriPermission() 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415) 在 android.app.ActivityThread.access$1100(ActivityThread.java:229) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:148) 在 android.app.ActivityThread.main(ActivityThread.java:7331) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 引起:java.lang.SecurityException: Permission Denial: 从 pid=28606 读取 com.android.providers.media.MediaProvider uri content://media/external/audio/media,uid=10161 需要 android.permission.READ_EXTERNAL_STORAGE,或者授予UriPermission() 在 android.os.Parcel.readException(Parcel.java:1621) 在 android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183) 在 android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135) 在 android.content.ContentProviderProxy.query(ContentProviderNative.java:421) 在 android.content.ContentResolver.query(ContentResolver.java:502) 在 android.content.ContentResolver.query(ContentResolver.java:445) 在 android.app.Activity.managedQuery(Activity.java:2227) 在 com.example.j.musicapp.MainActivity.init_phone_music_grid(MainActivity.java:100) 在 com.example.j.musicapp.MainActivity.onCreate(MainActivity.java:35) 在 android.app.Activity.performCreate(Activity.java:6904) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415) 在 android.app.ActivityThread.access$1100(ActivityThread.java:229) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:148) 在 android.app.ActivityThread.main(ActivityThread.java:7331) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

【问题讨论】:

  • 发布 logcat 详细信息
  • stackoverflow.com/a/34959331/4919210 看看这个答案!!
  • 好的先生等等............
  • 你遇到了什么错误?
  • 请看一下我的崩溃报告

标签: android android-6.0-marshmallow android-permissions


【解决方案1】:

你可以看看这个通用代码结构,看看是否匹配......我实际上遵循了它,效果很好

if(permissionNotGranted){
       requestPermission() ;
}else{
   //Permission granted, good to go!
    doWhateverWithPermission() ; 
}

onRequestPermissionsResult 你很擅长……看看结构。希望对您有所帮助!

【讨论】:

    【解决方案2】:

    这是棉花糖及以上版本的示例代码:

      public static class Utility {
            public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
    
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            public static boolean checkPermission(final Context context) {
                int currentAPIVersion = Build.VERSION.SDK_INT;
                if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                            AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context, R.style.MyAlertDialogStyle);
                            alertBuilder.setCancelable(true);
                            alertBuilder.setTitle("Permission necessary");
                            alertBuilder.setMessage("External storage permission is necessary");
                            alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                                public void onClick(DialogInterface dialog, int which) {
                                    ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                                }
                            });
                            AlertDialog alert = alertBuilder.create();
                            alert.show();
    
                        } else {
                            ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                        }
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    return true;
                }
            }
        }
    

    这是一种检查读取外部存储权限的方法。请参考代码并进行相应操作。 希望这对您有所帮助。

    在 onCreate 方法中也加入这段代码

     boolean result = Utility.checkPermission(MainActivity.this);
    

    【讨论】:

    • 但是如果用户拒绝了权限呢??
    • 如果一旦用户拒绝,那么它会再次要求它,因为在我的 else 条件下我再次调用它。如果您不想强制执行,则可以删除 else 代码
    • 是的,又成功了
    • 老兄
    • 哥们,你打勾了,票数仍然为零。一旦你点击向上投票箭头,它就会完成。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多