I have problem in permission request , when I run my application I get this message. When i click on the "give me permission" it opens toast and ask me to allow or deny , when i click allow it will close the application. Then i should open it again and it will work correctly. When i click on the button there is toast message that I allow permission , Is there any fault in my code ?
Thank you
IN MANIFEST:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
in java code in onclick() function that name is onSubmit():
public class MainActivity extends AppCompatActivity {
private int PHONE_STATE_CODE=1;
private Button button;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
textView = (TextView) findViewById( R.id.textView2 );
}
public void onSubmit(View v){
TelephonyManager t = (TelephonyManager) getSystemService(
Context.TELEPHONY_SERVICE );
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "you have already granted", Toast.LENGTH_SHORT).show();
} else {
reqPhonePermission();
}
String me =t.getDeviceId();
String id = t.getLine1Number();
}
~~~~~~~ outside onClick()
private void reqPhonePermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)){
new AlertDialog.Builder(this).setTitle("permission needed").setMessage("this permission needed")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_PHONE_STATE},PHONE_STATE_CODE);
}
}) .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).create().show();
} else {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_PHONE_STATE},PHONE_STATE_CODE);
}
}
public void onRequestPermissionResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults ){
if(requestCode == PHONE_STATE_CODE){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"Permission granted",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this,"Permission denied",Toast.LENGTH_SHORT).show();
}
}