我是Android新手,在我的应用中,我想在不打开现有MessageApp的情况下向手机发送短信。为实现这一目标,我编写了下面的代码,但我手机中没有收到任何消息。
有什么问题?
private void sendSms(String phoneNo, String msg) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, msg, null, null);
Toast.makeText(getApplicationContext(), "Message Sent",
Toast.LENGTH_LONG).show();
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), ex.getMessage().toString(),
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
另外,我将以下权限添加到我的宣言文件中。
<uses-permission android:name="android.permission.SEND_SMS"/>
答案 0 :(得分:2)
您必须导入:import android.telephony.SmsManager;
此外,您还需要为Api&gt; 23
添加运行时权限if(isSMSPermissionGranted()){
sendSms(String phoneNo, String msg);
}
使用此方法:
public boolean isSMSPermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.SEND_SMS)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
return true;
} else {
Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.SEND_SMS}, 0);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
捕获权限结果:
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 0: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getContext(), "Permission granted", Toast.LENGTH_SHORT).show();
//send sms here call your method
sendSms(String phoneNo, String msg);
} else {
Toast.makeText(getContext(), "Permission denied", Toast.LENGTH_SHORT).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
答案 1 :(得分:0)
sendSMS()
功能将是
//---sends an SMS message to another device---
private void sendSMS(String phoneNumber, String message)
{
PendingIntent pi = PendingIntent.getActivity(this, 0,
new Intent(this, SMS.class), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, pi, null);
}
希望本教程能为您提供帮助! https://www.tutorialspoint.com/android/android_sending_sms.htm
答案 2 :(得分:0)
使用此功能......
String mobileNumber="0123456789";
String messege="Message";
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);
}
答案 3 :(得分:-1)
import android.telephony.SmsManager;
不是import android.telephony.gsm.SmsManager;
这项工作在我的手机上。版本6 +可能需要权限,因此请查看并添加权限。它会对你有所帮助。