简体   繁体   中英

App crashes when requesting permission

I'm using this code to request SMS permission before running the method SendSMS(string 1, string 2); but my app crashes before permission request takes place. What's missing?

 final private int REQUEST_CODE = 101;

private void SendCreditSMS() {
    if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.SEND_SMS}, REQUEST_CODE);
    } else {
        SendSMS("181", "رصيد");
    }
}

Try this,

    final private int REQUEST_CODE = 101;


    private void SendCreditSMS() {
      if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.SEND_SMS)
                    != PackageManager.PERMISSION_GRANTED) 
            {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{android.Manifest.permission.SEND_SMS}, REQUEST_CODE);
            } else 
            {
                SendSMS("181", "رصيد");
            }
        }
        else{
            SendSMS("181", "رصيد");
        }
    }

The problem may be due to the reason that you declared the activity in which you request permission(s) as with no history. To solve the problem remove android:noHistory="true" line from the associated activity's code block in AndroidManifest file. To have an activity with no history you can use other calls such as finishAndRemoveTask() .

Try going to the application manager in your android device and select the app you are currently executing. Then check whether permissions are given by the device to use send_sms service in your device.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM