捕获短信发送和传递活动

时间:2013-11-06 12:53:19

标签: android sms broadcastreceiver smsmanager

我正在从我的应用发送短信。我能够在服务提供商的设备上成功地做到这一点,但在某些平板电脑设备和服务提供商不可用的模拟器上,我想显示相应的错误消息。我正在使用以下代码(来自{{3}) }):

            String SENT = "SMS_SENT";
            String DELIVERED = "SMS_DELIVERED";

                PendingIntent sentPI = PendingIntent.getBroadcast(
                        ClipResultActivity.this, 0, new Intent(SENT), 0);

                PendingIntent deliveredPI = PendingIntent.getBroadcast(
                        ClipResultActivity.this, 0, new Intent(DELIVERED),
                        0);

                // ---when the SMS has been sent---
                registerReceiver(new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context arg0, Intent arg1) {
                        if (getResultCode() == Activity.RESULT_OK)
                            Toast.makeText(getBaseContext(), "SMS sent",
                                    Toast.LENGTH_SHORT).show();
                        else
                            Toast.makeText(getBaseContext(),
                                    "SMS not sent", Toast.LENGTH_SHORT)
                                    .show();
                    }
                }, new IntentFilter(SENT));

                // ---when the SMS has been delivered---
                registerReceiver(new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context arg0, Intent arg1) {
                        if (getResultCode() == Activity.RESULT_OK)
                            Toast.makeText(getBaseContext(),
                                    "SMS delivered", Toast.LENGTH_SHORT)
                                    .show();
                        else
                            Toast.makeText(getBaseContext(),
                                    "SMS not delivered", Toast.LENGTH_SHORT)
                                    .show();
                    }
                }, new IntentFilter(DELIVERED));

                SmsManager sms = SmsManager.getDefault();
                sms.sendTextMessage(PHONE_NO, null, SMS_BODY, sentPI,
                        deliveredPI);

但是任何BroadcastReceiver都没有在没有服务提供商的设备上执行。我期待两个BroadcastReceiver被执行并返回否定回复。

请注意,BroadcastReceiver中的AndroidManifest.xml未添加有关。虽然我已经添加了短信权限。

我做错了吗?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

rowItem是我的listview的持有者类。我在特定项目上拨打onItemSelectedListener,因此对于您的平板电脑或任何其他设备,我的代码可以使用。如果不支持SMS,则显示Toast。

if(rowItems.get(position).getTitle().endsWith("SMS"))
        {
            if (getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY))
            {   
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.putExtra("address", "0"+9999999999);
                intent.setType("vnd.android-dir/mms-sms"); 
                startActivity(intent);  
            }
            else {
                toast("No SMS Support");
            }
        }