java - 将 Android 应用程序中的 GPS 功能外包给一个单独的类

标签 java android gps location

我关注了http://developer.android.com/guide/topics/location/obtaining-user-location.html当处于 onCreate 方法的 Activity 中时,这工作得很好。

然后我想将此功能外包到一个名为 LocationHelper 的单独类中。

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class LocationHelper {

public Context mContext;
public Location loc;

public LocationHelper (Context mContext){
    this.mContext = mContext;

    // Acquire a reference to the system Location Manager
    LocationManager locationManager = (LocationManager)     mContext.getSystemService(Context.LOCATION_SERVICE);

    // Define a listener that responds to location updates
    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
          // Called when a new location is found by the network location provider.
            setLocation(location);
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {}

        public void onProviderEnabled(String provider) {}

        public void onProviderDisabled(String provider) {}
      };

    // Register the listener with the Location Manager to receive location updates
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}

public void setLocation(Location location) {
    this.loc = location;
}

public Location getLocation() {
    return this.loc;
}
}

在 Activity 中我这样做;基本上我想从我的助手类中提取(出于测试目的!)GPS 坐标并显示它。问题是,该位置始终为空。

public class GraffitiWall extends Activity {

private TextView tv;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    tv = new TextView(this);

    LocationHelper gpsie = new LocationHelper(this);
    while (true){
        makeUseOfNewLocation(gpsie.getLocation());
    }
}

public void makeUseOfNewLocation(Location loc){
    if (loc == null){return;}
    tv.setText("" + loc.getLatitude());
    setContentView(tv);
}
}

我错过了什么并且做错了什么?

最佳答案

在 onCreate 方法中放置无限循环是一个主意。您的问题很可能是因为 onCreate 永远不会完成并将控制权传递回操作系统而引起的。如果这导致强制关闭错误,我不会感到惊讶。

也许您需要做的是创建一项服务来监控您的位置并从那里更新您的 Activity 。

关于java - 将 Android 应用程序中的 GPS 功能外包给一个单独的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5662746/

相关文章:

java - 添加重复项时,如何更新 TableView 中的行(而不是添加新行)? [JavaFX]

java - 如何使用 Java 查找剩余的磁盘空间?

java - 在尝试使用 GPS 之前如何检查它是否已启用

java - 在 Netbeans 中找不到符号 GWTServiceAsync

java - 代码不在 Debug模式下执行,需要源代码

android - 如何检查设备是否支持用户的联系人?

Android 将用户的选择保存为收藏夹

Android Gradle 模块依赖

android - GPS轨迹,计算高差

ios - 如何避免 XCode 每次运行时都重置我的 iPhone 上的位置