我总是收到Java.Lang.SecurityException的错误:getLine1NumberForDisplay:用户10710和当前进程都没有android.permission.READ_SMS。即使我已经在AndroidManifest.xml中添加了READ_SMS
mycode的:
public string GetNumber()
{
TelephonyManager telephonyManager = (TelephonyManager)GetSystemService(TelephonyService);
return telephonyManager.Line1Number;
}
感谢提前和美好的一天:D
答案 0 :(得分:3)
这是非常简单的运行时权限请求示例。
我强烈建议您阅读下面链接的Xamarin博客文章和Android文档,因为您应该向用户展示"为什么"您在系统对话框出现之前请求权限。
[Activity(Label = "RunTimePermissions", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : Activity
{
const int PermissionSMSRequestCode = 99;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
Button button = FindViewById<Button>(Resource.Id.myButton);
button.Click += delegate {
if ((int)Build.VERSION.SdkInt < 23) // Permissions accepted by the user during app install
DoSomeWork();
var permission = BaseContext.CheckSelfPermission(Manifest.Permission.ReadSms);
if (permission == Android.Content.PM.Permission.Granted) // Did the user already grant permission?
DoSomeWork();
else // Ask the user to allow/deny permission request
RequestPermissions(new string[] { Manifest.Permission.ReadSms }, PermissionSMSRequestCode);
};
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
{
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PermissionSMSRequestCode)
{
if ((grantResults.Count() > 0) && (grantResults[0] == Android.Content.PM.Permission.Granted))
DoSomeWork();
else
Log.Debug("PERM", "The user denied access!");
}
}
protected void DoSomeWork()
{
Log.Debug("PERM", "We have permission, so do something with it");
}
}