且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将结果数据从广播接收器发送到活动

更新时间:2022-12-29 13:38:02

我为我的接收器定义了一个监听器并在活动中使用它,现在它运行得很好.以后有没有可能出问题?

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