0

我想动态控制位置跟踪(注册/注销位置广播接收器)。这就是我打算这样做的方式。我有两个问题:

  1. 下面的实现中有什么错误,因为所有这些概念对我来说仍然非常理论化,因为我对 android/java 开发人员非常陌生。仍在构建概念!

  2. 如何将一些 EXTRA_INFO 从我的位置库类传递给位置接收器。

执行:

我有一个库类 LocationLibrary.java,它由两种方法组成。他们就像名字所暗示的那样。位置跟踪应该在我调用 startTracking() 时开始。请注意需要传递给 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
        }
    }
}

请帮帮我。谢谢!

4

1 回答 1

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!"));
于 2012-04-12T13:41:12.143 回答