0
我需要启动一个应用程序时,只收到来自特定号码和某个端口的SMS。如果应用程序已经运行,我需要解析这个消息。我如何使用PendingIntent来做到这一点?如何在收到短信时使用PendingIntent启动应用程序?
我需要启动一个应用程序时,只收到来自特定号码和某个端口的SMS。如果应用程序已经运行,我需要解析这个消息。我如何使用PendingIntent来做到这一点?如何在收到短信时使用PendingIntent启动应用程序?
首先让接收这样的消息的broadcastreceiver类。 并在收到短信时触发你班级的意图。
class SMSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
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]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
Intent mainActivityIntent = new Intent(context, SMS.class);
mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mainActivityIntent);
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
broadcastIntent.putExtra("sms", str);
context.sendBroadcast(broadcastIntent);
}
}
}
存储在字符串中作为sms_sender
String msg_sender=msg[0].getOriginatingAddress();
和接收到消息后,得到的条件是
if(msg_sender=(String)"your_unique_number")
and fire the intent of your class if this condition is true.