如何发送短信?这似乎很简单,但对我来说不起作用。
我在清单中获得了许可:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.healthapp.healthapp">
<uses-permission android:name="android.permission.SEND_SMS"/>
<application ...
然后我在onClick中使用了这段代码:
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("07123456789", null, "Hello there!", null, null);
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
但是当我运行这个时,我得到“不幸的是App停止了。”
错误信息:
FATAL EXCEPTION: main
Process: com.healthapp.healthapp, PID: 13477
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW typ=vnd.android-dir/mms-sms (has extras) }
答案 0 :(得分:2)
您有两种不同的方法可以在您的代码中发送短信。如果您要使用SmsManager
,则不需要Intent
/ startActivity()
方法,该方法会尝试打开另一个应用来处理短信。
您可以删除smsManager.sendTextMessage()
行之后的所有内容,但不会再获得Exception
。
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("07123456789", null, "Hello there!", null, null);
答案 1 :(得分:1)
如果你想通过Intent那么
sendSmsByViewIntent()
Intent smsVIntent = new Intent(Intent.ACTION_VIEW);
// prompts only sms-mms clients
smsVIntent.setType("vnd.android-dir/mms-sms");
// extra fields for number and message respectively
smsVIntent.putExtra("address", phoneNumber.getText().toString());
smsVIntent.putExtra("sms_body", smsBody.getText().toString());
try{
startActivity(smsVIntent);
} catch (Exception ex) {
Toast.makeText(MainActivity.this, "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
然后由SmsManager发送,
sendSmsByManager()
try {
// Get the default instance of the SmsManager
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber.getText().toString(),
null,
smsBody.getText().toString(),
null,
null);
Toast.makeText(getApplicationContext(), "Your sms has successfully sent!",
Toast.LENGTH_LONG).show();
} catch (Exception ex) {
Toast.makeText(getApplicationContext(),"Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
发送,
ACTION_SENDTO
// add the phone number in the data
Uri uri = Uri.parse("smsto:" + phoneNumber.getText().toString());
Intent smsSIntent = new Intent(Intent.ACTION_SENDTO, uri);
// add the message at the sms_body extra field
smsSIntent.putExtra("sms_body", smsBody.getText().toString());
try{
startActivity(smsSIntent);
} catch (Exception ex) {
Toast.makeText(MainActivity.this, "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
应该尝试任何一种这些方法。但你在同一时间尝试两种类型。
最后主要是manifest.xml上的权限
<uses-permission android:name="android.permission.SEND_SMS"/>