我如何发送结果数据广播接收到活动 [英] How can I send result data from Broadcast Receiver to Activity

查看:115
本文介绍了我如何发送结果数据广播接收到活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调用广播接收器的活动。广播接收机等待和倾听GPS。当听众获得新点我要发新点的活动。我怎样才能发送数据广播接收到活动?

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

这篇关于我如何发送结果数据广播接收到活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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