检查明确的权限?

时间:2018-12-04 09:18:37

标签: java android

  

在我的代码中,将显示权限日志,但在吐司面包中看不到电话号码   如何在使用明确许可的情况下在烤面包消息中获取卡号

public class MainActivity extends AppCompatActivity {
String TAG = "PhoneActivityTAG";
Activity activity = MainActivity.this;
String wantPermission = Manifest.permission.READ_PHONE_STATE;
private static final int PERMISSION_REQUEST_CODE = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (!checkPermission(wantPermission)) {
        requestPermission(wantPermission);
    } else {
        Log.d(TAG, "Phone number: " + getPhone());
    }

}

private String getPhone() {
    TelephonyManager phoneMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    if (ActivityCompat.checkSelfPermission(activity, wantPermission) != PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(this, "my phone no is:-" + phoneMgr,Toast.LENGTH_LONG).show();
    }
    return phoneMgr.getLine1Number();
}

private void requestPermission(String permission){
    if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)){
        Toast.makeText(activity, "Phone state permission allows us to get phone number. Please allow it for additional functionality.", Toast.LENGTH_LONG).show();
    }
    ActivityCompat.requestPermissions(activity, new String[]{permission},PERMISSION_REQUEST_CODE);
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_CODE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG, "Phone number: " + getPhone());
            } else {
                Toast.makeText(activity,"Permission Denied. We can't get phone number.", Toast.LENGTH_LONG).show();
            }
            break;
    }
}

private boolean checkPermission(String permission){
    if (Build.VERSION.SDK_INT >= 23) {
        int result = ContextCompat.checkSelfPermission(activity, permission);
        return result == PackageManager.PERMISSION_GRANTED;
    } else {
        return true;
    }
}
}

请帮助我
如何在烤面包机中获取电话号码?

2 个答案:

答案 0 :(得分:1)

请看一下这篇文章:https://en.proft.me/2017/11/27/how-get-phone-number-programmatically-android/

还值得注意的是,并非所有运营商都将其电话号码存储在sim卡上,因此,您将不得不提示用户手动输入电话号码,因为无法从电话中的任何位置检索到该电话号码< / p>

答案 1 :(得分:0)

签出here的答案。

代码中的一些更正

private String getPhone() {
    TelephonyManager phoneMgr = (TelephonyManager) Context.getSystemService(Context.TELEPHONY_SERVICE);
    if (ActivityCompat.checkSelfPermission(activity, wantPermission) != PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(this, "my phone no is:-" + phoneMgr,Toast.LENGTH_LONG).show();
    }
    return phoneMgr.getLine1Number();
}