我想动态控制位置跟踪(注册/取消注册位置广播接收器)。这就是我计划这样做的方式。我有两个问题:
下面的实现有什么错误,因为我对android / java dev非常新,所有这个概念对我来说仍然非常理论化。仍然在构建概念!
如何将某个EXTRA_INFO从我的位置库类传递到位置接收器。
实现:
我有一个库类LocationLibrary.java,它由两个方法组成。顾名思义,他们这样做。当我调用startTracking()时,位置跟踪应该开始。 Plz注意需要传递给myLocationReceiver的extraInfo。当调用stopTracking()时,跟踪应该停止。
代码段:
public class LocationLibraray
{
private static BroadcastReceiver myLocationReceiver;
public LocationLibraray(Context context)
{
this.ctx = context;
myLocationReceiver = new MyLocationReceiver();
}
public void startTracking(Context context, String extraInfo)
{
IntentFilter filter = new IntentFilter();
filter.addAction("com.app.android.tracker.LOCATION_READY");
context.registerReceiver(myLocationReceiver, filter);
// NEED TO PASS extraInfo to myLocationReceiver for some processing, but HOW?
}
public void stopTracking(Context context)
{
context.unregisterReceiver(locationReceiver);
}
}
MyLocationReceiver.java
public class MyLocationReceiver extends BroadcastReceiver {
public void onReceive(final Context context, Intent intent) {
if ((intent.getAction() != null) &&
(intent.getAction().equals("com.app.android.tracker.LOCATION_READY")))
{
//GET THAT EXTRA INFO FROM LocationLibrary class and process it here
}
}
}
请帮帮我。日Thnx!
答案 0 :(得分:1)
为什么不向MyLocationReceiver添加构造函数?
public class MyLocationReceiver extends BroadcastReceiver {
String info = "";
public MyLocationReceiver(String extraInfo)
{
this.info = extraInfo;
}
........
public void onReceive(final Context context, Intent intent) {
if ((intent.getAction() != null) &&
(intent.getAction().equals("com.app.android.tracker.LOCATION_READY")))
{
if (info.contains("Hi"))
//do some stuff
}
}
}
你会像这样实例化它:
myLocationReceiver = new MyLocationReceiver(new String("Hello!"));