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 
     } 
    } 
} 

請幫助我。日Thnx!

回答

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!")); 
+0

糟糕!那真是無賴。當然,一個建設者將會完成這項工作。我怎麼錯過了。謝謝傑克:)! – 2012-04-12 14:11:43