发送短信不会启动活动

时间:2017-01-07 05:01:59

标签: android android-mms android-sms

我想从我的应用程序发送短信,我已经在下面写了代码,这非常简单。但我面临的问题是,发送消息时未启动任何活动

  

发送消息的方法:

private void sendSMS(Context context, String phone, String msg){
    Intent smsIntent = new Intent(Intent.ACTION_VIEW);

    smsIntent.setData(Uri.parse("smsto:"));
    smsIntent.putExtra("address", phone);
    smsIntent.putExtra("sms_body", msg);
    smsIntent.setType("vnd.android-dir/mms-sms");

    try {
        startActivity(smsIntent);
        finish();
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(context, "SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
    }
}
  

清单中添加了权限

<uses-permission android:name="android.permission.SEND_SMS" />

它始终显示以catch()

编写的吐司

3 个答案:

答案 0 :(得分:2)

试试这个:

也没有必要:

<uses-permission android:name="android.permission.SEND_SMS" />

只需使用此代码:

Intent sendIntent = new Intent(Intent.ACTION_VIEW);
                sendIntent.setData(Uri.parse("sms:"));
                sendIntent.putExtra("sms_body", "Check out My app for your smartphone. Download it today from https://google.com");
                try {
                    startActivity(sendIntent);
                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();                        
                }

答案 1 :(得分:1)

您正在执行的代码是旧的。 这是从您的APP发送短信的代码

public void sendSMSFunction(){
     SmsManager smsManager = SmsManager.getDefault();
     String messageContent = "Your Content";
     smsManager.sendTextMessage("Destination_PhoneNumber", null, messageContent, null, null);
}

并将此权限添加到您的清单文件

<uses-permission android:name="android.permission.SEND_SMS"/>

如果您在Android Marshmallow及以上版本中执行此操作,则需要询问运行时权限。

答案 2 :(得分:0)

当你举杯时,总是意味着它进入了catch()。 Catch正在处理 ActivityNotFoundException

  

如果有帮助,请点击此链接:

https://stackoverflow.com/a/10613004/5722385

如果您正在使用棉花糖及以上,请通过以下链接,它有示例如何添加运行时权限

https://stackoverflow.com/a/34969604/5722385

由于发送短信被分组为危险权限,因此您也需要在运行时处理它,因此仅在清单文件中写入权限是不够的。

在添加运行时权限之前,如果您需要可以从手机启用权限,请按照以下步骤操作。

  

转到设置 - &gt;应用 - &gt;选择你的应用 - &gt;权限 - &gt;启用   短信许可。

您还可以查看此链接以获取应在运行时处理的危险权限列表

https://developer.android.com/guide/topics/permissions/requesting.html