从广播接收呼叫活动的方法 [英] call activity method from broadcast receiver

查看:144
本文介绍了从广播接收呼叫活动的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在主要活动,一个布局被加载,有一些输入字段和提交按钮。当点击提交按钮时,onclick处理方法发送短信回相同的手机号码:

In the main activity, a layout is loaded that has some input fields and a submit button. When the submit button is clicked, the onClick handler method sends an sms back to the same mobile number :

SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(number, null, "hi", null, null);

有定义的广播接收机截获的消息:

There is a broadcast receiver defined that intercepts the message :

public class SmsReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Bundle pdusBundle = intent.getExtras();
    Object[] pdus=(Object[])pdusBundle.get("pdus");
    SmsMessage messages=SmsMessage.createFromPdu((byte[]) pdus[0]);
    if(messages.getMessageBody().contains("hi")){
        abortBroadcast();
    }

}
}

现在,从广播接收器,我想调用一个函数(参数),这是在我的主要活动。那可能吗?如果是的话,我应该加入我的广播接收器有什么样的code?

Now, from the broadcast receiver, I want to call a function(with parameter), which is within my main activity. Is that possible? If yes, what kind of code should i add in my broadcast receiver ?

推荐答案

感谢@Manishika。要精心,制作,而不是将其定义在清单中的BroadcastReceiver动态,并获得成功。所以在我的广播接收机类,我添加了code:

Thanks @Manishika. To elaborate, making the Broadcastreceiver dynamic, instead of defining it in the manifest, did the trick. So in my broadcast receiver class, i add the code :

MainActivity main = null;
void setMainActivityHandler(MainActivity main){
    this.main=main;
}

在的BroadcastReceiver类的onReceive函数结束,我打电话的主要活动的功能:

In the end of the onReceive function of the BroadcastReceiver class, I call the main activity's function :

main.verifyPhoneNumber("hi");

在主要活动,我动态地定义和发送短信之前注册的广播接收器:

In the main activity, I dynamically define and register the broadcast receiver before sending the sms :

SmsReceiver BR_smsreceiver = null;
            BR_smsreceiver = new SmsReceiver();
            BR_smsreceiver.setMainActivityHandler(this);
            IntentFilter fltr_smsreceived = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
            registerReceiver(BR_smsreceiver,fltr_smsreceived);  

这篇关于从广播接收呼叫活动的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆