简体   繁体   English

ActivityCompat.requestPermissions不显示提示

[英]ActivityCompat.requestPermissions does not show prompt

I'm attempting to request ACCESS_FINE_LOCATION permissions in order to get the user's current location. 我正在尝试请求ACCESS_FINE_LOCATION权限以获取用户的当前位置。

My logging indicates that my app does not currently have this permission when querying ContextCompat.checkSelfPermission() , but when calling ActivityCompat.requestPermissions() nothing is displayed. 我的日志记录表明我的应用程序在查询ContextCompat.checkSelfPermission()时当前没有此权限,但在调用ActivityCompat.requestPermissions()不会显示任何内容。

My Google map code (implementing OnMapReadyCallback and ActivityCompat.OnRequestPermissionsResultCallback() ) is in a FragmentActivity . 我的Google地图代码(实现OnMapReadyCallbackActivityCompat.OnRequestPermissionsResultCallback() )位于FragmentActivity

I have managed to get the requestPermissions() function working successfully in other Activities in the app, it's just the one with the Google map. 我已经设法让requestPermissions()函数在应用程序中的其他活动中成功运行,它只是带有Google地图的那个。 It doesn't work when placed in the onCreate() method of the Activity , or in onMapReady() (where it needs to go). 放置在ActivityonCreate()方法或onMapReady() (它需要去的地方)时,它onMapReady()

if(ContextCompat.checkSelfPermission(LocationActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Log.d(TAG, "not granted");
        final String[] permissions = new String[] {android.Manifest.permission.ACCESS_FINE_LOCATION};
    if(ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
            Log.d(TAG, "rationale");
            // Explain to the user why permission is required, then request again
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("We need permissions")
                    .setCancelable(false)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            ActivityCompat.requestPermissions(LocationActivity.this, permissions, 1);
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();

    } else {
        Log.d(TAG, "request" + android.Manifest.permission.ACCESS_FINE_LOCATION);
        // If permission has not been denied before, request the permission
        ActivityCompat.requestPermissions(LocationActivity.this, permissions, 1);
    }
} else {
    Log.d(TAG, "granted");
}

Any ideas? 有任何想法吗? Is it something to do with my Activity's class ( FragmentActivity ), or possible the Google map calling the permissions request asynchronously? 它与我的Activity类( FragmentActivity )有关,还是可能是异步调用权限请求的Google地图?

After stripping out my class completely, and it still not working, I realised that this Activity is being instantiated using a TabHost. 完全剥离我的课程后,它仍然无法正常工作,我意识到这个Activity正在使用TabHost进行实例化。

When I stop using the TabHost, the prompt is displayed successfully. 当我停止使用TabHost时,提示会成功显示。 I guess TabHosts are not supported by the new permissions prompts - is this a bug? 我猜新的权限提示不支持TabHosts - 这是一个错误吗?

Same problem as App requests aren't showing up App请求未显示相同的问题

I ended up creating a PermissionsRequestActivity which handles the permission request and response on behalf of my TabHost, then exits (pass the requested permission information in through the Intent extras Bundle). 我最终创建了一个PermissionsRequestActivity,它代表我的TabHost处理权限请求和响应,然后退出(通过Intent extras Bundle传递请求的权限信息)。
It passes back the response to the request as a Broadcast, which is picked up by my TabHost. 它将响应作为广播传回给请求,由我的TabHost接收。

Bit of a hack but works OK! 一点点黑客,但工作正常!

Check that you have already added the requested permission in Android's manifest file like before Android M, only then you will get expected behaviour. 检查您是否已经在Android的清单文件中添加了所请求的权限,就像Android M之前一样,只有这样您才能获得预期的行为。

Add the permission to your manifest so you can request it via ActivityCompat.requestPermissions: 将权限添加到清单,以便您可以通过ActivityCompat.requestPermissions请求它:

<uses-permission android:name="android.permission. ACCESS_FINE_LOCATION" />

I will share the code that works for me. 我将分享适合我的代码。 In the protected void onCreate(Bundle savedInstanceState) {} method of my activity where I want to see the prompt, I included this code: 在我想要查看提示的受保护的void onCreate(Bundle savedInstanceState){}方法中,我包含了以下代码:

    /* Check whether the app has the ACCESS_FINE_LOCATION permission and whether the app op that corresponds to
     * this permission is allowed. The return value is an int: The permission check result which is either
     * PERMISSION_GRANTED or PERMISSION_DENIED or PERMISSION_DENIED_APP_OP.
     * Source: https://developer.android.com/reference/android/support/v4/content/PermissionChecker.html
     * While testing, the return value is -1 when the "Your location" permission for the App is OFF, and 1 when it is ON.
     */
    int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
    // The "Your location" permission for the App is OFF.
    if (permissionCheck == -1){
        /* This message will appear: "Allow [Name of my App] to access this device's location?"
         * "[Name of my Activity]._instance" is the activity.
         */
        ActivityCompat.requestPermissions([Name of my Activity]._instance, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_ACCESS_FINE_LOCATION);
    }else{
        // The "Your location" permission for the App is ON.
        if (permissionCheck == 0){
        }
    }

Before the protected void onCreate(Bundle savedInstanceState) {} method, I created the following constant and method: 在protected void onCreate(Bundle savedInstanceState){}方法之前,我创建了以下常量和方法:

public static final int REQUEST_CODE_ACCESS_FINE_LOCATION = 1; // For implementation of permission requests for Android 6.0 with API Level 23.

// Code from "Handle the permissions request response" at https://developer.android.com/training/permissions/requesting.html.
@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_CODE_ACCESS_FINE_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // location-related task you need to do.                

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

I've faced the same problem on a project which use TabHost. 我在使用TabHost的项目上遇到了同样的问题。 Basis on @Robin solution, I use the EventBus library for send a message from child activity to the TabActity. 基于@Robin解决方案,我使用EventBus库从子活动向TabActity发送消息。

EventBus : https://github.com/greenrobot/EventBus EventBus: https//github.com/greenrobot/EventBus

Create an event object : 创建一个事件对象:

public class MessageEvent {
    private String message;
    public MessageEvent(String message){
        this.message = message;
    }

    public String getMessage(){
        return this.message;
    }
}

In your main Activity : 在您的主要活动中:

private EventBus eventBus = EventBus.getDefault();
@Override
protected void onCreate(Bundle savedInstanceState) {
    eventBus.register(this);
}
@Override
protected void onDestroy() {
    eventBus.unregister(this);
    super.onDestroy();
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
    if (event.getMessage().equals("contacts")){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(android.Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainPage.this,new String[]{android.Manifest.permission.WRITE_CONTACTS}, 100 );
        }
    }
};

Set a different message for the permission your want to request. 为要请求的权限设置不同的消息。 In your child activity you can than post the adequate message : 在您的孩子活动中,您可以发布适当的消息:

EventBus.getDefault().post(new MessageEvent("contacts"));

Be aware of onRequestPermissionsResult callback and the request code ;)! 注意onRequestPermissionsResult回调和请求代码;)! It will only work in the main activity. 它只适用于主要活动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM