0

我在android中编写了发送和接收程序。当从特殊号码收到短信时,短信会转到我的程序和短信正文,以文本形式显示。但是对于从其他电话号码收到的短信,短信转到手机的收件箱并且程序没有打开。现在在我的程序中,对于每条收到的短信,都会打开程序并在 textview 中显示短信正文。如果条件不起作用!!!我把我的代码,请检查我的代码。短信接收器.java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class SmsReceiver extends BroadcastReceiver {
    public String str = "";
    static final String ACTION =
            "android.provider.Telephony.SMS_RECEIVED";
    @Override
    public void onReceive(Context context, Intent intent) {
         if (intent.getAction().equals(ACTION)) {       
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        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]);               
                String msg_from = msgs[i].getOriginatingAddress();    
                if(msg_from.equals("+9891--------"))
                {
                str += "SMS from " + msgs[i].getOriginatingAddress();
                str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "\n";
               }
            }
            Intent act = new Intent(context, MainActivity.class);
            act.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            act.putExtra("message", str);
            context.startActivity(act);
            }
        abortBroadcast();
        }
    }
}
4

1 回答 1

1

您应该context.startActivity(act);在 if 条件下执行。我认为您错误地将其排除在 if 条件之外。也abortBroadcast()应该在 if 条件下因为这是有道理的,如果 msg 不是来自特殊号码,它应该进入收件箱....对 :)

编辑:

public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(ACTION)) {
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        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]);
                String msg_from = msgs[i].getOriginatingAddress();
                if (msg_from.equals("+9891--------")) {
                    String str = "SMS from " + msgs[i].getOriginatingAddress();
                    str += " :";
                    str += msgs[i].getMessageBody().toString();
                    str += "\n";
                    Intent act = new Intent(context, MainActivity.class);
                    act.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    act.putExtra("message", str);
                    context.startActivity(act);
                    abortBroadcast();
                }
            }

        }

    }
}
于 2012-12-10T08:12:23.273 回答