in my code the permission log will be display but the phone number is not visible in toast how to get simcard number in the toast message with the use of explicit permission
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;
}
}
}
please help me
how can i get phone number in the display toast?