GPSTracker Class 不工作
GPSTracker Class not working
我曾尝试使用在我的应用程序中在线找到的 GPSTracker class,并且我之前可以使用它,但现在似乎莫名其妙地不起作用。
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"));
}
不幸的是,尽管我的 phone 上启用了 Wi-Fi 和 GPS,但我的标记不断出现在 (0,0)。我能想到的唯一改变的是电池,但我认为它不会受到影响超过 20%。使用 Toasts 显示 isGPSEnabled 显示为真,而 isNetworkEnabled 显示为假(也不知道为什么会这样,因为 Wi-Fi 工作正常)。
我有几个相关问题试图帮助我理解整个机制。当 locationManager.requestLocationUpdates() 被调用时,这些更新是否继续在后台发生?例如,当我在 MapActivity 中创建了一个 GPSTracker class 的实例时,每次我想获取当前位置时是否需要创建另一个 class 的实例?变量'gps'中保存的对象实例中的纬度和经度值会发生变化吗?如果是这种情况,我可以在每次移动 10 米时调用 gps.getLatitude(),它会自动更改纬度和经度的值。或者,由于 GPSTracker 实现了 LocationListener,我是否需要在 onLocationChanged() 方法中添加代码来请求位置更新?我只是对整个情况有点困惑,所以任何帮助将不胜感激。谢谢。
首先你并没有真正开始Android Service just by creating a new instance! Android Services can be started either by calling startService()
or bindService()
. Also don't forget to finish the Service
by calling stopSelf()
(or unbindService()
) after the work is done. I recommend to implement the interfaces GoogleApiClient.ConnectionCallbacks and GoogleApiClient.OnConnectionFailedListener in combination with the new 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'
//...
}
我曾尝试使用在我的应用程序中在线找到的 GPSTracker class,并且我之前可以使用它,但现在似乎莫名其妙地不起作用。
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"));
}
不幸的是,尽管我的 phone 上启用了 Wi-Fi 和 GPS,但我的标记不断出现在 (0,0)。我能想到的唯一改变的是电池,但我认为它不会受到影响超过 20%。使用 Toasts 显示 isGPSEnabled 显示为真,而 isNetworkEnabled 显示为假(也不知道为什么会这样,因为 Wi-Fi 工作正常)。
我有几个相关问题试图帮助我理解整个机制。当 locationManager.requestLocationUpdates() 被调用时,这些更新是否继续在后台发生?例如,当我在 MapActivity 中创建了一个 GPSTracker class 的实例时,每次我想获取当前位置时是否需要创建另一个 class 的实例?变量'gps'中保存的对象实例中的纬度和经度值会发生变化吗?如果是这种情况,我可以在每次移动 10 米时调用 gps.getLatitude(),它会自动更改纬度和经度的值。或者,由于 GPSTracker 实现了 LocationListener,我是否需要在 onLocationChanged() 方法中添加代码来请求位置更新?我只是对整个情况有点困惑,所以任何帮助将不胜感激。谢谢。
首先你并没有真正开始Android Service just by creating a new instance! Android Services can be started either by calling startService()
or bindService()
. Also don't forget to finish the Service
by calling stopSelf()
(or unbindService()
) after the work is done. I recommend to implement the interfaces GoogleApiClient.ConnectionCallbacks and GoogleApiClient.OnConnectionFailedListener in combination with the new 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'
//...
}