Call activity method from broadcast receiver android?

后端 未结 5 1823
猫巷女王i
猫巷女王i 2021-01-07 15:19

In my application I am sending a port SMS to the mobile. And when the message is recieved I need to perform some task in my activity and update the UI.

Manifest Decl

5条回答
  •  遥遥无期
    2021-01-07 16:17

    The error you get is that you are wrongly casting a android.app.ReceiverRestrictedContext to a com.vfi.VerifyActivity.

    If you want to achieve what you want to do simply start your activity by giving it some extra information.

    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);
        }
    }
    }
    

    And in your other class simply retrieve your message this way :

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

    That's it.

    Hope this help !

提交回复
热议问题