如何在MainActivity.java中侦听GPS更新并接收值?

问题描述:

我正在开发一个原型示例应用程序。 我有GPS.java文件中实现LocationListener的GPS类。 我有一个MainActivity.java文件,我有一个GPS实例,我想将位置更新到文本字段中。我已经看到很多例子,其中活动本身实现了OnLocationChanged,使得它能够访问TextView字段。但是,我想要将文件外部化。我怎样才能做到这一点?我是Java的新手。在javascript/AS3中,我会广播一个事件并让侦听器识别并获取值。我不完全确定我能做到这一点。如何在MainActivity.java中侦听GPS更新并接收值?

将参考传递给您的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

在您的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

在活动中使用具有侦听器的位置管理器。其在此活动中的自动更新。

requestLocationUpdates(String,long,float,LocationListener);

http://developer.android.com/reference/android/location/LocationListener.html

我希望它会工作。

您可以为前做同样这里还有:

在您的活动创建一个广播接收器如下:

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