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:com.swetha.easypark.GoogleDirectionsActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mapdirections);
    StrictMode.setThreadPolicy(/*  ww  w  .j a  v a 2 s .c  o  m*/
            new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread
                    .penaltyLog().build());
    Log.i("GoogleDirectionsActivity", "Inside Oncreate");

    Intent theIntent = getIntent();
    tolat = theIntent.getDoubleExtra(GetParkingLots.LATITUDE, Constants.doubleDefaultValue);
    tolng = theIntent.getDoubleExtra(GetParkingLots.LONGITUDE, Constants.doubleDefaultValue);

    toPosition = new LatLng(tolat, tolng);

    Log.i("GoogleDirectionsActivity",
            "After Setting tolat, tolng, toPosition" + tolat + "\n" + tolng + "\n" + toPosition);

    md = new GetDirections();
    Log.i("GoogleDirectionsActivity", "After calling GetDirctions constructor");

    FragmentManager fm = getSupportFragmentManager();
    Log.i("GoogleDirectionsActivity", "After creating fragmentManager" + fm);
    SupportMapFragment supportMapfragment = ((SupportMapFragment) fm.findFragmentById(R.id.drivingdirections));

    Log.i("GoogleDirectionsActivity", "After creating SupportMapFragment" + supportMapfragment);
    mMap = supportMapfragment.getMap();
    Log.i("GoogleDirectionsActivity", "After getting map");

    mMap.setMyLocationEnabled(true);
    Log.i("GoogleDirectionsActivity", "After  setMyLocationEnabled");
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Log.i("GoogleDirectionsActivity", "After  locationManager");
    Criteria criteria = new Criteria();

    // Getting the name of the provider that meets the criteria
    provider = locationManager.getBestProvider(criteria, true);

    if (provider != null && !provider.equals("")) {

        // Get the location from the given provider 
        location = locationManager.getLastKnownLocation(provider);

        locationManager.requestLocationUpdates(provider, 500, 1, GoogleDirectionsActivity.this);

        if (location != null) {

            fromlat = location.getLatitude();
            fromlng = location.getLongitude();
        }

        else {
            fromlat = GetParkingLots.latitude;
            fromlng = GetParkingLots.longitude;
        }

    } else {
        Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
        finish();
    }
    Log.e("GoogleDirectionsActivity", "After  setting location");
    fromPosition = new LatLng(fromlat, fromlng);
    LatLng coordinates = new LatLng(fromlat, fromlng);
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 16));

    mMap.addMarker(new MarkerOptions().position(fromPosition).title("Start"));
    mMap.addMarker(new MarkerOptions().position(toPosition).title("End"));

    Document doc = md.getDocument(fromPosition, toPosition, Constants.MODE_DRIVING);
    String duration = md.getDurationText(doc);

    tv_duration = (TextView) findViewById(R.id.tv_time);
    tv_duration.setText("Estimated driving time:" + duration);

    ArrayList<LatLng> directionPoint = md.getDirection(doc);

    PolylineOptions rectLine = new PolylineOptions().width(6).color(Color.RED);

    for (int i = 0; i < directionPoint.size(); i++) {
        rectLine.add(directionPoint.get(i));
    }

    mMap.addPolyline(rectLine);
}

From source file:com.example.getneighborposition.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textview = (TextView) findViewById(R.id.tv_location);

    // Google Play Services???????
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    // Showing status
    if (status != ConnectionResult.SUCCESS) {
        // Google Play Services ?????
        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();// ww  w  .  ja v  a2 s  . co m

    } else {
        // Google Play Services ???
        // activity_main.xml?SupportMapFragment????
        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        // fragment?GoogleMap object?
        gMap = fm.getMap();

        // Google Map?MyLocation???
        gMap.setMyLocationEnabled(true);
        gMap.setIndoorEnabled(true);
        gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        gMap.setTrafficEnabled(true);

        // ?LOCATION_SERVICE?LocationManager object?
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // retrieve provider?criteria object?
        Criteria criteria = new Criteria();

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

        //provider??????????????
        if (provider != null) {
            Toast.makeText(this, provider + "???", Toast.LENGTH_LONG).show();

            Log.d("app", "the best provider is " + provider);
            // ???
            Location location = locationManager.getLastKnownLocation(provider);

            if (location != null) {
                onLocationChanged(location);
            }
            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        } else { //GPS?????????
            Toast.makeText(this, "????????", Toast.LENGTH_LONG).show();
        }
    }

}

From source file:com.keysolutions.meteorparties.PartyMapFragment.java

/**
 * Gets current location using Android's location provider
 * so you can zoom the map to it/*from w w  w. j a v a2  s.  c  o  m*/
 * @return last known Location
 */
@SuppressWarnings("unused")
private Location getCurrentLocation() {
    Criteria criteria = new Criteria();
    LocationManager locMan = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    String towers = locMan.getBestProvider(criteria, false);
    Location location = locMan.getLastKnownLocation(towers);
    return location;
}

From source file:edu.mit.mobile.android.locast.ver2.casts.LocatableListWithMap.java

/**
 * Gets the last-known location and updates with that.
 *//* w  ww. ja  va 2s. co  m*/
private void updateLocation() {
    final LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
    final String provider = lm.getBestProvider(new Criteria(), true);
    if (provider == null) {
        Toast.makeText(this, getString(R.string.error_no_providers), Toast.LENGTH_LONG).show();
        finish();
        return;
    }

    final Location loc = lm.getLastKnownLocation(provider);
    if (loc != null) {
        updateLocation(loc);
    } else {
        Toast.makeText(this, R.string.notice_finding_your_location, Toast.LENGTH_LONG).show();
        setRefreshing(true);
        mMapView.setVisibility(View.VISIBLE); // show the map, even without location being found
    }
    mLastLocation = loc;
}

From source file:cubes.compass.service.WeatherActivity.java

private void getWeatherFromCurrentLocation() {
    // system's LocationManager
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    // medium accuracy for weather, good for 100 - 500 meters
    Criteria locationCriteria = new Criteria();
    locationCriteria.setAccuracy(Criteria.ACCURACY_MEDIUM);

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

    // single location update
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;//from w  w  w  . j a v  a 2s .  c  o  m
    }
    locationManager.requestSingleUpdate(provider, this, null);
}

From source file:edu.mit.mobile.android.locast.casts.LocatableListWithMap.java

/**
 * Gets the last-known location and updates with that.
 *//*from   w w  w  . j  a va  2 s .co  m*/
private void updateLocation() {
    final LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
    final String provider = lm.getBestProvider(new Criteria(), true);
    if (provider == null) {
        Toast.makeText(this, getString(R.string.error_no_providers), Toast.LENGTH_LONG).show();
        finish();
        return;
    }

    final Location loc = lm.getLastKnownLocation(provider);
    if (loc != null) {
        updateLocation(loc);
    } else {
        Toast.makeText(this, R.string.notice_finding_your_location, Toast.LENGTH_LONG).show();
        setRefreshing(true);
    }
    mLastLocation = loc;
}

From source file:com.dat255.ht13.grupp23.view.MapView.java

/**
 * Initiating the GoogleMap and all necessary items for the configuration
 * /*from  w w w . j a  v a 2s.c  o m*/
 * @param fragmentActivity
 */
private void initiateMap(FragmentActivity fragmentActivity) {
    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(fragmentActivity.getBaseContext());

    // Showing status
    if (status != ConnectionResult.SUCCESS) { // Google Play Services are
        // not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, fragmentActivity, requestCode);
        dialog.show();

    } else { // Google Play Services are available

        // Getting reference to the SupportMapFragment of activity_main.xml
        SupportMapFragment fm = (SupportMapFragment) fragmentActivity.getSupportFragmentManager()
                .findFragmentById(R.id.map);

        // Getting GoogleMap object from the fragment
        googleMap = fm.getMap();

        // Enabling MyLocation Layer of Google Map
        googleMap.setMyLocationEnabled(true);

        // Getting LocationManager object from System Service
        // LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) fragmentActivity
                .getSystemService(Context.LOCATION_SERVICE);

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

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

        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            onLocationChanged(location);
            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        }
    }

}

From source file:com.johan.vertretungsplan_2.SelectSchoolActivity.java

private void showListGeo() {
    final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE); // no GPS
    final String provider = locationManager.getBestProvider(criteria, true);

    if (provider == null) {
        Log.d("vertretungsplan", "provider==null");
        tvLocateString.setText(R.string.geolocate_disabled);
        status = Status.LIST;//  w  ww  .ja va 2  s .  c o m
        return;
    }
    locationManager.requestLocationUpdates(provider, 0, 0, new LocationListener() {
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onLocationChanged(Location location) {
            if (!visible)
                return;
            if (location != null) {
                double lat = location.getLatitude();
                double lon = location.getLongitude();
                for (Schule school : schools) {
                    float[] result = new float[1];
                    Location.distanceBetween(lat, lon, school.getGeo()[0], school.getGeo()[1], result);
                    school.setDistance(result[0]);
                    Log.d("vertretungsplan", school.getName() + ": " + school.getDistance());
                }
                Collections.sort(schools, new DistanceSchoolComparator());
                lstSchools.setAdapter(new SchoolsAdapter(SelectSchoolActivity.this, schools, true));
            }
            tvLocateString.setText(R.string.alphabetic_list);
            ivLocationIcon.setImageResource(R.drawable.ic_action_view_as_list);
            status = Status.GEO;
        }
    });
}

From source file:com.refujiate.ui.MainMapaActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tab_ubicacion);
    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    // Showing status
    if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();//from   ww w  .  ja  v a  2s.c  om

    } else { // Google Play Services are available

        // Getting reference to the SupportMapFragment of activity_main.xml
        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        // Getting GoogleMap object from the fragment
        googleMap = fm.getMap();

        // Enabling MyLocation Layer of Google Map
        googleMap.setMyLocationEnabled(true);

        googleMap.moveCamera(
                CameraUpdateFactory.newLatLngZoom(new LatLng(-8.105972881341886, -79.028778076171880), 12));

        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

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

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

        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(provider, 20000, 0, this);
    }
    addMaker(0);
    Intent svc = new Intent(this, RefugiateService.class);
    startService(svc);
}

From source file:com.example.zenkig.halomap.HaloMapsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_halo_maps);
    setUpMapIfNeeded();/*w  ww  .j a v a 2  s.  c o m*/

    tvLocInfo = (TextView) findViewById(R.id.locinfo);

    // mLocationClient = new LocationClient(this, this, this); // create location client

    mMap.setMyLocationEnabled(true); // location layer does not provide data
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    mMap.setOnMapClickListener(this);

    // before loop:
    List<Marker> markers = new ArrayList<Marker>();
    mMap.setOnMapLongClickListener(this);
    // after loop
    markers.size(); // marker numbers size get

    mMap.setOnMarkerDragListener(this);
    mMap.setOnMyLocationChangeListener(this); // listener for location change added
    mMap.setInfoWindowAdapter(new MyInfoWindowAdapter()); // Info window listener adaptor added
    mMap.setOnInfoWindowClickListener(this);

    markerClicked = false;

    // Getting Google Play status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    // Showing status
    if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();

    } else { // Google Play Services are available

        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

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

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

        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);
    }

}