requestPermissions在一个片段中

问题描述 投票:0回答:2

我添加了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);
   .
   .
   .
android android-fragments permissions android-permissions menuitem
2个回答
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);
}

0
投票

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

请查看以下链接:

How to check permission in fragment

希望这有帮助,如果你这样做,请提升它并关闭这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.