GPSTracker类无效

时间:2015-06-11 04:29:05

标签: android gps

我曾尝试使用我在我的应用程序中在网上找到的GPSTracker类,并且我让它早些时候工作,但现在似乎莫名其妙地无法工作。

public class GPSTracker extends Service implements LocationListener {

private static final String TAG = "GPSTracker";
private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location = null; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 30 * 1; //

// Declaring a Location Manager
protected LocationManager locationManager;
TextView tv;


public GPSTracker(Context c){
    this.mContext = c;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {

        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network Enabled");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener Calling this function will stop using GPS in your
 * app
 * */
public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
    }
}

/**
 * Function to get latitude
 * */
public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

 public boolean canGetLocation() {
    return this.canGetLocation;
}

在我的MainActivity中,我初始化了一个GPSTracker gps变量,并在我的onCreate()方法中创建了一个新实例:

gps = new GPSTracker(MapActivity.this);

现在使用它的代码是:

@Override
public void onMapReady(GoogleMap googleMap) {
    LatLng point = new LatLng(gps.getLatitude(),gps.getLongitude());
    pointList.add(point);
    googleMap.addMarker(new MarkerOptions().position(point).title("Home"));

}

不幸的是,尽管我手机上启用了Wi-Fi和GPS,但我的标记仍然会出现在(0,0)。我能想到的唯一改变的是电池,但我认为它不受影响的水平> 20%。使用Toasts显示isGPSEnabled显示为true,而isNetworkEnabled显示为false(不确定为什么会这样,因为Wi-Fi工作正常)。

我有一些相关的问题试图帮助我理解整个机制。调用locationManager.requestLocationUpdates()时,这些更新是否继续在后台进行?例如,当我在MapActivity中创建GPSTracker类的实例时,每次想要获取当前位置时,是否需要创建该类的另一个实例?纬度和经度的值是否会在变量'gps'中保存的对象的实例中发生变化?如果是这种情况,我可以在每次移动10米时调用gps.getLatitude(),它会自动更改纬度和经度值。或者,由于GPSTracker实现了LocationListener,我是否需要在onLocationChanged()方法中添加代码以请求位置更新?我对整个情况感到有些困惑,所以任何帮助都会非常感激。谢谢。

1 个答案:

答案 0 :(得分:0)

首先,您只需创建一个新实例即可真正启动Android Service!可以通过致电startService()bindService()来启动Android服务。在工作完成后,也不要忘记通过调用Service(或stopSelf())来完成unbindService()。我建议将接口GoogleApiClient.ConnectionCallbacks GoogleApiClient.OnConnectionFailedListener与新FusedLocationProviderApi结合使用。

这可以帮到你:

LocationService.java

    import android.app.Service;
    import android.content.Context;
    import android.content.Intent;
    import android.location.Location;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.util.Log;

    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.GooglePlayServicesUtil;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.location.LocationListener;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationServices;

    /**
     * Created by momo on 11.06.2015.
     */
    public class LocationService extends Service implements
            GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener,
            LocationListener {

    private GoogleApiClient mGoogleApiClient;
    private final String TAG = LocationService.class.getSimpleName();

    private Intent intent;

    public LocationService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate()");
        mGoogleApiClient = new GoogleApiClient.Builder(this) // com.google.android.gms.location.LocationServices
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand() " + intent);
        this.intent = intent;

        /**
         * com.google.android.gms.common.GooglePlayServicesUtil
         */
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode == ConnectionResult.SUCCESS) {
            Log.d(TAG, "handleActionGPS(): Connect to GooglePlayServices");
            mGoogleApiClient.connect();
        } else {
            Log.e(TAG, "GooglePlayService is not available");
            stopSelf();
        }

        return (START_REDELIVER_INTENT);
    }

    /**
     * com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks
     */
    @Override
    public void onConnected(Bundle bundle) {
        Log.d(TAG, "onConnected: Connected");
        LocationRequest mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(10000); // nterval 10 seconds
        mLocationRequest.setNumUpdates(1); // number of location updates
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
    }

    // com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks
    @Override
    public void onConnectionSuspended(int i) 
    {
        Log.i(TAG, "GoogleApiClient connection has been suspend");
        stopSelf();
    }

    /**
     * com.google.android.gms.location.LocationListener
     *
     */
    @Override
    public void onLocationChanged(Location location) {
        Log.d(TAG, "onLocationChanged()");

        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();

        stopSelf();
    }


    // com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.e(TAG, "GoogleApiClient connection has failed: " + connectionResult.getErrorCode());
        stopSelf();
    }

    boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return netInfo != null && netInfo.isConnectedOrConnecting();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy()");
    }

}

的build.gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.google.android.gms:play-services:7.5.0'
    //...
}