requestPermissions在一个片段中

时间:2017-12-16 14:10:07

标签: android android-fragments permissions android-permissions menuitem

我添加了setHasOptionsMenu(true);在onCreateView上。我想调用onRequestPermissionsResult,但onOptionsItemSelected存在问题。 这是一个片段,如果我使用v4.fragment,它会产生不同的问题。 我将使用import android.app.Fragment;但是requestPermissions想要--Call要求API级别23(当前最小值为16): - 我尝试了一些解决方案。我想只有办法解决api级问题。我该如何解决?

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
    menu.add("").setIcon(android.R.drawable.ic_menu_call).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED)
    {
        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_CONTACTS))
        {
        }
        else
        {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
            MenuFragment.this.requestPermissions( new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
            requestPermissions( new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
        }
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
{
    Toast.makeText(getActivity(), "Here", Toast.LENGTH_LONG).show();
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    //AlertDialog.Builder builder = new AlertDialog.Builder(this);
   .
   .
   .

2 个答案:

答案 0 :(得分:1)

我只添加了targetapi并且它有效。另外,我在这个片段中使用了requestPermissions。

@TargetApi(Build.VERSION_CODES.M)
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED)
    {
        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_CONTACTS))
        {
        }
        else
        {
            //ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
            //MenuFragment.requestPermissions( new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
            requestPermissions( new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
        }
    }
    return super.onOptionsItemSelected(item);
}

答案 1 :(得分:0)

当你在Fragment中使用Runtime权限时,使用了requestPermission()而不是AppCompact.requestpermission()。

请查看以下链接:

How to check permission in fragment

希望得到这个帮助,如果你这样做,请提起并关闭这个问题。