我正在尝试使用SmsManager发送短信。下面是我的代码,按照android文档。但问题是,在权限窗口上按下DENY / ALLOW按钮后,它不会触发onRequestPermissionsResult回调。我甚至在其中一篇帖子中根据某人的建议添加了super.onRequestPermissionsResult。我已经使用Log语句和调试模式通过设置断点进行了测试,但是onRequestPermissionsResult根本没有被调用。因此,即使在授予许可后,第一条SMS也永远不会消失,“SMS发送.1”永远不会显示。我错过了什么?在什么情况下不会触发回调?
private void sendSMSMessage() {
phoneNo = "+919535000000";
message = "Test SMS message";
if (ContextCompat.checkSelfPermission(NewAppointment.this, Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted. Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(NewAppointment.this,
Manifest.permission.SEND_SMS)) {
Toast.makeText(NewAppointment.this,
"Send SMS permission is needed to send notifications.", Toast.LENGTH_LONG).show();
}
// Request the permission
ActivityCompat.requestPermissions(NewAppointment.this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
} else {
// Permission has already been granted
message = "Test SMS message 2";
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent. 2",
Toast.LENGTH_LONG).show();
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.i(TAG,"In onRequestPermissionsResult callback ---> ");
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
message = "Test SMS message 1";
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent. 1",
Toast.LENGTH_LONG).show();
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request.
}
}
我的错。甚至在onRequestPermissionsResult被触发之前,活动就被杀死了。对代码进行了更改,以便不会杀死活动。