Example usage for android.location LocationManager getBestProvider

List of usage examples for android.location LocationManager getBestProvider

Introduction

In this page you can find the example usage for android.location LocationManager getBestProvider.

Prototype

public String getBestProvider(Criteria criteria, boolean enabledOnly) 

Source Link

Document

Returns the name of the provider that best meets the given criteria.

Usage

From source file:jp.co.tweetmap.Fragment0.java

/**
 * This is where we can add markers or lines, add listeners or move the camera. In this case, we
 * just add a marker near Africa./*from  w ww.ja va  2s .co m*/
 * <p/>
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 */
private void setUpMap() {
    if (LogUtil.isDebug())
        Log.e(TAG, "### mapInit() ###");
    // LocationManager
    LocationManager locationManager = (LocationManager) this.getActivity().getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);

    double latitude = MapUtil.TOKYO_STATION_LATITUDE;
    double longitude = MapUtil.TOKYO_STATION_LONGITUDE;

    if (null != locationManager) {
        String bestProv = locationManager.getBestProvider(new Criteria(), true);

        // Get location information from GPS
        Location myLocate = locationManager.getLastKnownLocation(bestProv);
        if (null == myLocate) {
            myLocate = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        }
        if (null == myLocate) {
            myLocate = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }

        if (null != myLocate) {
            latitude = myLocate.getLatitude();
            longitude = myLocate.getLongitude();
        }
    }

    CameraPosition camerapos = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(15.0f)
            .build();
    // Move camera position
    mMap.moveCamera(CameraUpdateFactory.newCameraPosition(camerapos));
    // Set current position
    mCenterPosition = camerapos;

    getNearestStation();
}

From source file:com.appnexus.opensdk.AdRequest.java

private AdRequest(AdRequester adRequester, int httpRetriesLeft, int blankRetriesLeft) {
    owner = adRequester.getOwner();/*  w  ww.  j a v  a2s. c  o m*/
    this.requester = adRequester;
    this.httpRetriesLeft = httpRetriesLeft;
    this.blankRetriesLeft = blankRetriesLeft;
    this.placementId = owner.getPlacementID();
    context = owner.getContext();
    String aid = android.provider.Settings.Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);

    // Do we have access to location?
    if (context.checkCallingOrSelfPermission(
            "android.permission.ACCESS_FINE_LOCATION") == PackageManager.PERMISSION_GRANTED
            || context.checkCallingOrSelfPermission(
                    "android.permission.ACCESS_COARSE_LOCATION") == PackageManager.PERMISSION_GRANTED) {
        // Get lat, long from any GPS information that might be currently
        // available
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Location lastLocation = lm.getLastKnownLocation(lm.getBestProvider(new Criteria(), false));
        if (lastLocation != null) {
            lat = "" + lastLocation.getLatitude();
            lon = "" + lastLocation.getLongitude();
            locDataAge = "" + (System.currentTimeMillis() - lastLocation.getTime());
            locDataPrecision = "" + lastLocation.getAccuracy();
        }
    } else {
        Clog.w(Clog.baseLogTag, Clog.getString(R.string.permissions_missing_location));
    }

    // Do we have permission ACCESS_NETWORK_STATE?
    if (context.checkCallingOrSelfPermission(
            "android.permission.ACCESS_NETWORK_STATE") != PackageManager.PERMISSION_GRANTED) {
        Clog.e(Clog.baseLogTag, Clog.getString(R.string.permissions_missing_network_state));
        fail();
        this.cancel(true);
        return;
    }

    // Get orientation, the current rotation of the device
    orientation = context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE
            ? "h"
            : "v";
    // Get hidmd5, hidsha1, the device ID hashed
    if (Settings.getSettings().hidmd5 == null) {
        Settings.getSettings().hidmd5 = HashingFunctions.md5(aid);
    }
    hidmd5 = Settings.getSettings().hidmd5;
    if (Settings.getSettings().hidsha1 == null) {
        Settings.getSettings().hidsha1 = HashingFunctions.sha1(aid);
    }
    hidsha1 = Settings.getSettings().hidsha1;
    // Get devMake, devModel, the Make and Model of the current device
    devMake = Settings.getSettings().deviceMake;
    devModel = Settings.getSettings().deviceModel;
    // Get carrier
    if (Settings.getSettings().carrierName == null) {
        Settings.getSettings().carrierName = ((TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE)).getNetworkOperatorName();
    }
    carrier = Settings.getSettings().carrierName;
    // Get firstlaunch and convert it to a string
    firstlaunch = Settings.getSettings().first_launch;
    // Get ua, the user agent...
    ua = Settings.getSettings().ua;
    // Get wxh

    if (owner.isBanner()) {
        this.width = ((BannerAdView) owner).getAdWidth();
        this.height = ((BannerAdView) owner).getAdHeight();
    }

    maxHeight = owner.getContainerHeight();
    maxWidth = owner.getContainerWidth();

    if (Settings.getSettings().mcc == null || Settings.getSettings().mnc == null) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String networkOperator = tm.getNetworkOperator();
        if (networkOperator != null && networkOperator.length() >= 6) {
            Settings.getSettings().mcc = networkOperator.substring(0, 3);
            Settings.getSettings().mnc = networkOperator.substring(3);
        }
    }
    mcc = Settings.getSettings().mcc;
    mnc = Settings.getSettings().mnc;

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    connection_type = wifi.isConnected() ? "wifi" : "wan";
    dev_time = "" + System.currentTimeMillis();

    if (owner instanceof InterstitialAdView) {
        // Make string for allowed_sizes
        allowedSizes = "";
        ArrayList<Size> sizes = ((InterstitialAdView) owner).getAllowedSizes();
        for (Size s : sizes) {
            allowedSizes += "" + s.width() + "x" + s.height();
            // If not last size, add a comma
            if (sizes.indexOf(s) != sizes.size() - 1)
                allowedSizes += ",";
        }
    }

    nativeBrowser = owner.getOpensNativeBrowser() ? "1" : "0";

    //Reserve price
    reserve = owner.getReserve();
    if (reserve <= 0) {
        this.psa = owner.shouldServePSAs ? "1" : "0";
    } else {
        this.psa = "0";
    }

    age = owner.getAge();
    if (owner.getGender() != null) {
        if (owner.getGender() == AdView.GENDER.MALE) {
            gender = "m";
        } else if (owner.getGender() == AdView.GENDER.FEMALE) {
            gender = "f";
        } else {
            gender = null;
        }
    }
    customKeywords = owner.getCustomKeywords();

    mcc = Settings.getSettings().mcc;
    mnc = Settings.getSettings().mnc;
    language = Settings.getSettings().language;
}

From source file:fashiome.android.fragments.MapListFragment.java

private LatLng getLastKnownLocation(boolean isMoveMarker) {
    LocationManager lm = (LocationManager) AppStarter.getAppContext()
            .getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_LOW);
    String provider = lm.getBestProvider(criteria, true);
    if (provider == null) {
        return null;
    }// w  ww.  j av  a  2s.c  om
    Activity activity = getActivity();
    if (activity == null) {
        return null;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (activity.checkSelfPermission(
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && activity.checkSelfPermission(
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
    }
    Location loc = lm.getLastKnownLocation(provider);
    if (loc != null) {
        LatLng latLng = new LatLng(loc.getLatitude(), loc.getLongitude());
        if (isMoveMarker) {
            moveMarker(latLng);
        }
        return latLng;
    }
    return null;
}

From source file:hr.foicore.varazdinlandmarksdemo.POIMapActivity.java

public boolean drawUserDestRoute(LatLng destination) {

    gmm.handleMapWarningMessages(POIMapActivity.this, tvMapMessage);
    if (!gmm.myLocationEnabled || !gmm.internetEnabled) {
        tvMapMessage.setBackgroundColor(POIMapActivity.this.getResources().getColor(R.color.red_transparent));

        miDirections.setIcon(R.drawable.ic_action_directions);
        mActionDirections = 0;/* w  w  w  .j av  a2 s  .  c  o  m*/
        tvMapDirectionsInfo.setVisibility(View.INVISIBLE);

    } else {
        if (gmm.googleMap.getMyLocation() != null) {
            userLocation = new LatLng(gmm.googleMap.getMyLocation().getLatitude(),
                    gmm.googleMap.getMyLocation().getLongitude());
        } else {

            LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            String provider = service.getBestProvider(criteria, false);
            Location location = service.getLastKnownLocation(provider);
            if (location != null) {
                userLocation = new LatLng(location.getLatitude(), location.getLongitude());
            } else {
                Toast.makeText(POIMapActivity.this,
                        POIMapActivity.this.getResources().getString(R.string.my_location_problem),
                        Toast.LENGTH_LONG).show();
                return false;
            }
        }
        new connectAsyncTask(gmm.makeURL(userLocation.latitude, userLocation.longitude, destination.latitude,
                destination.longitude)).execute();

    }

    return true;

}

From source file:com.xmobileapp.rockplayer.LastFmEventImporter.java

/*********************************
 * // w  ww  .  j a v  a  2  s  . c  o  m
 * Constructor
 * @param context
 * 
 *********************************/
public LastFmEventImporter(Context context) {
    this.context = context;

    Log.i("LASTFMEVENT", "creating-------------------------");
    /*
     * Check for Internet Connection (Through whichever interface)
     */
    ConnectivityManager connManager = (ConnectivityManager) ((RockPlayer) context)
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = connManager.getActiveNetworkInfo();
    /******* EMULATOR HACK - false condition needs to be removed *****/
    //if (false && (netInfo == null || !netInfo.isConnected())){
    if ((netInfo == null || !netInfo.isConnected())) {
        Bundle data = new Bundle();
        data.putString("info", "No Internet Connection");
        Message msg = new Message();
        msg.setData(data);
        ((RockPlayer) context).analyseConcertInfoHandler.sendMessage(msg);
        return;
    }

    /*
     * Get location
     */
    MIN_UPDATE_INTVL = 5 * 24 * 60 * 60 * 1000; // 5 days
    SPREAD_INTVL = 21 * 24 * 60 * 60 * 1000; // 21 days;
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    LocationManager locManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    if (locManager.getBestProvider(criteria, true) != null)
        myLocation = locManager.getLastKnownLocation(locManager.getBestProvider(criteria, true));
    else {
        myLocation = new Location("gps");
        myLocation.setLatitude(47.100301);
        myLocation.setLongitude(-119.982465);
    }

    /*
     * Get preferred distance
     */
    //      SharedPreferences prefs = ((Filex) context).getSharedPreferences(((Filex) context).PREFS_NAME, 0);
    RockOnPreferenceManager prefs = new RockOnPreferenceManager(((RockPlayer) context).FILEX_PREFERENCES_PATH);
    concertRadius = prefs.getLong("ConcertRadius", (long) (((RockPlayer) context).CONCERT_RADIUS_DEFAULT));

    //myLocation =  locManager.getLastKnownLocation(locManager.getBestProvider(Criteria.POWER_LOW, true));

    //      try {
    //         getArtistEvents();
    //      } catch (SAXException e) {
    //         e.printStackTrace();
    //      } catch (ParserConfigurationException e) {
    //         e.printStackTrace();
    //      }
}

From source file:com.tingbacke.wearmaps.MobileActivity.java

/**
 * This is where we can add markers or lines, add listeners or move the camera. In this case, we
 * just add a marker near Africa.//  w w w .  j av a2 s.c om
 * <p/>
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 */
private void setUpMap() {

    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    mMap.setMyLocationEnabled(true);
    /**
     * https://geolocation.ws/map/55.588227,13.002735/13/en?types=&limit=300&licenses=
     * Dammfrivgen 61 = 55.587116, 12.979788
     */
    /*
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.61015, 12.9786)).title("Cykelpump Kockums Torg"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.5877, 12.9887)).title("Cykelpump Malm gamla stadion"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6093, 12.9967)).title("Cykelpump, Anna Linds plats"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6025, 12.9679)).title("Cykelpump, Ribersborgsstigen"));
            
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6131, 12.9767)).title("Turning Torso"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6140, 12.9839)).title("Stapelbddsparken, skatepark"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6125, 12.9914)).title("Media Evolution City"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6144, 12.9895)).title("Doc Piazza Trattoria"));
            
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6156, 12.9857)).title("Kranen K3, Malm Hgskola"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6150, 12.9858)).title("Ubtshallen"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6108, 12.9949)).title("Orkanen, Malm Hgskola"));
            
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.5850, 12.9873)).title("Swedbank Stadion"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.5922, 12.9975)).title("Pildammsparken Entr"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.5901, 12.9887)).title("Pildammsparken Tallriken"));
            
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.5890, 12.9825)).title("Jet bensinmack, Lorensborg"));
            
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6048, 12.9658)).title("Ribersborgs Kallbadhus"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6041, 12.9735)).title("Toalett, Ribersborgsstigen"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6086, 12.9774)).title("Kockum fritid"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6138, 12.9812)).title("Varvsparken"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6137, 12.9725)).title("Daniabadet, Vstra Hamnen"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6171, 12.9744)).title("Scaniabadet, Vstra Hamnen"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.5967, 13.0053)).title("MALM"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.5986, 12.9836)).title("Kronprinsen"));
    //mMap.addMarker(new MarkerOptions().position(new LatLng()).title(""));
    */
    // Get LocationManager object from System Service LOCATION_SERVICE
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    // Create a criteria object to retrieve provider
    Criteria criteria = new Criteria();

    // Get the name of the best provider
    String provider = locationManager.getBestProvider(criteria, true);

    // Get Current Location
    Location myLocation = locationManager.getLastKnownLocation(provider);

    // Get latitude of the current location
    double latitude = myLocation.getLatitude();

    // Get longitude of the current location
    double longitude = myLocation.getLongitude();

    // Create a LatLng object for the current location
    LatLng latLng = new LatLng(latitude, longitude);

    // Show the current location in Google Map
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(18).bearing(0).tilt(25)
            .build();
    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    LatLng myCoordinates = new LatLng(latitude, longitude);
    CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(myCoordinates, 18);
    mMap.animateCamera(yourLocation);

}

From source file:net.mypapit.mobile.myrepeater.RepeaterListActivity.java

public boolean isLocationEnabled(Context context) {
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    String provider = lm.getBestProvider(new Criteria(), true);
    return (!TextUtils.isEmpty(provider) && !LocationManager.PASSIVE_PROVIDER.equals(provider));

}

From source file:org.otempo.view.StationActivity.java

/**
 * Inicializa la estacin elegida, mirando en el GPS y sino pillando la primera.
 *///w  ww  .j a  v  a 2s.co m
private void initStationManager() {
    final Object data = getLastNonConfigurationInstance();
    if (data == null) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        String defaultStationPreference = prefs.getString(Preferences.PREF_DEFAULT_STATION,
                Preferences.DEFAULT_DEFAULT_STATION);
        int defaultStationFixed = Integer.valueOf(prefs.getString(Preferences.PREF_DEFAULT_STATION_FIXED, "1"));
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        assert locationManager != null;
        _stationManager = new StationManager(locationManager, defaultStationPreference, defaultStationFixed);
        if (locationManager.getBestProvider(new Criteria(), false) == null) {
            Toast.makeText(getApplicationContext(), R.string.gps_unavailable, Toast.LENGTH_LONG).show();
        }
    } else {
        final Object[] list = (Object[]) data;
        _stationManager = (StationManager) list[0];
        _skipDialog = true;
    }
    _stationManager.setListener(this);
}

From source file:com.ht.app.RestaurantsActivity.java

private Location getLastKnownLocation() {
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    String provider = lm.getBestProvider(criteria, true);
    if (provider == null) {
        return null;
    }//ww w  .  j  a va 2  s. c o m
    return lm.getLastKnownLocation(provider);
}

From source file:de.sindzinski.wetter.MainActivity.java

public Location getLocation() {
    Location location = null;//from w w  w .j ava2  s. c  o  m
    String provider = "";
    String locationSetting = "";

    if (!checkAndAskForPermission()) {
        return null;
    }

    try {
        // Get the location manager
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // Define the criteria how to select the locatioin provider -> use
        // default
        Criteria criteria = new Criteria();
        if (locationManager != null) {
            provider = locationManager.getBestProvider(criteria, false);
            location = locationManager.getLastKnownLocation(provider);
        }

    } catch (Exception ex) {
        Log.e(LOG_TAG, "Error creating location service: " + ex.getMessage());
    }

    return location;
}