0

我正在编写一个具有发送和接收 SMS 消息功能的应用程序。我希望我的应用程序发送的 SMS 消息只能被安装了我的应用程序的另一部手机接收,而不是到达手机的本机 SMS 应用程序。到目前为止,我发现的唯一解决方案是在 Manifest 文件中为 android:priority 设置高优先级:

<receiver android:name=".SMSreceiver">
        <intent-filter android:priority="100">
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
</receiver>

并将 onReceive 方法中的 this.abortBroadcast() 语句放到扩展 BroadcastReceiver 的类中:

public class SMSreceiver extends BroadcastReceiver
{
    private final String CODE = "myappcodeword";

    @Override
    public void onReceive(Context context, Intent intent)
    {
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String from = "";
        String str = "";
        String sms = "";

        if (bundle != null)
        {
            Object [] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            for (int i = 0; i<msgs.length; i++)
            {
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                if (i == 0)
                {
                    from = msgs[i].getOriginatingAddress();
                }
                str += msgs[i].getMessageBody().toString();
            }

            if (str.startsWith(CODE)) // SMS starts with code word therefore was sent by my app
            {
                sms = str.substring(CODE.length()); // extract code word from actual sms message
                Intent SMSIntent = new Intent(context, SMSActivity.class);
                SMSIntent.putExtra("from", from);
                SMSIntent.putExtra("sms", sms);
                SMSIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(SMSIntent); // start new activity using sms info
                this.abortBroadcast();
            }
        }
    }
 }

因为我当然不想阻止不适合我的应用程序的短信,所以我想通过某种关键字启动我的应用程序发送的短信。我的问题是,有没有比这更好的解决方案?(例如,理论上用户实际上可能会故意向包含关键字的人发送短信,无论关键字多么随机,而我的应用程序会将其过滤掉)。如果短信发送到的手机没有安装我的应用程序,上面的代码也不会过滤掉我的应用程序发送的短信。有没有办法先查明手机短信是否安装了我的应用程序?如果未安装该应用程序,那么我希望 SMS 甚至不会出现在该手机上。

4

2 回答 2

1

you might want to look at GCM, allows you to target your application running on targeted devices based on your need.

Google Cloud Messaging for Android

于 2013-05-06T21:36:48.530 回答
0

不,您不能使用 SMS 作为您描述的场景的载体。请记住,SMS 是一种存储和转发服务(在这方面类似于电子邮件),如果收件人未打开或不在覆盖范围内(在某些时候),移动运营商可能会将消息存储很长时间(可能数天)它将被丢弃,但这要由运营商决定)。

于 2013-05-08T16:43:16.477 回答