无法使用真实设备发送短信。没有错误消息。我允许清单文件中的权限并导入必要的类,但仍然无法弄清楚出了什么问题。任何帮助将不胜感激。
sendMessage(contact,message);
private void sendMessage(String contact, String message)
{
SmsManager smsManager = SmsManager.getDefault();
try {
smsManager.sendTextMessage(contact, null , message , null , null);
Toast.makeText(getApplicationContext(), "SMS Sent.", Toast.LENGTH_LONG).show();
} catch (Exception e)
{
Toast.makeText(getApplicationContext(), "SMS failed to send.", Toast.LENGTH_LONG).show();
}
}
清单
<uses-permission android:name="android.permission.SEND_SMS"/>
答案 0 :(得分:0)
使用此功能..
sendMySMS(personalPhone,消息);
private void sendMySMS(String personalPhone, String messege)
{
SmsManager sms = SmsManager.getDefault();
List<String> messages = sms.divideMessage(messege);
for (String msg : messages)
{
PendingIntent sentIntent = PendingIntent.getBroadcast(getActivity(), 0, new Intent("SMS_SENT"), 0);
PendingIntent deliveredIntent = PendingIntent.getBroadcast(getActivity(), 0, new Intent("SMS_DELIVERED"), 0);
sms.sendTextMessage(personalPhone, null, msg, sentIntent, deliveredIntent);
}
}
添加权限...
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
答案 1 :(得分:0)
如果您使用的是Android 6.0(API 23)或更高版本的真实设备,则必须在运行时请求权限。
SEND_SMS权限被归类为危险权限。
因此,在运行短信发送逻辑之前,您必须询问用户是否允许发送消息。
要做到这一点,首先需要在您的活动中添加它
if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
thisActivity,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
然后,您将检查用户是否已授予添加此覆盖方法的权限
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
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 GRANTED
// Now you can send sms
} else {
// PERMISSION DENIED
// You should disable send sms feature
}
return;
}
}
}