I am trying to get the IMEI number of the android device.I am able to get it too, but the application doesn't return the IMEI in the first Install. i need to restart the application. Can anyone tell me where I am Wrong? Thanks in advance
public class RootActivity extends AppCompatActivity {
private static final int REQUEST_PERMISSION_PHONE_STATE = 1;
TextView tv ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.TV_imei);
tv.setText(showPhoneStatePermission());
}private String showPhoneStatePermission() {
String imei ="ERROR";
int permissionCheck = ContextCompat.checkSelfPermission(
this, Manifest.permission.READ_PHONE_STATE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_PERMISSION_PHONE_STATE);
} else {
imei=getIMEI();
}
return imei;
}
private String getIMEI() {
TelephonyManager telephonyManager = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
@SuppressLint("MissingPermission") String deviceId = telephonyManager.getDeviceId().trim();
return deviceId;
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
showPhoneStatePermission();
}
}
tv.setText(showPhoneStatePermission())
will only get called once in OnCreate()
. After permission granted in onRequestPermissionsResult
you did not set text .
You need to cal setText()
after onRequestPermissionsResult
.
You can use
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
tv.setText(showPhoneStatePermission());
}
If this is just a sample then Okay . If not then you are missing Permission handling in your code . You need to handle Rational too . Look at android-m-check-runtime-permission