0

我有一个接收器,每当收到短信时都会调用它

public class SMSReceiver extends BroadcastReceiver {

    private SharedPreferences prefs;
    private String prefName = "MyPref";
    private static final String NUMBER_KEY = "number";

    @Override
    public void onReceive(Context context, Intent intent) {
        // ---get the SMS message passed in---
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String str = "";
        String Sender = null;
        if (bundle != null) {
            // ---retrieve the SMS message received---
            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]);
                Sender = msgs[i].getOriginatingAddress();
            }
            prefs = context
                    .getSharedPreferences(prefName, Context.MODE_PRIVATE);
            String phoneNumber = (String) prefs.getString(NUMBER_KEY, "");
            // If the sender of the SMS just received is the same as one chosen
            // earlier
            if (Sender.equals(phoneNumber)) {
                Toast.makeText(context, "text message received",
                        Toast.LENGTH_LONG).show();
                // ---Launch the minderActivity even when the app is not in the
                // foreground---
                Intent minderActivityIntent = new Intent(context, Minder.class);
                minderActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(minderActivityIntent);
                // ---send a broadcast intent to update the SMS received in the
                // activity---
                Intent broadcastIntent = new Intent();
                broadcastIntent.setAction("SMS_RECEIVED_ACTION");
                broadcastIntent.putExtra("Sender", Sender);
                context.sendBroadcast(broadcastIntent);
            }
        }
    }
}

我使用按钮在名为“minder”的活动中注册接收器

registerReceiver(intentReceiver, intentFilter);

在这个“看护人”活动中,我还有一个BroadcastReceiver

private BroadcastReceiver intentReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        // ---gather up all the necessary user input---
        prefs = getSharedPreferences(prefName, MODE_PRIVATE);
        final Button btn2 = (Button) findViewById(R.id.btnContacts);
        String phoneNumber = (String) prefs.getString(NUMBER_KEY, "");
        String messageChosen = (String) prefs.getString(MESSAGE_KEY, "");
        String delay = (String) prefs.getString(DELAY_KEY, "");
        String Sender = (String) intent.getExtras().getString("Sender");
        if (Sender.equals(phoneNumber)) {
            sendSMS(phoneNumber, messageChosen, delay);
        }
    }
};

所有的permissions都在manifest.

不幸的是,当我测试接收器(即在接收器注册后,从定义为“phoneNumber”的号码向手机发送短信)时,应用程序不执行任何操作。我上面的代码中缺少什么想法?

4

0 回答 0