Get current location during app launch

前端 未结 4 1579
再見小時候
再見小時候 2020-12-16 04:29

Good Day! I am working on an android app which monitors user location. I am using LocationManager to get users location, using the following method

public vo         


        
4条回答
  •  青春惊慌失措
    2020-12-16 04:45

    Try This Code.Hope It will work

    import android.app.Activity;
    import android.content.Context;
    import android.location.Criteria;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.Button;
    import android.widget.Toast;
    import com.google.android.maps.MapController;
    import com.google.android.maps.MapView;
    
    public class MainActivity extends Activity implements LocationListener {
    
    private LocationManager locationManager;
    private String provider;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);
        if (location != null) {
            System.out.println("Provider " + provider + " has been selected.");
            onLocationChanged(location);
          } else {
            System.out.println("Location not avilable");
          }
    
    }
    
    protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(provider, 400, 1, (LocationListener) this);
      }
    
      /* Remove the locationlistener updates when Activity is paused */
      @Override
      protected void onPause() {
        super.onPause();
        locationManager.removeUpdates((LocationListener) this);
      }
    public void onLocationChanged(Location location) {
        double lat = (double) (location.getLatitude());
        double lng = (double) (location.getLongitude());
        Toast.makeText(getApplicationContext(), lat+"----"+lng,Toast.LENGTH_LONG).show();
        Log.i("Latitude------------", "Lattitude:" +lat);
        Log.i("Longitude-------------", "Longitude:" +lng);
      }
    
    @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
    
    }
        }
    

    Must add required permission

提交回复
热议问题