在用户输入之前,Android权限请求运行代码

时间:2016-06-15 21:08:32

标签: android android-permissions

我有以下帮助方法来检查权限:

private boolean canAccessLocation() {
        return(hasPermission(Manifest.permission.ACCESS_FINE_LOCATION));
    }
private boolean hasPermission(String perm) {
        return(PackageManager.PERMISSION_GRANTED==checkCallingOrSelfPermission(perm));
    }

我有一个提示用户访问其位置的请求方法

public void requestLocationPermissions(){
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
            Log.d("permissions",
                    "Displaying contacts permission rationale to provide additional context.");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                    REQUEST_LOCATION);

        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                    REQUEST_LOCATION);
        }
    }

我需要位置权限的地方,我写

if(!canAccessLocation()){
            requestLocationPermissions();
        } else {

}
startActivity(new Intent(MyActivity.this, MyOtherActivity.class));

我遇到的问题是,在用户甚至显示允许或拒绝权限的对话之前,新活动是通过意图启动的。因此,如果我的下一个活动中的代码需要用户授予或拒绝权限,那么它将崩溃并且然后询问用户是否要授予权限。我很难让API 23权限系统在这个应用程序上正常工作,我真的可以使用一些帮助。

所以我的问题是:在用户选择是否拒绝或允许权限之前,如何阻止后续代码行的执行?

3 个答案:

答案 0 :(得分:2)

您确实需要在您的Activity中实现此回调,该回调请求权限

void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults);

在该回调中,只需验证requestCode是否是您所请求的,如果grantResults [0] == PackageManager.PERMISSION_GRANTED,那么在获得权限时需要执行的操作如生成新活动。

此外,如果ActivityCompat.shouldShowRequestPermissionRationale调用返回true,则应向用户显示提示以请求权限。用户按“确定”后,您将再次请求权限。

答案 1 :(得分:1)

如果发布的代码段正是您在项目中尝试的内容,那么解决方案很简单:D

ptm <- proc.time()
library(ranger)
library(mlr)

# Define task and learner
task <- makeClassifTask(id = "iris",
                        data = iris,
                        target = "Species")

learner <- makeLearner("classif.ranger")

# Choose resampling strategy and define grid
rdesc <- makeResampleDesc("CV", iters = 5)
ps <- makeParamSet(makeIntegerParam("mtry", 3, 4),
                   makeDiscreteParam("num.trees", 200))

# Tune
res = tuneParams(learner, task, rdesc, par.set = ps,
           control = makeTuneControlGrid())

# Train on entire dataset (using best hyperparameters)
lrn = setHyperPars(makeLearner("classif.ranger"), par.vals = res$x)
m = train(lrn, iris.task)

print(m)
print(proc.time() - ptm) # ~6 seconds

答案 2 :(得分:1)

我挣扎了几个小时,所以我只想把它放在那里以防它对某人有用。

我调整了以下代码: https://developer.android.com/training/permissions/requesting.html

在我的情况下,应用需要请求多个('危险')权限。我会在应用启动时执行此操作,然后再显示启动画面。

P.S。我应该提一下,我没有运气同时请求所有权限,因此递归。希望有可能,有人可以解决这个问题。另外,我已经评论了“我们应该展示一个解释”块。下面的逻辑不适合这种行为,但我把它留给了后代,因为它来自上面的链接。

package a.dangerous.app;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

public class AskMultiplePermsThenSpashActivity extends Activity  {

    static final String[] _requestPermissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_SMS,
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.WRITE_CONTACTS
    };

    @Override
    protected void onStart() {
        super.onStart();

        this.checkPermissions(0);   //start at zero, of course
    }

    private void checkPermissions(int permissionIndex) {
        if(permissionIndex >= _requestPermissions.length) {
            //i.e. we have requested all permissions, so show the splash screen
            this.showSplash();
        }
        else {
            this.askForPermission(_requestPermissions[permissionIndex], permissionIndex);
        }
    }

    private void askForPermission(String permission, int permissionIndex) {
        if (ContextCompat.checkSelfPermission(
                this,
                permission)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            //  if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

            //} else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(
                    this,
                    new String[]{permission},
                    permissionIndex //permissionIndex will become the requestCode on callback
            );
        }
        else {
            this.checkPermissions(permissionIndex+1); //check the next permission
        }
    }

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

        //Regardless of whether the permission was granted we carry on.
        //If perms have been denied then the app must cater for it

        this.checkPermissions(requestCode+1); //check the next permission
    }

    private void showSplash() {
        //(ta da)

        //once splashed, start the main activity
        this.startMainActivity();
    }

    private void startMainActivity() {
        Intent mainIntent = new Intent(
                this,
                MainActivity.class
        );
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

        this.startActivity(mainIntent);

        this.finish();
    }
}