从广播接收器 android 调用 activity 方法?

Call activity method from broadcast receiver android?

在我的应用程序中,我正在向手机发送端口短信。 收到消息后,我需要在 activity 中执行一些任务并更新 UI.

收件人清单声明

 <receiver android:name="com.vfi.BinarySMSReceiver" >
        <intent-filter android:priority="10" >
            <action android:name="android.intent.action.DATA_SMS_RECEIVED" />

            <data
                android:host="*"
                android:port="9512"
                android:scheme="sms" />
        </intent-filter>
    </receiver>

接收者class

public class BinarySMSReceiver extends BroadcastReceiver {

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

    if (null != bundle) {
        String info = "SMS from ";
        String sender = "";
        String msg = "";

        Object[] pdus = (Object[]) bundle.get("pdus");

        msgs = new SmsMessage[pdus.length];
        byte[] data = null;

        for (int i = 0; i < msgs.length; i++) {
            msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            sender += msgs[i].getOriginatingAddress();
            info += msgs[i].getOriginatingAddress() + "\n";

            data = msgs[i].getUserData();

            for (int index = 0; index < data.length; ++index) {
                info += Character.toString((char) data[index]);
                msg += Character.toString((char) data[index]);
            }
        }
        Log.e("SakjsdMS", "akjsdhkas" + msg);
        Log.e("sender", "asdasdasdasdasdasd" + info);

        ((VerifyActivity)context).msgReceived(msg);
    }
}
}

activity

中的方法
public  void msgReceived(String msgContent)
{
    if(msgContent.equalsIgnoreCase(etMobile.getText().toString().trim())){
        showToast("Number Verified");
    }else{
        showToast("Sorry wrong number. Input your number again.");
    }

}

我得到的异常

java.lang.RuntimeException: Unable to start receiver com.vfi.BinarySMSReceiver: java.lang.ClassCastException: android.app.ReceiverRestrictedContext cannot be cast to com.vfi.VerifyActivity
        at android.app.ActivityThread.handleReceiver(ActivityThread.java:2467)
        at android.app.ActivityThread.access00(ActivityThread.java:145)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1319)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5127)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.ClassCastException: android.app.ReceiverRestrictedContext cannot be cast to com.vfi.VerifyActivity
        at com.vfi.BinarySMSReceiver.onReceive(BinarySMSReceiver.java:46)
        at android.app.ActivityThread.handleReceiver(ActivityThread.java:2460)

价格为 android.app.ActivityThread.access1700 美元(ActivityThread.java:145)

如何在接收方中获取 activity 上下文来调用我的方法?

默认情况下,您的 BroadcastReceiver 对任何 activity 都一无所知。您必须为其提供上下文,例如在您创建 broadcastReceiver 时在构造函数中。

private Activity activity;
public BroadcastReceiver(Activity activity) {
    super();
    this.activity = activity;
}

在您的 onReceive 方法中,您现在可以以任何您喜欢的方式使用您的 activity。

((VerifyActivity)context).msgReceived(msg); 那是你的错误。 您为什么假设此上下文是您的 activity?

执行此操作的最佳方法(没有第 3 方库)是发送本地广播。

在这个其他回答中,我给出了如何使用 LocalBroadcast Best practice to launch AsyncTask from custom view

的大致思路

如果您可以使用第 3 方库,我建议您从 Square

查看 Otto

BinarySMSReceiveronReceive 中传递的 Context 不是 Activity - 它是 Context in which the receiver is running。要启动 Activity,您需要使用 context.startActivity(Intent) 并使用 Intent 将任何其他数据传递给 Activity。

您得到的错误是您错误地将 android.app.ReceiverRestrictedContext 转换为 com.vfi.VerifyActivity

如果你想实现你想做的事情,只需给它一些额外的信息来开始你的 activity。

public class BinarySMSReceiver extends BroadcastReceiver {

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

    if (null != bundle) {
        String info = "SMS from ";
        String sender = "";
        String msg = "";

        Object[] pdus = (Object[]) bundle.get("pdus");

        msgs = new SmsMessage[pdus.length];
        byte[] data = null;

        for (int i = 0; i < msgs.length; i++) {
            msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            sender += msgs[i].getOriginatingAddress();
            info += msgs[i].getOriginatingAddress() + "\n";

            data = msgs[i].getUserData();

            for (int index = 0; index < data.length; ++index) {
                info += Character.toString((char) data[index]);
                msg += Character.toString((char) data[index]);
            }
        }
        Log.e("SakjsdMS", "akjsdhkas" + msg);
        Log.e("sender", "asdasdasdasdasdasd" + info);

        // HERE COMES THE CHANGE
        Intent intent = new Intent(context, YourActivityToLaunch.class);
        intent.putExtra("message_received", msg);
        context.startActivity(intent);
    }
}
}

而在您的另一个 class 中,只需以这种方式检索您的消息:

Intent intent = getIntent();
String message = intent.getStringExtra("message_received");

就是这样。

希望对您有所帮助!

我能够通过以编程方式声明接收器来解决它:

在 activity 之前发送消息

private void sendSMS() {
    BinarySMSReceiver smsReceiver = null;
    smsReceiver = new BinarySMSReceiver();
    smsReceiver.setActivityHandler(this);
    IntentFilter portIntentFilter = new IntentFilter("android.intent.action.DATA_SMS_RECEIVED");
    portIntentFilter.addDataAuthority("*", "9512");
    portIntentFilter.addDataScheme("sms");
    registerReceiver(smsReceiver, portIntentFilter);



        String messageText = etMobile.getText().toString().trim();
        short SMS_PORT = 9512;
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendDataMessage(etMobile.getText().toString().trim(), null, SMS_PORT, messageText.getBytes(), null, null);
}

在接收器中class

 public class BinarySMSReceiver extends BroadcastReceiver {
    VerifyActivity vAct = null;

    void setActivityHandler(VerifyActivity main) {
        vAct = main;
    }

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

        if (null != bundle) {
            String info = "SMS from ";
            String sender = "";
            String msg = "";

            Object[] pdus = (Object[]) bundle.get("pdus");

            msgs = new SmsMessage[pdus.length];
            byte[] data = null;

            for (int i = 0; i < msgs.length; i++) {
                msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                sender += msgs[i].getOriginatingAddress();
                info += msgs[i].getOriginatingAddress() + "\n";

                data = msgs[i].getUserData();

                for (int index = 0; index < data.length; ++index) {
                    info += Character.toString((char) data[index]);
                    msg += Character.toString((char) data[index]);
                }
            }

            Log.e("message", "receiver " + msg);
            Log.e("sender", "from " + info);
            vAct.msgReceived(msg);  //activity method
        }
    }
}

取消注册接收器

 @Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(smsReceiver);
}