我正在尝试使用SmsManager发送短信。下面是我的代码,然后按照android文档进行操作。但是问题是,在权限窗口上按DENY / ALLOW按钮后,它不会触发onRequestPermissionsResult回调。我甚至在其中一篇博文中根据某人的建议添加了super.onRequestPermissionsResult。我已经通过设置断点在Log语句和调试模式下进行了测试,但是onRequestPermissionsResult根本没有被调用。因此,即使在授予许可后,第一个SMS也不会消失,也不会显示“ SMS sent。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.
}
}
答案 0 :(得分:0)
我的错误。甚至在触发onRequestPermissionsResult之前,该活动就被杀死了。更改了代码,以防止活动被杀死。