我正在前台显示的服务中需要发送短信,我正在使用服务类中的以下代码
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, "text", null, null);
我已经获得了以下权限android:name =“ android.permission.SEND_SMS”,但它没有工作,没有消息正在发送
答案 0 :(得分:0)
声明:
public static final int PERMISSION_CODE_SEND_SMS = 123;
检查是否授予许可:
if (checkSelfPermission(android.Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{android.Manifest.permission.SEND_SMS},
PERMISSION_CODE_SEND_SMS);
return;
}
现在处理响应:
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_CODE_SEND_SMS: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted send SMS now
} else {
// permission denied ask again
}
return;
}
}
}
答案 1 :(得分:0)
在主要活动中检查权限
private void checkForSmsPermission() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
} else {
// Permission already granted. Enable the SMS button.
permission=1;
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
// For the requestCode, check if permission was granted or not.
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (permissions[0].equalsIgnoreCase(Manifest.permission.SEND_SMS)
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission was granted. Enable sms button.
permission = 1;
} else {
// Permission denied.
permission = 0;
// Disable the sms button.
}
}
}
}
并通过意图将权限详细信息作为权限变量(int)发送到服务类
checkForSmsPermission();
final Intent intent = new Intent(this, Chat.class);
intent.putExtra("permission",permission);
ContextCompat.startForegroundService(this, intent);
服务类别中的chked许可并发送了消息(按下发送按钮时)
if (permission==1) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} else
{
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}