获得最佳和最有效的位置更新

时间:2016-01-06 14:21:47

标签: android location locationmanager

在我的应用程序中,我想在一定时间后更新服务器上的用户位置并改变距离。为此我创建了一个工作正常的服务但唯一的问题是在设置位置它显示高电池使用。

这是我的服务类

public class LocationService extends Service {
private static final int TWO_MINUTES = 1000 * 60 * 2;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
public LocationManager locationManager;
public MyLocationListener listener;
public Location previousBestLocation = null;
PrefStore store;


Intent intent;
int counter = 0;

@Override
public void onCreate() {
    super.onCreate();
    intent = new Intent(Constants.BROADCAST_ACTION);
    store = new PrefStore(this);
}

@Override
public void onStart(Intent intent, int startId) {
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    listener = new MyLocationListener();

    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, TWO_MINUTES, MIN_DISTANCE_FOR_UPDATE, listener);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, TWO_MINUTES, MIN_DISTANCE_FOR_UPDATE, listener);

}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

protected boolean isBetterLocation(Location location, Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return true;
    }

    // Check whether the new location fix is newer or older
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;

    // If it's been more than two minutes since the current location, use the new location
    // because the user has likely moved
    if (isSignificantlyNewer) {
        return true;
        // If the new location is more than two minutes older, it must be worse
    } else if (isSignificantlyOlder) {
        return false;
    }

    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

    // Check if the old and new location are from the same provider
    boolean isFromSameProvider = isSameProvider(location.getProvider(),
            currentBestLocation.getProvider());

    // Determine location quality using a combination of timeliness and accuracy
    if (isMoreAccurate) {
        return true;
    } else if (isNewer && !isLessAccurate) {
        return true;
    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
        return true;
    }
    return false;
}

/**
 * Checks whether two providers are the same
 */
private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) {
        return provider2 == null;
    }
    return provider1.equals(provider2);
}

@Override
public void onDestroy() {
    // handler.removeCallbacks(sendUpdatesToUI);
    super.onDestroy();
    Log.v("STOP_SERVICE", "DONE");
    locationManager.removeUpdates(listener);
}

public static Thread performOnBackgroundThread(final Runnable runnable) {
    final Thread t = new Thread() {
        @Override
        public void run() {
            try {
                runnable.run();
            } finally {

            }
        }
    };
    t.start();
    return t;
}


public class MyLocationListener implements LocationListener {

    public void onLocationChanged(final Location loc) {
        Log.i("//////////", "Location changed");
        if (isBetterLocation(loc, previousBestLocation)) {
            store.setString("Lat", loc.getLatitude() + "");
            store.setString("Long", loc.getLongitude() + "");
            loc.getLongitude();
            previousBestLocation = loc;
            if (store != null) {
                if (store.getInt(Constants.IS_APPLICATION_VISIBLE, 0) == 1) {   //App is running send update through application
                    intent.putExtra("Latitude", loc.getLatitude());
                    intent.putExtra("Longitude", loc.getLongitude());
                    sendBroadcast(intent);
                } else {
                    if (store.getString(Constants.gcmToken) != null) {
                        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
                        String deviceId = Settings.Secure.getString(getContentResolver(),
                                Settings.Secure.ANDROID_ID);
                        Log.d("", "Device_id-" + deviceId);
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("device_token", store.getString(Constants.gcmToken));
                        params.put("device_id", deviceId);
                        params.put("device_os", "android");
                        params.put("client", Constants.clientId);
                        params.put("language", store.getInt("Language", 0) + "");
                        params.put("long", loc.getLongitude() + "");
                        params.put("lat", loc.getLatitude() + "");
                        CustomRequest jsObjRequest = new CustomRequest(Request.Method.POST, Constants.urlUpdateLocation, params, new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject jsonObject) {
                                try {
                                    if (jsonObject.getInt("success") == 1) {

                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {

                            }
                        });
                        requestQueue.add(jsObjRequest);
                    }
                }
            }
        }
    }

    public void onProviderDisabled(String provider) {
    }


    public void onProviderEnabled(String provider) {
    }


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

}

我做错了什么?

提前完成

0 个答案:

没有答案