[英]How to define custom events and event listeners in Android?
I'm a starter in Android app development, and my experience in Java development is also minimal. 我是Android应用程序开发的入门者,而我在Java开发方面的经验也很少。
I'm working on a very basic context-aware application and I want to understand how can I notify my activity class of some custom event? 我正在开发一个非常基础的上下文感知应用程序,我想了解如何将某些自定义事件通知我的活动类? (unlike onClick()).
(与onClick()不同)。 So if I have a class which is responsible for monitoring some resource.
因此,如果我有一个班级负责监视某些资源。 (For simplicity, let's assume a Timer class which monitors time and notifies the Activity class every hour).
(为简单起见,我们假设一个Timer类监视时间并每小时通知一次Activity类)。
How can my activity class 'subscribe' and listen for such events from the Timer class? 我的活动类如何“订阅”并侦听Timer类中的此类事件?
I would really appreciate if you provide some code example and perhaps how event handling works in Android/Java. 如果您提供一些代码示例以及事件处理在Android / Java中的工作方式,我将不胜感激。 Thanks for your time and help!
感谢您的时间和帮助!
Use Broadcast
Intents to notify listeners of system or application/custom events.. 使用
Broadcast
意图可将系统或应用程序/自定义事件通知给侦听器。
send a Broadcast
using sendBroadcast
method whenever your custom event occurs.. 每当您的自定义事件发生时,使用
sendBroadcast
方法发送Broadcast
。
Intent intent = new Intent(NEW_Intent);
intent.putExtra(“Test”,Test1);
sendBroadcast(intent);
To create a new Broadcast Receiver(which will listen to your event/broadcast), extend the BroadcastReceiver
class and override the onReceive
event handler.The onReceive
method will be executed when a Broadcast
Intent is received that matches the Intent Filter used to register the receiver. 要创建一个新的广播接收器(它将监听您的事件/广播),请扩展
BroadcastReceiver
类并覆盖onReceive
事件处理程序。当接收到与用于注册接收器的Intent过滤器匹配的Broadcast
Intent时,将执行onReceive
方法。 。
Register your receiver in either Manifest file or in the code.. 在清单文件或代码中注册您的接收器。
//in xml //在xml中
<receiver android:name=”.ReceiverName”>
<intent-filter>
<action android:name=”com.paad.action.NEW_INTENT”/>
</intent-filter>
</receiver>
//in code.. //在代码中..
IntentFilter filter = new IntentFilter(NEW_INTENT);
ReceiverName r = new ReceiverName();
registerReceiver(r, filter);
您可以使用Intent类: http : //developer.android.com/reference/android/content/Intent.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.