How to find my current location (latitude + longitude) in every 5 second in Android?

后端 未结 4 1681
无人共我
无人共我 2021-01-26 01:45

I tried many code snippets but all the example takes too much time to provide latitude and longitude .

I want to get current latitude in every 5 seconds .

4条回答
  •  长情又很酷
    2021-01-26 01:58

    You can create service that broadcasts your latitude and longitude in every 5 seconds using LocationManager.

    public class MyLocationService extends Service {
    
    private LocationManager locationManager;
    private LocationListener locationListener;
    
    public final String APP_BROADCAST_RECEIVER = "LatLonReciever"; // You should define it somewhere else as a static. e.g within Const class 
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (locationListener == null ) {
            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    
    
            locationListener = new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    locationIsChanged(location);
                }
    
                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {
                }
    
                @Override
                public void onProviderEnabled(String provider) {
                }
    
                @Override
                public void onProviderDisabled(String provider) {
                }
            };
        }
    
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 5000, locationListener); // here 5000 is 5 seconds
        return START_STICKY;
    }
    
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    private void locationIsChanged(Location location){
        Intent intent = new Intent(APP_BROADCAST_RECEIVER); 
        intent.putExtra("lat", location.getLatitude());
        intent.putExtra("lon", location.getLongitude());
        sendBroadcast(intent);
        }
    }
    

    Also, don't foret to register the reciever where you want to recieve the results:

    public final String APP_BROADCAST_RECEIVER = "LatLonReciever"; 
    
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    // Here you do what you want with recieved intent that contains lat and lon
                }
            };
    
    IntentFilter intentFilter = new IntentFilter(APP_BROADCAST_RECEIVER);
    registerReceiver(broadcastReceiver, intentFilter);
    

提交回复
热议问题