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.lauszus.launchpadflightcontrollerandroid.app.MapFragment.java

@Override
public void onResume() {
    super.onResume();
    LocationManager locationManager = (LocationManager) getActivity()
            .getSystemService(Context.LOCATION_SERVICE);
    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        new AlertDialog.Builder(getActivity())
                .setMessage("Your GPS seems to be disabled, do you want to enable it?").setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {
                        startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }/*  w w  w . j a  va2  s. c o m*/
                }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int id) {
                        dialog.cancel();
                        Toast.makeText(getActivity(), "GPS must be on in order to use this application!",
                                Toast.LENGTH_LONG).show();
                        getActivity().finish();
                    }
                }).create().show();
    } else {
        setUpMapIfNeeded();
        if (ActivityCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            Location location = locationManager
                    .getLastKnownLocation(locationManager.getBestProvider(new Criteria(), false));
            if (location != null) {
                LatLng myLocation = new LatLng(location.getLatitude(), location.getLongitude());
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation, 19.0f));
            }
        }
    }
}

From source file:com.example.angel.parkpanda.MainActivity.java

public Location moveMyPosCamera() {

    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return null;
    }// w  ww.j av  a 2 s  .c  o m
    Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (myLocation == null) {
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        String provider = lm.getBestProvider(criteria, true);
        myLocation = lm.getLastKnownLocation(provider);
    }
    return myLocation;
}

From source file:it.geosolutions.geocollect.android.core.mission.PendingMissionListActivity.java

/**
 * Get provider name.//from   w ww  . java2  s . c  o m
 * @return Name of best suiting provider.
 * */
String getProviderName() {
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    criteria.setPowerRequirement(Criteria.POWER_LOW); // Chose your desired power consumption level.
    criteria.setAccuracy(Criteria.ACCURACY_FINE); // Choose your accuracy requirement.
    criteria.setSpeedRequired(false); // Chose if speed for first location fix is required.
    criteria.setAltitudeRequired(false); // Choose if you use altitude.
    criteria.setBearingRequired(false); // Choose if you use bearing.
    criteria.setCostAllowed(false); // Choose if this provider can waste money :-)

    // Provide your criteria and flag enabledOnly that tells
    // LocationManager only to return active providers.
    return locationManager.getBestProvider(criteria, true);
}

From source file:com.coincide.alphafitness.ui.Fragment_Main.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    //        final View v = inflater.inflate(R.layout.fragment_overview, null);
    View v = null;//ww  w . j  ava 2s .c  o m

    v = inflater.inflate(R.layout.fragment_main, container, false);

    //        stepsView = (TextView) v.findViewById(R.id.steps);
    //        totalView = (TextView) v.findViewById(R.id.total);
    totalView = (TextView) v.findViewById(R.id.tv_distance);
    tv_avg = (TextView) v.findViewById(R.id.tv_avg);
    tv_max = (TextView) v.findViewById(R.id.tv_max);
    tv_min = (TextView) v.findViewById(R.id.tv_min);
    //        averageView = (TextView) v.findViewById(R.id.average);

    /*
            pg = (PieChart) v.findViewById(R.id.graph);
            
            // slice for the steps taken today
            sliceCurrent = new PieModel("", 0, Color.parseColor("#99CC00"));
            pg.addPieSlice(sliceCurrent);
            
            // slice for the "missing" steps until reaching the goal
            sliceGoal = new PieModel("", Fragment_Settings.DEFAULT_GOAL, Color.parseColor("#CC0000"));
            pg.addPieSlice(sliceGoal);
            
            pg.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(final View view) {
        showSteps = !showSteps;
        stepsDistanceChanged();
    }
            });
            
            pg.setDrawValueInPie(false);
            pg.setUsePieRotation(true);
            pg.startAnimation();
    */

    /*
    * MainActivity
    * */
    // Always cast your custom Toolbar here, and set it as the ActionBar.
    Toolbar tb = (Toolbar) v.findViewById(R.id.toolbar);
    ((AppCompatActivity) getActivity()).setSupportActionBar(tb);

    TextView tv_tb_center = (TextView) tb.findViewById(R.id.tv_tb_center);
    tv_tb_center.setText("ALPHA FITNESS");

    /*   ImageButton imgbtn_cart = (ImageButton) tb.findViewById(R.id.imgbtn_cart);
       imgbtn_cart.setVisibility(View.GONE);*/

    tb.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getActivity().onBackPressed();
        }
    });

    // Get the ActionBar here to configure the way it behaves.
    final ActionBar ab = ((AppCompatActivity) getActivity()).getSupportActionBar();
    //ab.setHomeAsUpIndicator(R.drawable.ic_menu); // set a custom icon for the default home button
    ab.setDisplayShowHomeEnabled(false); // show or hide the default home button
    ab.setDisplayHomeAsUpEnabled(false);
    ab.setDisplayShowCustomEnabled(false); // enable overriding the default toolbar layout
    ab.setDisplayShowTitleEnabled(false); // disable the default title element here (for centered title)

    tv_duration = (TextView) v.findViewById(R.id.tv_duration);

    startButton = (Button) v.findViewById(R.id.btn_start);
    if (isButtonStartPressed) {
        startButton.setBackgroundResource(R.drawable.btn_stop_states);
        startButton.setText(R.string.btn_stop);
        try {
            SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
            sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER),
                    SensorManager.SENSOR_DELAY_UI, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        try {
            SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
            sm.unregisterListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    startButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            onSWatchStart();
        }
    });
    iv_profile = (ImageView) v.findViewById(R.id.iv_profile);
    iv_profile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Database db = Database.getInstance(getActivity());
            tot_workouts = db.getTotWorkouts();
            tot_workTime = db.getWorkTime();
            Log.e("Tot Work time", tot_workTime + "");
            //                int seconds = (int) (tot_workTime / 1000) % 60;
            //                int minutes = (int) ((tot_workTime / (1000 * 60)) % 60);

            long millis = tot_workTime * 100; // obtained from StopWatch
            long hours = (millis / 1000) / 3600;
            long minutes = (millis / 1000) / 60;
            long seconds = (millis / 1000) % 60;

            db.close();

            Intent i = new Intent(getActivity(), ProfileActivity.class);
            i.putExtra("avg_distance", avg_distance + "");
            i.putExtra("all_distance", all_distance + "");
            i.putExtra("avg_time", tv_duration.getText().toString());
            i.putExtra("all_time", tv_duration.getText().toString());
            i.putExtra("avg_calories", avg_calories + "");
            i.putExtra("all_calories", all_calories + "");
            i.putExtra("tot_workouts", tot_workouts + "");
            i.putExtra("avg_workouts", tot_workouts + "");

            i.putExtra("tot_workTime", hours + " hrs " + minutes + " min " + seconds + " sec");

            startActivity(i);

        }
    });

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

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

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

    } else { // Google Play Services are available

        // Initializing
        mMarkerPoints = new ArrayList<LatLng>();

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

        // Getting Map for the SupportMapFragment
        mGoogleMap = fm.getMap();

        // Enable MyLocation Button in the Map
        mGoogleMap.setMyLocationEnabled(true);

        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getActivity().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 From GPS
        Location location;
        if (provider != null) {

            if (ActivityCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(getActivity(),
                            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 null;
            }
            location = locationManager.getLastKnownLocation(provider);
            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        } else {
            location = new Location("");
            location.setLatitude(0.0d);//your coords of course
            location.setLongitude(0.0d);
        }

        if (location != null) {
            onLocationChanged(location);
        }

        // Setting onclick event listener for the map
        mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

            @Override
            public void onMapClick(LatLng point) {

                // Already map contain destination location
                if (mMarkerPoints.size() > 1) {

                    FragmentManager fm = getActivity().getSupportFragmentManager();
                    mMarkerPoints.clear();
                    mGoogleMap.clear();
                    LatLng startPoint = new LatLng(mLatitude, mLongitude);
                    drawMarker(startPoint);
                }

                drawMarker(point);

                // Checks, whether start and end locations are captured
                if (mMarkerPoints.size() >= 2) {
                    LatLng origin = mMarkerPoints.get(0);
                    LatLng dest = mMarkerPoints.get(1);

                    // Getting URL to the Google Directions API
                    String url = getDirectionsUrl(origin, dest);

                    DownloadTask downloadTask = new DownloadTask();

                    // Start downloading json data from Google Directions API
                    downloadTask.execute(url);
                }
            }
        });
        fixedCentreoption = new MarkerOptions();

        mGoogleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {

            @Override
            public void onCameraChange(CameraPosition position) {
                // TODO Auto-generated method stub
                // Get the center of the Map.

                mGoogleMap.clear();

                LatLng centerOfMap = mGoogleMap.getCameraPosition().target;

                // Update your Marker's position to the center of the Map.
                fixedCentreoption.position(centerOfMap);
                //                   mGoogleMap.addMarker(fixedCentreoption);
                //                   drawMarker(centerOfMap);
                LatLng origin = new LatLng(0.0d, 0.0d);
                ;
                if (mMarkerPoints.size() > 0) {
                    origin = mMarkerPoints.get(0);
                }
                //                  LatLng dest = mMarkerPoints.get(1);
                LatLng dest = centerOfMap;
                // Getting URL to the Google Directions API
                String url = getDirectionsUrl(origin, dest);

                DownloadTask downloadTask = new DownloadTask();

                // Start downloading json data from Google Directions API
                downloadTask.execute(url);

                GPSTracker gpsTracker = new GPSTracker(getActivity().getApplicationContext());
                //               String Addrs = gpsTracker.location();
                Addrs = gpsTracker.locationBasedOnLatlng(centerOfMap);
                //               Toast.makeText(getApplicationContext(), Addrs, Toast.LENGTH_LONG).show();

            }
        });
    }

    SharedPreferences sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES,
            Context.MODE_PRIVATE);
    mBodyWeight = Float.parseFloat(sharedpreferences.getString(sp_weight, "50"));

    return v;
}

From source file:com.mobilyzer.util.PhoneUtils.java

/**
 * Lazily initializes the location manager.
 *
 * As a side effect, assigns locationManager and locationProviderName.
 *///  www . jav a 2 s .  c  om
private synchronized void initLocation() {
    if (locationManager == null) {
        LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        Criteria criteriaCoarse = new Criteria();
        /* "Coarse" accuracy means "no need to use GPS".
         * Typically a gShots phone would be located in a building,
         * and GPS may not be able to acquire a location.
         * We only care about the location to determine the country,
         * so we don't need a super accurate location, cell/wifi is good enough.
         */
        criteriaCoarse.setAccuracy(Criteria.ACCURACY_COARSE);
        criteriaCoarse.setPowerRequirement(Criteria.POWER_LOW);
        String providerName = manager.getBestProvider(criteriaCoarse, /*enabledOnly=*/true);

        List<String> providers = manager.getAllProviders();
        for (String providerNameIter : providers) {
            try {
                LocationProvider provider = manager.getProvider(providerNameIter);
            } catch (SecurityException se) {
                // Not allowed to use this provider
                Logger.w("Unable to use provider " + providerNameIter);
                continue;
            }
            Logger.i(providerNameIter + ": "
                    + (manager.isProviderEnabled(providerNameIter) ? "enabled" : "disabled"));
        }

        /* Make sure the provider updates its location.
         * Without this, we may get a very old location, even a
         * device powercycle may not update it.
         * {@see android.location.LocationManager.getLastKnownLocation}.
         */
        manager.requestLocationUpdates(providerName, /*minTime=*/0, /*minDistance=*/0,
                new LoggingLocationListener(), Looper.getMainLooper());
        locationManager = manager;
        locationProviderName = providerName;
    }
    assert locationManager != null;
    assert locationProviderName != null;
}

From source file:org.getlantern.firetweet.activity.support.ComposeActivity.java

/**
 * The Location Manager manages location providers. This code searches for
 * the best provider of data (GPS, WiFi/cell phone tower lookup, some other
 * mechanism) and finds the last known location.
 *//*  w w w.  j  av  a  2 s  .c o  m*/
private boolean startLocationUpdateIfEnabled() {
    final LocationManager lm = mLocationManager;
    final boolean attachLocation = mPreferences.getBoolean(KEY_ATTACH_LOCATION, false);
    if (!attachLocation) {
        lm.removeUpdates(this);
        return false;
    }
    final Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    final String provider = lm.getBestProvider(criteria, true);
    if (provider != null) {
        mLocationText.setText(R.string.getting_location);
        lm.requestLocationUpdates(provider, 0, 0, this);
        final Location location;
        if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } else {
            location = lm.getLastKnownLocation(provider);
        }
        if (location != null) {
            onLocationChanged(location);
        }
    } else {
        Toast.makeText(this, R.string.cannot_get_location, Toast.LENGTH_SHORT).show();
    }
    return provider != null;
}

From source file:org.mariotaku.twidere.activity.support.ComposeActivity.java

/**
 * The Location Manager manages location providers. This code searches for
 * the best provider of data (GPS, WiFi/cell phone tower lookup, some other
 * mechanism) and finds the last known location.
 *//*from  w w w  .j  ava  2  s.c o m*/
private boolean startLocationUpdateIfEnabled() {
    final LocationManager lm = mLocationManager;
    final boolean attachLocation = mPreferences.getBoolean(KEY_ATTACH_LOCATION);
    if (!attachLocation) {
        lm.removeUpdates(this);
        return false;
    }
    final Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    final String provider = lm.getBestProvider(criteria, true);
    if (provider != null) {
        mLocationText.setText(R.string.getting_location);
        lm.requestLocationUpdates(provider, 0, 0, this);
        final Location location;
        if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        } else {
            location = lm.getLastKnownLocation(provider);
        }
        if (location != null) {
            onLocationChanged(location);
        }
    } else {
        Toast.makeText(this, R.string.cannot_get_location, Toast.LENGTH_SHORT).show();
    }
    return provider != null;
}

From source file:com.thomasokken.free42.Free42Activity.java

public int shell_get_location(DoubleHolder lat, DoubleHolder lon, DoubleHolder lat_lon_acc, DoubleHolder elev,
        DoubleHolder elev_acc) {//from  w  w w. ja va 2 s  . c om
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        locat_inited = false;
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
        return 0;
    }
    if (!locat_inited) {
        locat_inited = true;
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria cr = new Criteria();
        cr.setAccuracy(Criteria.ACCURACY_FINE);
        String provider = lm.getBestProvider(cr, true);
        if (provider == null) {
            locat_exists = false;
            return 0;
        }
        LocationListener ll = new LocationListener() {
            public void onLocationChanged(Location location) {
                // TODO: Verify units etc.
                locat_lat = location.getLatitude();
                locat_lon = location.getLongitude();
                locat_lat_lon_acc = location.getAccuracy();
                locat_elev = location.getAltitude();
                locat_elev_acc = location.hasAltitude() ? locat_lat_lon_acc : -1;
            }

            public void onProviderDisabled(String provider) {
                // Ignore
            }

            public void onProviderEnabled(String provider) {
                // Ignore
            }

            public void onStatusChanged(String provider, int status, Bundle extras) {
                // Ignore
            }
        };
        try {
            lm.requestLocationUpdates(provider, 60000, 1, ll, Looper.getMainLooper());
        } catch (IllegalArgumentException e) {
            return 0;
        } catch (SecurityException e) {
            return 0;
        }
        locat_exists = true;
    }

    if (locat_exists) {
        lat.value = locat_lat;
        lon.value = locat_lon;
        lat_lon_acc.value = locat_lat_lon_acc;
        elev.value = locat_elev;
        elev_acc.value = locat_elev_acc;
        return 1;
    } else
        return 0;
}

From source file:pandroid.agent.PandroidAgentListener.java

private void gpsLocation() {
    // Starts with GPS, if no GPS then gets network location
    //       /*w ww .  j av a2s. c o  m*/
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = lm.getProviders(true);
    Log.d("PANDROID providers count", "" + providers.size());

    /* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
    Location loc = null;

    for (int i = providers.size() - 1; i >= 0; i--) {
        Log.d("PANDROID providers", providers.get(i));
        loc = lm.getLastKnownLocation(providers.get(i));
        if (loc != null)
            break;
    }

    if (loc != null) {
        Log.d("PANDROID", "loc != null");
        //if(latitude != loc.getLatitude() || longitude != loc.getLongitude()) {
        lastGpsContactDateTime = getHumanDateTime(-1);
        //`}
        Log.d("LATITUDE", Double.valueOf(loc.getLatitude()).toString());
        Log.d("LONGITUDE", Double.valueOf(loc.getLongitude()).toString());
        putSharedData("PANDROID_DATA", "latitude", Double.valueOf(loc.getLatitude()).toString(), "float");
        putSharedData("PANDROID_DATA", "longitude", Double.valueOf(loc.getLongitude()).toString(), "float");
    }
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    String bestProvider = lm.getBestProvider(criteria, true);

    // If not provider found, abort GPS retrieving
    if (bestProvider == null) {
        Log.e("LOCATION", "No location provider found!");
        return;
    }

    lm.requestLocationUpdates(bestProvider, Core.interval, 15, new LocationListener() {
        public void onLocationChanged(Location location) {
            Log.d("Best latitude", Double.valueOf(location.getLatitude()).toString());
            putSharedData("PANDROID_DATA", "latitude", Double.valueOf(location.getLatitude()).toString(),
                    "float");
            Log.d("Best longitude", Double.valueOf(location.getLongitude()).toString());
            putSharedData("PANDROID_DATA", "longitude", Double.valueOf(location.getLongitude()).toString(),
                    "float");
        }

        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        public void onProviderEnabled(String s) {
            // try switching to a different provider
        }

        public void onProviderDisabled(String s) {
            putSharedData("PANDROID_DATA", "enabled_location_provider", "disabled", "string");
        }
    });
    //}

}