How can I send result data from Broadcast Receiver to Activity

后端 未结 4 710
刺人心
刺人心 2020-12-06 02:26

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 Ac

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 02:55

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

    }

    in My receiver class wich is named as ReceiverPositioningAlarm:

    // listener ----------------------------------------------------
    
    static ArrayList arrOnNewLocationListener =
            new ArrayList();
    
    // 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);
    

提交回复
热议问题