Example usage for android.location LocationManager GPS_PROVIDER

List of usage examples for android.location LocationManager GPS_PROVIDER

Introduction

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

Prototype

String GPS_PROVIDER

To view the source code for android.location LocationManager GPS_PROVIDER.

Click Source Link

Document

Name of the GPS location provider.

Usage

From source file:edu.cens.loci.provider.LociDbUtils.java

/**
 * Returns an average position fix/*from  w w  w .ja v  a2  s  .co m*/
 * @param start beginning time
 * @param end ending time
 * @param accuracy filter position fixes with accuracy value higher than this value
 * @return average position within the provided time interval, filtered by accuracy
 */
public LociLocation getAveragePosition(long start, long end, int accuracy) {

    LociLocation placeLoc = null;

    String[] columns = new String[] { Tracks._ID, Tracks.TIME, Tracks.LATITUDE, Tracks.LONGITUDE,
            Tracks.ALTITUDE, Tracks.SPEED, Tracks.BEARING, Tracks.ACCURACY };

    String selection = Tracks.TIME + ">=" + start + " AND " + Tracks.TIME + " <= " + end;

    final SQLiteDatabase db = mDbHelper.getWritableDatabase();
    Cursor cursor = db.query(Tables.TRACKS, columns, selection, null, null, null, null);

    ArrayList<LociLocation> track = new ArrayList<LociLocation>();

    MyLog.d(LociConfig.D.DB.UTILS, TAG,
            String.format("[DB] average position between %s-%s ==> #pos=%d (accuracy=%d)",
                    MyDateUtils.getTimeFormatLong(start), MyDateUtils.getTimeFormatLong(end), cursor.getCount(),
                    accuracy));

    if (cursor.moveToFirst()) {
        do {
            LociLocation loc = new LociLocation(LocationManager.GPS_PROVIDER);
            loc.setTime(cursor.getLong(cursor.getColumnIndex(Tracks.TIME)));
            loc.setLatitude(cursor.getDouble(cursor.getColumnIndex(Tracks.LATITUDE)));
            loc.setLongitude(cursor.getDouble(cursor.getColumnIndex(Tracks.LONGITUDE)));
            loc.setAltitude(cursor.getDouble(cursor.getColumnIndex(Tracks.ALTITUDE)));
            loc.setSpeed(cursor.getFloat(cursor.getColumnIndex(Tracks.SPEED)));
            loc.setBearing(cursor.getFloat(cursor.getColumnIndex(Tracks.BEARING)));
            loc.setAccuracy(cursor.getFloat(cursor.getColumnIndex(Tracks.ACCURACY)));
            track.add(loc);
        } while (cursor.moveToNext());

        placeLoc = LociLocation.averageLocation(track, accuracy);
    }
    cursor.close();
    return placeLoc;

}

From source file:com.lewa.crazychapter11.MainActivity.java

public boolean hasGPSDevice(Context context) {
    final LocationManager mgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    if (mgr == null)
        return false;
    final List<String> providers = mgr.getAllProviders();
    if (providers == null)
        return false;

    Log.i("algerheGps", "System hasGps=" + providers.contains(LocationManager.GPS_PROVIDER));
    return providers.contains(LocationManager.GPS_PROVIDER);
}

From source file:org.planetmono.dcuploader.ActivityUploader.java

@Override
public void onResume() {
    super.onResume();

    /* resume location query */
    if (locationEnabled) {
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationTracker);
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationTracker);
    }//from  w ww.j  ava2  s . c om
}

From source file:edu.cens.loci.provider.LociDbUtils.java

public LociLocation getPlaceLocationEstimationWithBestAccuracy(long start, long end) {
    LociLocation placeLoc = null;/*from  w  w  w  .j ava  2 s  .  co  m*/

    String[] columns = new String[] { Tracks._ID, Tracks.TIME, Tracks.LATITUDE, Tracks.LONGITUDE,
            Tracks.ALTITUDE, Tracks.SPEED, Tracks.BEARING, Tracks.ACCURACY };

    String selection = Tracks.TIME + ">=" + start + " AND " + Tracks.TIME + " <= " + end;

    final SQLiteDatabase db = mDbHelper.getWritableDatabase();
    Cursor cursor = db.query(Tables.TRACKS, columns, selection, null, null, null, null);

    float minAccuracy = Float.MAX_VALUE;

    if (cursor.moveToFirst()) {
        do {
            if (minAccuracy > cursor.getFloat(cursor.getColumnIndex(Tracks.ACCURACY))) {
                if (placeLoc == null)
                    placeLoc = new LociLocation(LocationManager.GPS_PROVIDER);
                placeLoc.setTime(cursor.getLong(cursor.getColumnIndex(Tracks.TIME)));
                placeLoc.setLatitude(cursor.getDouble(cursor.getColumnIndex(Tracks.LATITUDE)));
                placeLoc.setLongitude(cursor.getDouble(cursor.getColumnIndex(Tracks.LONGITUDE)));
                placeLoc.setAltitude(cursor.getDouble(cursor.getColumnIndex(Tracks.ALTITUDE)));
                placeLoc.setSpeed(cursor.getFloat(cursor.getColumnIndex(Tracks.SPEED)));
                placeLoc.setBearing(cursor.getFloat(cursor.getColumnIndex(Tracks.BEARING)));
                placeLoc.setAccuracy(cursor.getFloat(cursor.getColumnIndex(Tracks.ACCURACY)));
                minAccuracy = placeLoc.getAccuracy();
            }
        } while (cursor.moveToNext());
    }
    cursor.close();
    return placeLoc;
}

From source file:com.davidmascharka.lips.TrackerActivity.java

@Override
public void onResume() {
    super.onResume();

    File root = Environment.getExternalStorageDirectory();
    File dir = new File(root.getAbsolutePath() + "/indoor_localization");
    dir.mkdirs();/*from  ww  w .j a v a  2 s . c  om*/
    file = new File(dir, "livetest_" + building + ".txt");
    valuesFile = new File(dir, "livetest_" + building + "_values.txt");
    try {
        outputStream = new FileOutputStream(file, true);
        valuesOutputStream = new FileOutputStream(valuesFile, true);
        writer = new PrintWriter(outputStream);
        valuesWriter = new PrintWriter(valuesOutputStream);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Set building textview to the building the user has selected
    //TextView buildingText = (TextView) findViewById(R.id.text_building);
    //buildingText.setText("Building: " + building);

    // Set room size textview to the room size the user has selected
    //TextView roomSizeText = (TextView) findViewById(R.id.text_room_size);
    //roomSizeText.setText("Room size: " + roomWidth + " x " + roomLength);

    // Set grid options
    GridView grid = (GridView) findViewById(R.id.tracker_gridView);
    //grid.setGridSize(roomWidth, roomLength);
    grid.setGridSize(102, 64);
    grid.setCatchInput(false);
    //grid.setDisplayMap(displayMap);

    // Register to get sensor updates from all the available sensors
    sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL);
    for (Sensor sensor : sensorList) {
        sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_FASTEST);
    }

    // Enable wifi if it is disabled
    if (!wifiManager.isWifiEnabled()) {
        Toast.makeText(this, "WiFi not enabled. Enabling...", Toast.LENGTH_SHORT).show();
        wifiManager.setWifiEnabled(true);
    }

    // Request location updates from gps and the network
    //@author Mahesh Gaya added permission if-statment
    if (ActivityCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        Log.i(TAG, "Permissions have NOT been granted. Requesting permissions.");
        requestMyPermissions();
    } else {
        Log.i(TAG, "Permissions have already been granted. Getting location from GPS and Network");
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    }

    registerReceiver(receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

    wifiManager.startScan();
    Toast.makeText(this, "Initiated scan", Toast.LENGTH_SHORT).show();

    xText = (TextView) findViewById(R.id.tracker_text_xcoord);
    yText = (TextView) findViewById(R.id.tracker_text_ycoord);
}

From source file:edu.cens.loci.provider.LociDbUtils.java

/**
 * @param time//w w  w . j  a v a2s . c om
 * @param before
 * @return first location before time if before is true. Otherwise, after time. 
 *         returns null if no location is available.
 */
public LociLocation getFirstLocationBeforeOrAfterTime(long time, boolean before) {

    LociLocation loc = null;

    String[] columns = new String[] { Tracks._ID, Tracks.TIME, Tracks.LATITUDE, Tracks.LONGITUDE,
            Tracks.ALTITUDE, Tracks.SPEED, Tracks.BEARING, Tracks.ACCURACY };

    String selection = Tracks.TIME + "<=" + time;
    String order = " DESC";

    if (!before) {
        selection = Tracks.TIME + ">=" + time;
        order = " ASC";
    }

    final SQLiteDatabase db = mDbHelper.getWritableDatabase();
    Cursor cursor = db.query(Tables.TRACKS, columns, selection, null, null, null, Tracks.TIME + order, "" + 1);

    if (cursor.moveToFirst()) {
        loc = new LociLocation(LocationManager.GPS_PROVIDER);
        loc.setTime(cursor.getLong(cursor.getColumnIndex(Tracks.TIME)));
        loc.setLatitude(cursor.getDouble(cursor.getColumnIndex(Tracks.LATITUDE)));
        loc.setLongitude(cursor.getDouble(cursor.getColumnIndex(Tracks.LONGITUDE)));
        loc.setAltitude(cursor.getDouble(cursor.getColumnIndex(Tracks.ALTITUDE)));
        loc.setSpeed(cursor.getFloat(cursor.getColumnIndex(Tracks.SPEED)));
        loc.setBearing(cursor.getFloat(cursor.getColumnIndex(Tracks.BEARING)));
        loc.setAccuracy(cursor.getFloat(cursor.getColumnIndex(Tracks.ACCURACY)));
    }
    cursor.close();
    return loc;
}

From source file:com.davidmascharka.lips.TrackerActivity.java

/**
 * When a new WiFi scan comes in, get sensor values and predict position
 *///from www  .j a  v a  2  s .  c  o m
private void updateScanResults() {
    resetWifiReadings();

    scanResults = wifiManager.getScanResults();

    // Start another scan to recalculate user position
    wifiManager.startScan();

    time = new Timestamp(System.currentTimeMillis());

    for (ScanResult result : scanResults) {
        if (wifiReadings.get(result.BSSID) != null) {
            wifiReadings.put(result.BSSID, result.level);
        } // else BSSID wasn't programmed in
    }
    //@author Mahesh Gaya added permission if-statment
    if (ActivityCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.CHANGE_WIFI_STATE) != PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(this,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        Log.i(TAG, "Permissions have NOT been granted. Requesting permissions.");
        requestMyPermissions();
    } else {
        Log.i(TAG, "Permissions have already been granted. Getting last known location from GPS and Network");
        if (location == null) {
            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        }
        if (location == null) {
            locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
    }
    setInstanceValues();

    printValues();

    // this is where the magic happens
    // TODO clean up
    if (!t.isAlive()) {
        t = new Thread(new Runnable() {
            public void run() {
                Timestamp myTime = time;
                // This doesn't do anything -> classifierXKStar is null -> not loaded
                /*try {
                   predictedX = (float) classifierXRBFRegressor.classifyInstance(xInstances.get(0));
                } catch (Exception e) {
                   e.printStackTrace();
                }
                // Likewise, doesn't happen
                try {
                   predictedY = (float) classifierYRBFRegressor.classifyInstance(yInstances.get(0));
                } catch (Exception e) {
                   e.printStackTrace();
                }*/

                // Get the partition that the new instance is in
                // Use the classifier of the predicted partition to predict an x and y value for
                // the new instance if the classifier is loaded (not null)
                try {
                    predictedPartition = partitionClassifier.classifyInstance(partitionInstances.get(0));
                    //double[] dist = partitionClassifier.distributionForInstance(partitionInstances.get(0)); // gets the probability distribution for the instance
                } catch (Exception e) {
                    e.printStackTrace();
                }

                String partitionString = partitionInstances.classAttribute().value((int) predictedPartition);
                if (partitionString.equals("upperleft")) {
                    if (partitionUpperLeftX != null) {
                        try {
                            predictedX = (float) partitionUpperLeftX.classifyInstance(xInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (partitionUpperLeftY != null) {
                        try {
                            predictedY = (float) partitionUpperLeftY.classifyInstance(yInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else if (partitionString.equals("upperright")) {
                    if (partitionUpperRightX != null) {
                        try {
                            predictedX = (float) partitionUpperRightX.classifyInstance(xInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (partitionUpperRightY != null) {
                        try {
                            predictedY = (float) partitionUpperRightY.classifyInstance(yInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else if (partitionString.equals("lowerleft")) {
                    if (partitionLowerLeftX != null) {
                        try {
                            predictedX = (float) partitionLowerLeftX.classifyInstance(xInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (partitionLowerLeftY != null) {
                        try {
                            predictedY = (float) partitionLowerLeftY.classifyInstance(yInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else if (partitionString.equals("lowerright")) {
                    if (partitionLowerRightX != null) {
                        try {
                            predictedX = (float) partitionLowerRightX.classifyInstance(xInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (partitionLowerRightY != null) {
                        try {
                            predictedY = (float) partitionLowerRightY.classifyInstance(yInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else if (partitionString.equals("middle")) {
                    if (partitionMiddleX != null) {
                        try {
                            predictedX = (float) partitionMiddleX.classifyInstance(xInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (partitionMiddleX != null) {
                        try {
                            predictedY = (float) partitionMiddleY.classifyInstance(yInstances.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                xText.post(new Runnable() {
                    public void run() {
                        xText.setText("X Position: " + predictedX);
                    }
                });

                yText.post(new Runnable() {
                    public void run() {
                        yText.setText("Y Position: " + predictedY);
                    }
                });

                // TODO: make this work -> grid is apparently null here. For whatever reason.
                /*runOnUiThread(new Runnable() {
                   public void run() {
                      grid.setUserPointCoords(predictedX, predictedY);
                   }
                });*/

                // Unnecessary if you're not testing
                writer.print("(" + predictedX + "," + predictedY + ")");
                writer.print(" %" + myTime.toString() + "\t " + time.toString() + "\t"
                        + new Timestamp(System.currentTimeMillis()) + "\n");
                writer.flush();
            }
        });
        t.setPriority(Thread.MIN_PRIORITY); // run in the background
        t.start();
    }
}

From source file:reportsas.com.formulapp.Formulario.java

public void HabilitarParametros(Menu menu) {
    for (int i = 0; i < encuesta.getParametros().size(); i++) {

        switch (encuesta.getParametros().get(i).getIdParametro()) {
        // Captura GPS
        case 1:/*from  w  w  w .j a v  a  2s .  c o m*/

            menu.getItem(2).setVisible(true);
            parametroGPS = new ParametrosRespuesta(1);
            manejador = (LocationManager) getSystemService(LOCATION_SERVICE);
            if (!manejador.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                AlertDialog alert = null;
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("El sistema GPS esta desactivado, Debe activarlo!").setCancelable(false)
                        .setPositiveButton("Activar GPS", new DialogInterface.OnClickListener() {
                            public void onClick(@SuppressWarnings("unused") final DialogInterface dialog,
                                    @SuppressWarnings("unused") final int id) {
                                startActivity(
                                        new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                            }
                        });
                alert = builder.create();
                alert.show();
            }
            Criteria criterio = new Criteria();
            criterio.setCostAllowed(false);
            criterio.setAltitudeRequired(false);
            criterio.setAccuracy(Criteria.ACCURACY_FINE);
            proveedor = manejador.getBestProvider(criterio, true);
            Location localizacion = manejador.getLastKnownLocation(proveedor);
            capturarLocalizacion(localizacion);
            manejador.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, this);
            Toast toast1;
            if (parametroGPS.getValor().equals("Posicion Desconocida")) {
                toast1 = Toast.makeText(this, "Posicion Desconocida.", Toast.LENGTH_SHORT);

            } else {
                toast1 = Toast.makeText(this, "Localizacin obtenida exitosamente.", Toast.LENGTH_SHORT);

            }

            toast1.show();
            break;
        // Captura Imgen
        case 2:

            menu.getItem(0).setVisible(true);
            break;
        // Lectura de Codigo
        case 3:

            menu.getItem(1).setVisible(true);
            break;

        default:

            break;
        }

    }

}

From source file:com.vonglasow.michael.satstat.MainActivity.java

/**
 * Called when the status of the GPS changes. Updates GPS display.
 *//*w w w. j a v  a 2  s.com*/
public void onGpsStatusChanged(int event) {
    GpsStatus status = mLocationManager.getGpsStatus(null);
    int satsInView = 0;
    int satsUsed = 0;
    Iterable<GpsSatellite> sats = status.getSatellites();
    for (GpsSatellite sat : sats) {
        satsInView++;
        if (sat.usedInFix()) {
            satsUsed++;
        }
    }

    if (isGpsViewReady) {
        gpsSats.setText(String.valueOf(satsUsed) + "/" + String.valueOf(satsInView));
        gpsTtff.setText(String.valueOf(status.getTimeToFirstFix() / 1000));
        gpsStatusView.showSats(sats);
        gpsSnrView.showSats(sats);
    }

    if ((isMapViewReady) && (satsUsed == 0)) {
        Location location = providerLocations.get(LocationManager.GPS_PROVIDER);
        if (location != null)
            markLocationAsStale(location);
        applyLocationProviderStyle(this, LocationManager.GPS_PROVIDER, LOCATION_PROVIDER_GRAY);
    }
}

From source file:com.vonglasow.michael.satstat.MainActivity.java

/**
 * Called when a new location is found by a registered location provider.
 * Stores the location and updates GPS display and map view.
 *//*from w w w. j av  a2s.c o m*/
public void onLocationChanged(Location location) {
    // some providers may report NaN for latitude and longitude:
    // if that happens, do not process this location and mark any previous
    // location from that provider as stale
    if (Double.isNaN(location.getLatitude()) || Double.isNaN(location.getLongitude())) {
        markLocationAsStale(providerLocations.get(location.getProvider()));
        if (isMapViewReady)
            applyLocationProviderStyle(this, location.getProvider(), LOCATION_PROVIDER_GRAY);
        return;
    }

    if (providerLocations.containsKey(location.getProvider()))
        providerLocations.put(location.getProvider(), new Location(location));

    // update map view
    if (isMapViewReady) {
        LatLong latLong = new LatLong(location.getLatitude(), location.getLongitude());

        Circle circle = mapCircles.get(location.getProvider());
        Marker marker = mapMarkers.get(location.getProvider());

        if (circle != null) {
            circle.setLatLong(latLong);
            if (location.hasAccuracy()) {
                circle.setVisible(true);
                circle.setRadius(location.getAccuracy());
            } else {
                Log.d("MainActivity", "Location from " + location.getProvider() + " has no accuracy");
                circle.setVisible(false);
            }
        }

        if (marker != null) {
            marker.setLatLong(latLong);
            marker.setVisible(true);
        }

        applyLocationProviderStyle(this, location.getProvider(), null);

        Runnable invalidator = providerInvalidators.get(location.getProvider());
        if (invalidator != null) {
            providerInvalidationHandler.removeCallbacks(invalidator);
            providerInvalidationHandler.postDelayed(invalidator, PROVIDER_EXPIRATION_DELAY);
        }

        // redraw, move locations into view and zoom out as needed
        if ((circle != null) || (marker != null) || (invalidator != null))
            updateMap();
    }

    // update GPS view
    if ((location.getProvider().equals(LocationManager.GPS_PROVIDER)) && (isGpsViewReady)) {
        if (location.hasAccuracy()) {
            gpsAccuracy.setText(String.format("%.0f", location.getAccuracy()));
        } else {
            gpsAccuracy.setText(getString(R.string.value_none));
        }

        gpsLat.setText(String.format("%.5f%s", location.getLatitude(), getString(R.string.unit_degree)));
        gpsLon.setText(String.format("%.5f%s", location.getLongitude(), getString(R.string.unit_degree)));
        gpsTime.setText(String.format("%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS", location.getTime()));

        if (location.hasAltitude()) {
            gpsAlt.setText(String.format("%.0f", location.getAltitude()));
            orDeclination.setText(String.format("%.0f%s",
                    new GeomagneticField((float) location.getLatitude(), (float) location.getLongitude(),
                            (float) location.getAltitude(), location.getTime()).getDeclination(),
                    getString(R.string.unit_degree)));
        } else {
            gpsAlt.setText(getString(R.string.value_none));
            orDeclination.setText(getString(R.string.value_none));
        }

        if (location.hasBearing()) {
            gpsBearing.setText(String.format("%.0f%s", location.getBearing(), getString(R.string.unit_degree)));
            gpsOrientation.setText(formatOrientation(location.getBearing()));
        } else {
            gpsBearing.setText(getString(R.string.value_none));
            gpsOrientation.setText(getString(R.string.value_none));
        }

        if (location.hasSpeed()) {
            gpsSpeed.setText(String.format("%.0f", (location.getSpeed()) * 3.6));
        } else {
            gpsSpeed.setText(getString(R.string.value_none));
        }

        // note: getting number of sats in fix by looking for "satellites"
        // in location's extras doesn't seem to work, always returns 0 sats
    }
}