问题描述
我有一个调用广播接收器的活动.广播接收器等待并收听 GPS.当侦听器获得新点时,我想将该新点发送到 Activity.如何将数据从广播接收器发送到活动?
I have an Activity that calls a Broadcast Receiver. The Broadcast Receiver waits and listens to GPS. When the listener gets the new point I want to send that new point to Activity. How can I send data from Broadcast Receiver to Activity?
我的活动中需要一个侦听器,等待广播接收器的响应.我该怎么做?
I need a listener in my Activity waiting for response from Broadcast Receiver. How can I do that?
推荐答案
我为我的接收器定义了一个监听器并在活动中使用它,现在它运行得很好.以后有没有可能出问题?
I defined a listener for my receiver and use it in activity and it is running perfect now. Is it possible to happen any problem later?
public interface OnNewLocationListener {
public abstract void onNewLocationReceived(Location location);
}
在我的接收器类中,它被命名为 ReceiverPositioningAlarm:
in My receiver class wich is named as ReceiverPositioningAlarm:
// listener ----------------------------------------------------
static ArrayList<OnNewLocationListener> arrOnNewLocationListener =
new ArrayList<OnNewLocationListener>();
// Allows the user to set an Listener and react to the event
public static void setOnNewLocationListener(
OnNewLocationListener listener) {
arrOnNewLocationListener.add(listener);
}
public static void clearOnNewLocationListener(
OnNewLocationListener listener) {
arrOnNewLocationListener.remove(listener);
}
// This function is called after the new point received
private static void OnNewLocationReceived(Location location) {
// Check if the Listener was set, otherwise we'll get an Exception when
// we try to call it
if (arrOnNewLocationListener != null) {
// Only trigger the event, when we have any listener
for (int i = arrOnNewLocationListener.size() - 1; i >= 0; i--) {
arrOnNewLocationListener.get(i).onNewLocationReceived(
location);
}
}
}
并在我的一种活动方法中:
and in one of my activity's methods:
OnNewLocationListener onNewLocationListener = new OnNewLocationListener() {
@Override
public void onNewLocationReceived(Location location) {
// do something
// then stop listening
ReceiverPositioningAlarm.clearOnNewLocationListener(this);
}
};
// start listening for new location
ReceiverPositioningAlarm.setOnNewLocationListener(
onNewLocationListener);
这篇关于如何将结果数据从广播接收器发送到活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!