2013-12-19 29 views
0

我正在開發一個原型示例應用程序。 我有GPS.java文件中實現LocationListener的GPS類。 我有一個MainActivity.java文件,我有一個GPS實例,我想將位置更新到文本字段中。我已經看到很多例子,其中活動本身實現了OnLocationChanged,使得它能夠訪問TextView字段。但是,我想要將文件外部化。我怎樣才能做到這一點?我是Java的新手。在javascript/AS3中,我會廣播一個事件並讓偵聽器識別並獲取值。我不完全確定我能做到這一點。如何在MainActivity.java中偵聽GPS更新並接收值?

回答

1

將參考傳遞給您的GPS類中的上下文(或更好的實現它在Service)。接下來,註冊在一些自定義操作您的MainActivity類別的廣播接收器,例如com.mypackage.ACTION_RECEIVE_LOCATION.

在您的GPS類的onLocationChanged(Location location)方法,當您收到適合您的目的,意圖作爲一個額外的廣播它的位置。

Intent toBroadcast = new Intent(com.mypackage.ACTION_RECEIVE_LOCATION); 
toBroadcast.putExtra(MainActivity.EXTRA_LOCATION,location); 
context.sendBroadcast(toBroadcast); 

在您的MainActivity的註冊接收器中,接收廣播並處理該位置。

public class MainActivity extends Activity { 

public static final String EXTRA_LOCATION = "EXTRA_LOCATION"; 

    private class LocationUpdateReceiver extends BroadcastReceiver { 

     /** 
     * Receives broadcast from GPS class/service. 
     */ 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      Bundle extras = intent.getExtras(); 

      Location location = (Location) extras.get(MainActivity.EXTRA_LOCATION); 

       //DO SOMETHING 
       ... 

    } 
} 
+0

這看起來像最簡單的實現,它的工作..感謝很多人。 – jagzviruz

1

在您的GPS類中創建一個interface,然後在您的主要活動中設置偵聽器以偵聽回調。那麼當您的位置更改觸發與新位置的回調。

它會是這個樣子

GPS gps = new GPS(); 
gps.setLocationListener(new OnMyGpsLocationChanged(){ 
    @Override 
    public void myLocationChanged(Location location){ 
     //use the new location here 
    } 
)}; 

的GPS類將有這樣的事情

public interface OnMyGpsLocationChanged{ 
    public void myLocationChanged(Location location); 
} 

那麼當你的位置改變了你只想做

listener.myLocationChanged(location); 

在onLocationChanged爲您的LocationManager

+0

這很適合爲好。 – jagzviruz

0

您可以爲前做同樣這裏還有:

在您的活動創建一個廣播接收器如下:

public class MyReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
    <YourTextView>.setText(intent.getStringExtra("lat")); 
    } 
} 

中的onCreate一些自定義的意向登記活動的這個接收器過濾器:

MyReceiver mr=new MyReceiver(); 
this.registerReceiver(mr,new IntentFilter("my-event")); 

in onPause:

this.unregisterReceiver(mr); 

現在在onLocationChanged回調您的GPS類只需發送一個廣播:

public void onLocationChanged(Location location) { 
    Intent intent = new Intent(); 
    intent.putExtra("lat",location.getLatitude()); 
    intent.setAction("my-event"); 
    sendBroadcast(intent); 
} 
相關問題