请求访问Android SDK中的SEND_SMS和GPS 23

时间:2015-10-01 19:14:49

标签: android permissions

我对Android编程比较陌生。到目前为止,我正在开发一个消息应用程序,它将通过短信发送消息,并可以选择在消息中附加GPS坐标。我在这里遇到的问题是SDK版本23,需要在运行时请求权限,我还没有找到一个很好的例子,我可以在运行应用程序之前请求所需的权限。我的代码示例如下。

如果我注释掉这段代码,Android Studio会编译代码,但当我点击发送消息的按钮时,我的应用程序崩溃了。我的AndroidManifest.xml中有相应的代码,用于使用短信和GPS权限。

if (ContextCompat.checkSelfPermission(MainActivity,
Manifest.permission.SEND_SMS)
    != PackageManager.PERMISSION_GRANTED)
{

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

        Toast.makeText(getBaseContext(),
                "Foo Messenger requires permission to send SMS",
                Toast.LENGTH_SHORT).show();

    }

    else
    {

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

    ActivityCompat.requestPermissions(MainActivity,
            new String[]{Manifest.permission.SEND_SMS},
            MY_PERMISSIONS_REQUEST_SEND_SMS);

    }
}

if (ContextCompat.checkSelfPermission(MainActivity,
Manifest.permission.ACCESS_FINE_LOCATION)
    != PackageManager.PERMISSION_GRANTED)
{

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

        Toast.makeText(getBaseContext(),
                "Foo Messenger requires permission to access GPS to be able to send your coordinates",
                Toast.LENGTH_SHORT).show();

    }

    else
    {

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

        ActivityCompat.requestPermissions(MainActivity,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                MY_PERMISSIONS_REQUEST_SEND_SMS);

      }
}

1 个答案:

答案 0 :(得分:0)

  

无法解析符号checkSelfPermission

您需要在support-v4中的dependencies更新app/build.gradle版本的v23版本(假设您的应用位于app/中):

dependencies {
    compile 'com.android.support:support-v4:23.0.1'
}
  

Manifest.permission.SEND_SMS和PackageManager.PermissionGranted被识别为未知类

您需要为importandroid.Manifest.permission添加android.content.pm.PackageManager个语句。

  

传递给Activity.Compat.requestPermissions()的MainActivity不被视为表达式

MainActivity是一个班级。据推测,您希望该参数为this,或者MainActivity.this