在我正在开发的Android应用程序中。
- 我想获取用户位置,并在每5秒发布一次请求时将其发送到服务器;即使应用程序在后台运行
- 我想发送包括方位在内的所有地理位置信息
- 我需要一个方法来调用以启动发送作业,以及一个方法以停止发送作业
- 计划是只发送新数据,因为旧数据已经发送。避免将数据一次全部重载到服务器
您必须编写服务,并从智能定位库中获取您使用的位置
public class StatusUserServices extends Service {
public static final String BROADCAST_ACTION = "reporter";
private static final int TWO_SECONDS = 1000 * 2;
public LocationManager locationManager;
public MyLocationListener listener;
public Location previousBestLocation = null;
Intent intent;
int counter = 0;
protected Handler handler;
double lat,longi;
private final LocalBinder mBinder = new LocalBinder();
boolean speed;
public class LocalBinder extends Binder {
public StatusUserServices getService() {
return StatusUserServices .this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
listener = new MyLocationListener();
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
if (locationManager != null){
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if( !isGPSEnabled && !isNetworkEnabled) {
showGPSDisabledAlertToUser();
} else {
if(isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2*1000, 100, listener);
} else if(isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,2*1000,100, listener);
}
}
}
return START_STICKY;
}
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
return true;
}
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
if (isSignificantlyNewer) {
return true;
} else if (isSignificantlyOlder) {
return false;
}
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 3000;
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
}
return false;
}
private void showGPSDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage(getResources().getString(R.string.ActivateGPSQuestion))
.setCancelable(false)
.setPositiveButton(R.string.GoToTheSettingsPage,
(dialog, id) -> {
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
});
alertDialogBuilder.setNegativeButton(R.string.cancel,
(dialog, id) -> dialog.cancel());
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.v("STOP_SERVICE", "DONE");
if (locationManager != null) {
try {
locationManager.removeUpdates(listener);
} catch (Exception ex) {
Log.i("******", "fail to remove location listners, ignore", ex);
}
}
}
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(final Location loc)
{
if(isBetterLocation(loc, previousBestLocation)) {
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
SimpleDateFormat time= new SimpleDateFormat("HH:mm:ss", Locale.US);
if(loc.getLatitude() == 0.0 && loc.getLongitude() == 0.0){
SmartLocation.with(getApplicationContext()).location()
.start(location -> {
lat = location.getLatitude();
longi = location.getLongitude();
speed = location.hasSpeed();
});
}else{
lat = loc.getLatitude();
longi = loc.getLongitude();
speed = loc.hasSpeed();
}
String times = time.format(new Date());
String dates = date.format(new Date());
intent.putExtra("Latitude", lat);
intent.putExtra("Longitude", longi);
intent.putExtra("Speed", speed);
intent.putExtra("Time", times);
intent.putExtra("Date", dates);
intent.setAction(BROADCAST_ACTION);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider)
{
}
}
}