2017-09-08 57 views
2

android.location.LocationListener的位置监听器的onLocationChanged()函数中的问题。在Android中,如何连续接收GPS位置?

在请求LocationManager的requestLocationUpdates之后的代码如下,onLocationChanged以不均匀的间隔被调用,即我设置了1秒的时间段,但是我没有在每秒之后收到位置改变。

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

@SuppressWarnings("MissingPermission") 
public class SimplePositionProvider extends PositionProvider implements LocationListener { 

public SimplePositionProvider(Context context, PositionListener listener) { 
super(context, listener); 

Log.i("SimplePositionProvider", "start"); 
if (!type.equals(LocationManager.NETWORK_PROVIDER)) { 
type = LocationManager.GPS_PROVIDER; 
} 

} 

public void startUpdates() { 
Log.i("startUpdates", "start"); 
try { 
Log.i("requestLocationUpdates", "start"); 
Log.i("TYPE", type); 
locationManager.requestLocationUpdates(type, period, 0, this); 
} catch (Exception e) { 
e.printStackTrace(); 
Log.e(TAG, "error"); 
} 
} 

public void stopUpdates() { 
Log.i("stopUpdates", "start"); 
locationManager.removeUpdates(this); 
} 

@Override 
public void onLocationChanged(Location location) { 
Log.i("onLocationChanged", "start"); 
updateLocation(location); 
} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 
Log.i("onStatusChanged", "start"); 
} 

@Override 
public void onProviderEnabled(String provider) { 
Log.i("onProviderEnabled", "start"); 
} 

@Override 
public void onProviderDisabled(String provider) { 
Log.i("onProviderDisabled", "start"); 
} 

} 
+0

创建位置服务来获得位置continiusly –

回答

0
public class CustomLocationService extends Service implements LocationListener { 


private static final Location TODO = null; 
boolean isGPSEnabled = false; 
boolean isNetworkEnabled = false; 
public boolean canGetLocation = false; 

Location location; 

double latitude; 
double longitude; 

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; 
private static final long MIN_TIME_BW_UPDATES = 10000 * 60 * 1; 
private CommonSharedPreference commonSharedPreference = new CommonSharedPreference(); 

protected LocationManager locationManager; 
private long time; 
Context context; 


@Override 
public void onCreate() { 
    super.onCreate(); 
    context = this; 

    time = MIN_TIME_BW_UPDATES; 
    getLocation(); 

} 

@Override 
public void onStart(Intent intent, int startId) { 
    getLocation(); 
} 

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

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

     isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

     isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     if (!isGPSEnabled && !isNetworkEnabled) { 
      // no network provider is enabled 

     } else { 
      this.canGetLocation = true; 
      // First get location from Network Provider 
      if (isNetworkEnabled) { 
       if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
        return TODO; 
       } 
       locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
       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); 
        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; 
} 


public void stopUsingGPS() { 
    if(locationManager != null) { 
     locationManager.removeUpdates(GPSTracker.this); 
    } 
} 

public double getLatitude() { 
    if(location != null) { 
     latitude = location.getLatitude(); 
    } 
    return latitude; 
} 

public double getLongitude() { 
    if(location != null) { 
     longitude = location.getLongitude(); 
    } 

    return longitude; 
} 

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


@Override 
public void onLocationChanged(Location arg0) { 
    // TODO Auto-generated method stub 
} 

@Override 
public void onProviderDisabled(String arg0) { 
    // TODO Auto-generated method stub 

} 

@Override 
public void onProviderEnabled(String arg0) { 
    // TODO Auto-generated method stub 

} 

@Override 
public void onStatusChanged(String arg0, int arg1, Bundle arg2) { 
    // TODO Auto-generated method stub 

} 

@Override 
public IBinder onBind(Intent intent) { 
    // TODO Auto-generated method stub 
    return null; 
} 

}

+0

嗨,首先感谢您的代码,但我的问题不是没有收到地址,而是始终没有收到地址!您正在使用locationManager的最后一个已知位置,我们被要求不要使用,我们希望当前位置每隔30秒 –

+0

一旦服务是明星,然后onLocationChanged会给你在给定时间间隔的当前位置 –

0

According to the documentation,您使用的是period说法是位置更新之间的最小间隔。如果您希望位置与位置系统更新一样快,请将period设置为零。

+0

谢谢,但问题我们所面临的是,位置接收不稳定,经过一段时间间隔后会断开。在仿真器中不会连续接收位置问题。 –

+0

@BonnySebastian你应该重新提出你的问题。这不是它似乎要问的。 – Haem

0

使用这个类..

public class MyLocationService extends Service { 
    private static final String TAG = "MyLocationService"; 
    private LocationManager mLocationManager = null; 
    private static final int LOCATION_INTERVAL = 1000 * 30;; 
    private static final float LOCATION_DISTANCE = 0f; 


    private final IBinder serviceBinder = new MyLocationService.RunServiceBinder(); 

    public MyLocationService() { 
    } 

    LocationListener[] mLocationListeners = new LocationListener[]{ 
      new LocationListener(LocationManager.GPS_PROVIDER), 

    }; 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     Log.e(TAG, "onStartCommand"); 
     super.onStartCommand(intent, flags, startId); 
     return START_STICKY; 
    } 

    @Override 
    public void onCreate() { 

     Log.e(TAG, "onCreate"); 

     initializeLocationManager(); 

    /* try { 
      mLocationManager.requestLocationUpdates(
        LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, 
        mLocationListeners[1]); 
     } catch (java.lang.SecurityException ex) { 
      Log.i(TAG, "fail to request location update, ignore", ex); 
     } catch (IllegalArgumentException ex) { 
      Log.d(TAG, "network provider does not exist, " + ex.getMessage()); 
     }*/ 



     try { 
      mLocationManager.requestLocationUpdates(
        LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, 
        mLocationListeners[0]); 
     } catch (java.lang.SecurityException ex) { 
      Log.i(TAG, "fail to request location update, ignore", ex); 
     } catch (IllegalArgumentException ex) { 
      Log.d(TAG, "gps provider does not exist " + ex.getMessage()); 
     } 
    } 

    @Override 
    public void onDestroy() { 
     Log.e(TAG, "onDestroy"); 
     super.onDestroy(); 
     if (mLocationManager != null) { 
      for (int i = 0; i < mLocationListeners.length; i++) { 
       try { 
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
         return; 
        } 
        mLocationManager.removeUpdates(mLocationListeners[i]); 
       } catch (Exception ex) { 
        Log.i(TAG, "fail to remove location listener, ignore", ex); 
       } 
      } 
     } 
    } 

    private void removeUpdate(){ 
     if (mLocationManager != null) { 
      for (int i = 0; i < mLocationListeners.length; i++) { 
       try { 
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
         return; 
        } 
        mLocationManager.removeUpdates(mLocationListeners[i]); 
       } catch (Exception ex) { 
        Log.i(TAG, "fail to remove location listener, ignore", ex); 
       } 
      } 
     } 
    } 

    private void initializeLocationManager() { 
     Log.e(TAG, "initializeLocationManager - LOCATION_INTERVAL: " + LOCATION_INTERVAL + " LOCATION_DISTANCE: " + LOCATION_DISTANCE); 
     if (mLocationManager == null) { 
      mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); 
     } 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     // TODO: Return the communication channel to the service. 
     // throw new UnsupportedOperationException("Not yet implemented"); 
     return null; 
    } 

    public class RunServiceBinder extends Binder { 
     public MyLocationService getService() { 
      return MyLocationService.this; 
     } 
    } 


    private class LocationListener implements android.location.LocationListener { 
     Location mLastLocation; 

     public LocationListener(String provider) { 
      Log.e(TAG, "LocationListener " + provider); 
      // Toast.makeText(MyLocationService.this, ""+provider, Toast.LENGTH_SHORT).show(); 
      mLastLocation = new Location(provider); 
     } 

     @Override 
     public void onLocationChanged(Location location) { 
      Log.e(TAG, "onLocationChanged: " + location); 
      // Toast.makeText(MyLocationService.this, ""+"checked", Toast.LENGTH_SHORT).show(); 
      mLastLocation.set(location); 

     } 

     @Override 
     public void onProviderDisabled(String provider) { 
      Log.e(TAG, "onProviderDisabled: " + provider); 
     } 

     @Override 
     public void onProviderEnabled(String provider) { 
      Log.e(TAG, "onProviderEnabled: " + provider); 
     } 

     @Override 
     public void onStatusChanged(String provider, int status, Bundle extras) { 
      Log.e(TAG, "onStatusChanged: " + provider); 
     } 
    } 


} 
+0

在放在我的玻璃桌上时需要时间来启动和停止(与我的上面的代码相同) –

0

按照tutorial,你应该使用FusedLocationProviderClient请求位置更新。如果内存提供服务,那么该解决方案会按指定的时间间隔发送更新。您可以拨打LocationServices.getFusedLocationProviderClient(Context context)来获得FusedLocationProviderClient

您可以在LocationRequest请求到期时间与setExpirationDuration,然后使用类似这样的代码,当你开始更新,重新开始各自到期后:

Handler handler = new Handler(Looper.myLooper()); 
handler.postDelayed(new Runnable() { 
    @Override 
    public void run() { 
     if (expectingLocationUpdates) { 
     restartLocationUpdates(); 
     } 
    } 
}, EXPIRATION_DURATION);