Android M permission: onRequestPermissionsResult()未被调用

我正在更新我们的应用程序,以使用新的M运行时权限系统。 除了onRequestPermissionsResult()之外,它都在工作。我需要检查按下按钮的权限,如果成功,就发送一条短信。当我授权这样做时,对话框关闭,但它不会触发发送文本,直到我再次按下按钮

我已经在onRequestPermissionsResult()方法中调试和设置了断点,但它从未进入它。

首先调用这个方法:

    private void askForPermission() {
String[] permissions = new String[]{Manifest.permission.SEND_SMS};
ActivityCompat.requestPermissions(getActivity(), permissions, PERMISSIONS_CODE);
}

然后我的回调函数是这样的:

    @Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);


if (requestCode == PERMISSIONS_CODE) {
for (int i = 0; i < permissions.length; i++) {
String permission = permissions[i];
int grantResult = grantResults[i];


if (permission.equals(Manifest.permission.SEND_SMS)) {
if (grantResult == PackageManager.PERMISSION_GRANTED) {
onPPSButtonPress();
} else {
requestPermissions(new String[]{Manifest.permission.SEND_SMS}, PERMISSIONS_CODE);
}
}
}
}
}
有人遇到过类似的问题吗? 感谢任何帮助。 由于< / p >
195996 次浏览

你可以试试这个:

requestPermissions(permissions, PERMISSIONS_CODE);

如果你从一个片段中调用这段代码,它有自己的requestPermissions方法。我相信问题是你正在调用静态方法。

如果你想在一个片段中使用onRequestPermissionsResult(): FragmentCompat.requestPermissions(Fragment fragment, String[] permissions, int requestCode) < / p >
你有checkpermission函数用于FragmentCompat中的pre Marshmallow设备。 我这样使用:

FragmentCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);

我也遇到了同样的问题,我只是找到了解决方案。在使用Support库时,必须使用正确的方法调用。例如:

  • AppCompatActivity中,你应该使用ActivityCompat.requestPermissions;
  • 当在android.support.v4.app.Fragment中,你应该简单地使用requestPermissions(这是android.support.v4.app.Fragment的实例方法)

如果你调用ActivityCompat。在一个片段中,onRequestPermissionsResult回调是在活动上调用的,而不是在片段上。

这个问题实际上是由NestedFragments引起的。 基本上大多数片段都扩展了一个hostdfragment,而hostdfragment又扩展了一个CompatFragment。这些嵌套的片段导致了一些问题,这些问题最终由项目中的另一个开发人员解决

他正在做一些低级别的东西,比如位切换来让它工作,所以我不太确定实际的最终解决方案

如果在activity和fragment中都有onRequestPermissionsResult,请确保在activity中调用super.onRequestPermissionsResult。它不是片段所需要的,但它是活动所需要的。

如果你在fragment中使用requestPermissions,它接受2个而不是3个参数。

你应该使用requestPermissions(permissions, PERMISSIONS_CODE);

如果出于某种原因,你扩展了一个自定义Activity,这个Activity位于一些外部库中,不调用super,你将需要手动调用Fragment super。onRequestPermissionsResult你在你的活动onRequestPermissionsResult。

YourActivity extends SomeActivityNotCallingSuperOnRequestPermissionsResult{
Fragment requestingFragment;//the fragment requesting the permission
...
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestingFragment!=null)
requestingFragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
...

这会起作用的。

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}

我发现在调用android.support.v4.app.Fragment.requestPermissions时这很重要。

如果在onCreate()中执行,onRequestPermissionsResult()将永远不会被调用。

解决方案:在onActivityCreated()中调用它;

@Override
public void onActivityCreated(Bundle savedInstanceState) {


super.onActivityCreated(savedInstanceState);


if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_DENIED)
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, 0);


}
 /* use the object of your fragment to call the
* onRequestPermissionsResult in fragment after
* in activity and use different request Code for
* both Activity and Fragment */


if (isFragment)
mFragment.requestPermissions(permissions.toArray(new
String[permissions.size()]),requestPermission);


else
ActivityCompat.requestPermissions(mActivity,permissions.toArray(new
String[permissions.size()]),requestPermission);

我也遇到过这个问题。如果你想让处理权限的活动不在历史记录/最近记录中,那么你会被诱惑去改变你的AndroidManifest.xml条目。

如果你设置了调用requestPermissionsAppCompatActivity.requestPermissions的活动

android:noHistory="true"
android:excludeFromRecents="true"

在你的AndroidManifest.xml中,那么onRequestPermissionsResult()将不会被调用。如果你的Activity是从ActivityAppCompatActivity派生的,这是正确的。

这可以通过从'AndroidManifest.xml'中删除这两个标志并使用finishAndRemoveTask()来完成您的活动来修复。

回答不赞成,请参阅: https://developer.android.com/training/permissions/requesting < / p >

在片段中,你需要调用:

FragmentCompat.requestPermissions(permissionsList, RequestCode)

不是:

ActivityCompat.requestPermissions(Activity, permissionsList, RequestCode);

在你根据上面的答案检查一切之前,确保你的请求代码不是0!!

检查FragmentActivity.java中onRequestPermissionsResult()的代码:

public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
int index = (requestCode>>16)&0xffff;
if (index != 0) {
index--;


String who = mPendingFragmentActivityResults.get(index);
mPendingFragmentActivityResults.remove(index);
if (who == null) {
Log.w(TAG, "Activity result delivered for unknown Fragment.");
return;
}
Fragment frag = mFragments.findFragmentByWho(who);
if (frag == null) {
Log.w(TAG, "Activity result no fragment exists for who: " + who);
} else {
frag.onRequestPermissionsResult(requestCode&0xffff, permissions, grantResults);
}
}
}
private void showContacts() {
if (getActivity().checkSelfPermission(Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
} else {
doShowContacts();
}
}


@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
doShowContacts();
}
}

我希望它能正常工作

活动:

 ActivityCompat.requestPermissions(this,permissionsList,REQUEST_CODE);

对于片段:

 requestPermissions(permissionsList,REQUEST_CODE);

你可以使用requestPermissions(PERMISSIONS, MULTIPLE_PERMISSIONS_CODE);。如果您正在使用v4,请不要使用FragmentCompat。

如果你从一个片段中调用这段代码,它有自己的requestPermissions方法。

基本概念是,如果你在一个活动中,那么调用

ActivityCompat.requestPermissions(this,
permissionsList,
permissionscode);

如果是碎片,就打电话

requestPermissions(permissionsList,
permissionscode);

基于goodgamerguy的回答的解决方案是:

myFragment.this.requestPermissions(....)

更新:看到其他人关于在活动中调用super.onRequestPermissionResult()的回答,这修复了我提到的请求代码问题,并调用片段的onRequestPermissionResult。

忽略这些东西:

对我来说,它调用了活动的onRequestPermissionResult,尽管我调用了fragment.requestPermission(...),但它返回了一个错误的requestCode(111变成65647为什么??)我永远也不会知道)。

幸运的是,这是我们在屏幕上请求的唯一权限,所以我只是忽略了请求代码(没有时间弄清楚为什么它现在不正确)

我有一个很棒的解决方案来实现这个,像这样创建一个BaseActivity。

public class BaseActivity extends AppCompatActivity {


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this));




}


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
CustomToast.getInstance().setCustomToast("Now you can share the Hack.");


} else {
Toast.makeText(this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
}
}
}
}

现在你可以像这样调用代码来请求许可

 ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

每次这发生在任何地方无论是在片段中还是在任何活动中基活动都会被调用。

谢谢

细节

  • 芬兰湾的科特林1.2.70
  • 在minSdkVersion 19中检查
  • Android studio 3.1.4

算法

模块 -相机,位置,....

  1. 检查hasSystemFeature(如果模块存在于phone中)
  2. 检查用户是否有权访问模块
  3. 发送权限请求(请求用户允许模块使用)

特性

  1. 使用活动和片段
  2. 只有一个结果响应
  3. 可以检查几个模块在一个请求

解决方案

class PermissionType(val manifest_permission: String, val packageManager: String) {
object Defined {
val camera = PermissionType(Manifest.permission.CAMERA, PackageManager.FEATURE_CAMERA)
val currentLocation = PermissionType(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.FEATURE_LOCATION_GPS)
}
}


class  Permission {


enum class PermissionResult {
ACCESS_ALLOWED, ACCESS_DENIED, NO_SYSTEM_FEATURE;
}


interface ManagerDelegate {
fun permissionManagerDelegate(result: Array<Pair<String, PermissionResult>>)
}


class Manager internal constructor(private val delegate: ManagerDelegate?) {


private var context: Context? = null
private var fragment: Fragment? = null
private var activity: AppCompatActivity? = null
private var permissionTypes: Array<PermissionType> = arrayOf()
private val REQUEST_CODE = 999
private val semaphore = Semaphore(1, true)
private var result: Array<Pair<String, PermissionResult>> = arrayOf()




constructor(permissionType: PermissionType, delegate: ManagerDelegate?): this(delegate) {
permissionTypes = arrayOf(permissionType)
}


constructor(permissionTypes: Array<PermissionType>, delegate: ManagerDelegate?): this(delegate) {
this.permissionTypes = permissionTypes
}


init {
when (delegate) {
is Fragment -> {
this.fragment = delegate
this.context = delegate.context
}


is AppCompatActivity -> {
this.activity = delegate
this.context = delegate
}
}
}


private fun hasSystemFeature(permissionType: PermissionType) : Boolean {
return context?.packageManager?.hasSystemFeature(permissionType.packageManager) ?: false
}


private fun hasAccess(permissionType: PermissionType) : Boolean {
return if (Build.VERSION.SDK_INT < 23) true else {
context?.checkSelfPermission(permissionType.manifest_permission) == PackageManager.PERMISSION_GRANTED
}
}


private fun sendRequest(permissionTypes: Array<String>) {


if (fragment != null) {
fragment?.requestPermissions(permissionTypes, REQUEST_CODE)
return
}


if (activity != null){
ActivityCompat.requestPermissions(activity!!, permissionTypes, REQUEST_CODE)
}
}


fun check() {


semaphore.acquire()
AsyncTask.execute {
var permissionsForSendingRequest: Array<String> = arrayOf()
this.result = arrayOf()


for (it in permissionTypes) {
if (!hasSystemFeature(it)) {
result += Pair(it.manifest_permission, PermissionResult.NO_SYSTEM_FEATURE)
continue
}


if (hasAccess(it)) {
result += Pair(it.manifest_permission, PermissionResult.ACCESS_ALLOWED)
} else {
permissionsForSendingRequest += it.manifest_permission
}
}


if (permissionsForSendingRequest.isNotEmpty()) {
sendRequest(permissionsForSendingRequest)
} else {
delegate?.permissionManagerDelegate(result)
}
}
}


fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
REQUEST_CODE -> {
if (grantResults.isEmpty()) {
return
}
for ((i,permission) in permissions.withIndex()) {
for (item in this.permissionTypes) {
if (permission == item.manifest_permission && i < grantResults.size) {
result += if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
Pair(item.manifest_permission, PermissionResult.ACCESS_ALLOWED)
} else {
Pair(item.manifest_permission, PermissionResult.ACCESS_DENIED)
}
break
}
}
}
delegate?.permissionManagerDelegate(result)
}
}
semaphore.release()
}
}
}

在活动中的使用(在片段中相同)

class BaseActivity : AppCompatActivity(), Permission.ManagerDelegate {


private lateinit var permissionManager: Permission.Manager


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.base_activity)


permissionManager = Permission.Manager(arrayOf(PermissionType.Defined.camera, PermissionType.Defined.currentLocation), this)
permissionManager.check()
}


override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
permissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults)
}




override fun permissionManagerDelegate(result: Array<Pair<String, Permission.PermissionResult>>) {
result.forEach {
println("!!! ${it.first} ${it.second}")
//            when (it.second) {
//                Permission.PermissionResult.NO_SYSTEM_FEATURE -> {
//                }
//
//                Permission.PermissionResult.ACCESS_DENIED  -> {
//                }
//
//                Permission.PermissionResult.ACCESS_ALLOWED -> {
//                }
//            }
}
}
}

我有一个类似的问题,除了我按下一个按钮进行调用,这触发了callIntent。我首先检查权限,如果没有授予我要求权限和onRequestPermissionResult我调用检查权限,并再次调用。

 @Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case Constants.PERMISSIONS_REQUEST_CALL_PHONE: {
if ( grantResults[0] == PackageManager.PERMISSION_GRANTED) {


checkPermissionsAndCall();
}
}
}
}


public void checkPermissionsAndCall(){
if (Build.VERSION.SDK_INT > 22) {
if(ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED){
requestPermissions( new String[]{Manifest.permission.CALL_PHONE}, Constants.PERMISSIONS_REQUEST_CALL_PHONE);
}
else{
callIntent();
}
}
}

在这里,我想展示我的代码我是如何做到这一点的。

public class CheckPermission {


public Context context;


public static final int PERMISSION_REQUEST_CODE =  200;


public CheckPermission(Context context){
this.context = context;
}


public boolean isPermissionGranted(){
int read_contact = ContextCompat.checkSelfPermission(context.getApplicationContext() , READ_CONTACTS);
int phone = ContextCompat.checkSelfPermission(context.getApplicationContext() , CALL_PHONE);


return read_contact == PackageManager.PERMISSION_GRANTED && phone == PackageManager.PERMISSION_GRANTED;
}
}

在这个类中,我想检查许可是否被授予。那我是不是会从我的MainActivity调用许可呢

public void requestForPermission() {
ActivityCompat.requestPermissions(MainActivity.this, new String[]    {READ_CONTACTS, CALL_PHONE}, PERMISSION_REQUEST_CODE);
}


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION)) {
showMessageOKCancel("You need to allow access to both the permissions",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.CALL_PHONE},
PERMISSION_REQUEST_CODE);
}
}
});
return;
}
}
}
}

现在在onCreate方法中,你需要调用requestForPermission()函数。

就是这样。您也可以同时请求多个权限。

我还遇到了一个问题,即使你调用正确的requestPermissions,你仍然可以有这个问题。问题是父活动可能会在不调用super的情况下重写此方法。加上超级,问题就解决了。

对于kotlin用户,这里我的扩展检查和验证权限没有覆盖onRequestPermissionResult

 * @param permissionToValidate (request and check currently permission)
*
* @return recursive boolean validation callback (no need OnRequestPermissionResult)
*
* */
internal fun Activity.validatePermission(
permissionToValidate: String,
recursiveCall: (() -> Boolean) = { false }
): Boolean {
val permission = ContextCompat.checkSelfPermission(
this,
permissionToValidate
)


if (permission != PackageManager.PERMISSION_GRANTED) {
if (recursiveCall()) {
return false
}


ActivityCompat.requestPermissions(
this,
arrayOf(permissionToValidate),
110
)
return this.validatePermission(permissionToValidate) { true }
}


return true


}