我可以使用BroadcastReceiver中的回调方法吗? [英] Can I use a callback method from a BroadcastReceiver?

查看:126
本文介绍了我可以使用BroadcastReceiver中的回调方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学习使用Android中的BroadcastReceiver类后,我编写了一个小程序来接收电池电量状态并将其写入活动中的三个TextView字段中.

Learning to use the BroadcastReceiver class in Android, I have written a small program to receive the battery charge state and write it to three TextView fields in an activity.

但是,我将BroadcastReceiver设为一个单独的类,以使其更加简单并与活动分开.因此,我必须找到一种方法来告诉Activity类电池数据已更新,或者,这是我的解决方案,是将对TextView字段的引用从Activity传递给BroadcastReceiver类.

However, I have made the BroadcastReceiver as a separate class to make it more simple and separate from the activity. Therefore I have to find a method to tell my Activity class that the battery data has been updated, or, which is my solution, to pass in references to the TextView fields from the Activity to the BroadcastReceiver class.

是否有人知道是否可以从BroadcastReceiver中创建一个回调方法来启动函数f.ex.updateTextViews();在活动中?

Does anyone know whether it is possible to make a callback method from the BroadcastReceiver to start a function, f.ex. updateTextViews(); in the Activity?

这是源代码-请注意有两个Java文件: http://pastebin.com/qjCTsSuH

Here is the source code - note there are two java files: http://pastebin.com/qjCTsSuH

关于,尼尔斯.

推荐答案

我将BroadcastReceiver作为一个单独的类使其变得更加简单

I have made the BroadcastReceiver as a separate class to make it more simple

恕我直言,您使它变得更加复杂.

IMHO, you made it more complex.

因此,我必须找到一种方法来告诉Activity类电池数据已更新,或者,这是我的解决方案,是将对TextView字段的引用从Activity传递到BroadcastReceiver类.

Therefore I have to find a method to tell my Activity class that the battery data has been updated, or, which is my solution, to pass in references to the TextView fields from the Activity to the BroadcastReceiver class.

选项1:只需回到为 BroadcastReceiver 使用内部类即可.无论如何,只能通过 registerReceiver()使用 ACTION_BATTERY_CHANGED .只需让 onReceive()在活动上调用某种方法来完成更新UI的工作即可.

Option #1: Just go back to using an inner class for the BroadcastReceiver. ACTION_BATTERY_CHANGED can only be used via registerReceiver() anyway. Just have onReceive() call some method on the activity to do the work of updating the UI.

选项#2:将您的活动传递到 BroadcastReceiver 的构造函数中,并按照选项#1中的方法调用该方法.

Option #2: Pass your activity into the constructor of the BroadcastReceiver, and call the method as in option #1.

选项3:使用事件总线,例如Square的Otto或greenrobot的EventBus.

Option #3: Use an event bus, like Square's Otto or greenrobot's EventBus.

这篇关于我可以使用BroadcastReceiver中的回调方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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