How do I get the current GPS location programmatically in Android?

前端 未结 22 2624
梦谈多话
梦谈多话 2020-11-21 04:42

I need to get my current location using GPS programmatically. How can i achieve it?

22条回答
  •  庸人自扰
    2020-11-21 04:57

    LocationManager is a class that provides in-build methods to get last know location

    STEP 1 :Create a LocationManager Object as below

    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    STEP 2 : Add Criteria

    *Criteria is use for setting accuracy*
    
    Criteria criteria = new Criteria();
    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    
    if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB) {
    
        criteria.setSpeedAccuracy(Criteria.ACCURACY_HIGH);
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(true);
        criteria.setBearingRequired(true);
        criteria.setSpeedRequired(true);
    
    }
    

    STEP 3 :GET Avaliable Provider

    Threre are two types of provider GPS and network

     String provider = locationManager.getBestProvider(criteria, true);
    

    STEP 4: Get Last Know Location

    Location location = locationManager.getLastKnownLocation(provider);
    

    STEP 5: Get Latitude and Longitude

    If location object is null then dont try to call below methods

    getLatitude and getLongitude is methods which returns double values

提交回复
热议问题