我有一个活动(Activity)调用了广播接收器(Broadcast Receiver)。广播接收器等待并监听GPS。当监听器获得新点时,我想将该新点发送给活动。如何从广播接收器向活动发送数据?
我需要在我的活动中添加一个监听器,以等待广播接收器的响应。我该如何做到这一点?
我有一个活动(Activity)调用了广播接收器(Broadcast Receiver)。广播接收器等待并监听GPS。当监听器获得新点时,我想将该新点发送给活动。如何从广播接收器向活动发送数据?
我需要在我的活动中添加一个监听器,以等待广播接收器的响应。我该如何做到这一点?
您可以从您的活动中调用接收器。如果您不想在您的活动中添加接收器的逻辑,您可以使用抽象接收器。
您的抽象接收器:
public abstract class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//Add you receiver logic here
...
...
onNewPosition();
}
protected abstract void onNewPosition();
}
在您的活动中:
public class MyActivity extends Activity {
private smsReceiver smsReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_one_position);
smsReceiver = new smsReceiver() {
// this code is call asyncrously from the receiver
@Override
protected void onNewPosition() {
//Add your activty logic here
}
};
IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
intentFilter.setPriority(999);
this.registerReceiver(smsReceiver, intentFilter);
}
@Override
protected void onPause() {
super.onPause();
this.unregisterReceiver(this.smsReceiver);
}
}
希望这能对你有所帮助...
我为我的接收器定义了一个监听器,并在活动中使用它,现在它运行得很好。以后会出现任何问题吗?
public interface OnNewLocationListener {
public abstract void onNewLocationReceived(Location location);
在我的接收器类中,它被命名为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);
}
}
}
在我的一个活动方法中:
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);
只需要在活动中实现广播接收器。使用活动的上下文注册接收器。