List of usage examples for android.location LocationManager GPS_PROVIDER
String GPS_PROVIDER
To view the source code for android.location LocationManager GPS_PROVIDER.
Click Source Link
From source file:com.davidmascharka.lips.MainActivity.java
private void updateScanResults() { if (userInitiatedScan) { //Toast.makeText(this, "Scan finished", Toast.LENGTH_SHORT).show(); resetWifiReadings(building);/*from w ww . j a v a2 s . com*/ scanResults = wifiManager.getScanResults(); for (ScanResult result : scanResults) { if (wifiReadings.get(result.BSSID) != null) { wifiReadings.put(result.BSSID, result.level); } else { // BSSID wasn't programmed in - notify user //Toast.makeText(this, "This BSSID is new: " + result.BSSID, // Toast.LENGTH_SHORT).show(); } } // Get a filehandle for /sdcard/indoor_localization/dataset_BUILDING.txt File root = Environment.getExternalStorageDirectory(); File dir = new File(root.getAbsolutePath() + "/indoor_localization"); dir.mkdirs(); File file = new File(dir, "dataset_" + building + ".txt"); try { FileOutputStream outputStream = new FileOutputStream(file, true); PrintWriter writer = new PrintWriter(outputStream); writer.print(accelerometerX + "," + accelerometerY + "," + accelerometerZ + "," + magneticX + "," + magneticY + "," + magneticZ + "," + light + "," + rotationX + "," + rotationY + "," + rotationZ + "," + orientation[0] + "," + orientation[1] + "," + orientation[2]); for (String key : wifiReadings.keySet()) { writer.print("," + wifiReadings.get(key)); } if (location != null) { writer.print("," + location.getLatitude() + "," + location.getLongitude() + "," + location.getAccuracy()); } else { //@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"); location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); } if (location != null) { writer.print("," + location.getLatitude() + "," + location.getLongitude() + "," + location.getAccuracy()); } else { //@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, "Permssions have already been granted. Getting last know location from network"); location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } if (location != null) { writer.print("," + location.getLatitude() + "," + location.getLongitude() + "," + location.getAccuracy()); } else { Toast.makeText(this, "Location was null", Toast.LENGTH_SHORT).show(); writer.print(",?,?,?"); } } } TextView xposition = (TextView) findViewById(R.id.text_xposition); TextView yposition = (TextView) findViewById(R.id.text_yposition); writer.print("," + xposition.getText().toString().substring(3)); writer.print("," + yposition.getText().toString().substring(3)); writer.print(" %" + (new Timestamp(System.currentTimeMillis())).toString()); writer.print("\n\n"); writer.flush(); writer.close(); Toast.makeText(this, "Done saving datapoint", Toast.LENGTH_SHORT).show(); userInitiatedScan = false; } catch (Exception e) { Toast.makeText(this, "There was an error", Toast.LENGTH_SHORT).show(); Log.e("ERROR", Log.getStackTraceString(e)); } } Button button = (Button) findViewById(R.id.button_confirm); button.setClickable(true); }
From source file:it.unime.mobility4ckan.MainActivity.java
private boolean isGPSEnable() { LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); return mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER); }
From source file:com.roamprocess1.roaming4world.ui.messages.MessageActivity.java
private boolean checkGPSEnabled() { // TODO Auto-generated method stub try {/* w w w . jav a 2s. co m*/ locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); } catch (Exception ex) { return false; } }
From source file:ca.nehil.rter.streamingapp2.StreamingActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Orientation listenever implementation myOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) { @Override/*from ww w.j ava2 s . co m*/ public void onOrientationChanged(int orientation) { int rotation = getWindowManager().getDefaultDisplay().getRotation(); if (rotation == Surface.ROTATION_270) { flipVideo = true; } else { flipVideo = false; } } }; myOrientationEventListener.enable(); // stopService(new Intent(StreamingActivity.this, // BackgroundService.class)); Log.e(TAG, "onCreate"); AndroidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID); frameInfo = new FrameInfo(); // openGL overlay overlay = new OverlayController(this); // orientation mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); mAcc = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mMag = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); setContentView(R.layout.activity_streaming); // Find the total number of cameras available numberOfCameras = Camera.getNumberOfCameras(); cookies = getSharedPreferences("RterUserCreds", MODE_PRIVATE); prefEditor = cookies.edit(); setUsername = cookies.getString("Username", "not-set"); setRterCredentials = cookies.getString("RterCreds", "not-set"); if (setRterCredentials.equalsIgnoreCase("not-set") || setRterCredentials == null) { Log.e("PREFS", "Login Not successful, please restart"); } Log.d("PREFS", "Prefs ==> rter_Creds:" + setRterCredentials); // Get the location manager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // Define the criteria how to select the location provider -> use // default if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Log.e(TAG, "GPS not available"); } Criteria criteria = new Criteria(); provider = locationManager.getBestProvider(criteria, true); Log.d(TAG, "Requesting location"); locationManager.requestLocationUpdates(provider, 0, 1, this); // register the overlay control for location updates as well, so we get // the geomagnetic field locationManager.requestLocationUpdates(provider, 0, 1000, overlay); if (provider != null) { Location location = locationManager.getLastKnownLocation(provider); // Initialize the location fields if (location != null) { System.out.println("Provider " + provider + " has been selected. and location " + location); onLocationChanged(location); } else { Toast toast = Toast.makeText(this, "Location not available", Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP, 0, 0); toast.show(); lati = (float) (45.505958f); longi = (float) (-73.576254f); Log.d(TAG, "Location not available"); } } // power manager PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, CLASS_LABEL); mWakeLock.acquire(); // test, set desired orienation to north overlay.letFreeRoam(false); overlay.setDesiredOrientation(0.0f); // CharSequence text = "Tap to start.."; // int duration = Toast.LENGTH_SHORT; // // Toast toast = Toast.makeText(this, text, duration); // toast.setGravity(Gravity.TOP|Gravity.RIGHT, 0, 0); // toast.show(); }
From source file:cl.gisred.android.InspActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LicenseResult licenseResult = ArcGISRuntime.setClientId(CLIENT_ID); LicenseLevel licenseLevel = ArcGISRuntime.License.getLicenseLevel(); if (licenseResult == LicenseResult.VALID && licenseLevel == LicenseLevel.BASIC) { //Toast.makeText(getApplicationContext(), "Licencia bsica vlida", Toast.LENGTH_SHORT).show(); } else if (licenseResult == LicenseResult.VALID && licenseLevel == LicenseLevel.STANDARD) { //Toast.makeText(getApplicationContext(), "Licencia standard vlida", Toast.LENGTH_SHORT).show(); }/*from w ww . ja va2 s. c o m*/ setContentView(R.layout.activity_insp); Toolbar toolbar = (Toolbar) findViewById(R.id.apptool); setSupportActionBar(toolbar); /*Get Credenciales String*/ Bundle bundle = getIntent().getExtras(); usuar = bundle.getString("usuario"); passw = bundle.getString("password"); modulo = bundle.getString("modulo"); empresa = bundle.getString("empresa"); //Set Credenciales setCredenciales(usuar, passw); //Set Mapa setMap(R.id.map, 0xffffff, 0xffffff, 10, 10, false, true); choices = 0; if (Build.VERSION.SDK_INT >= 23) verifPermisos(); else initGeoposition(); setLayersURL(this.getResources().getString(R.string.url_Mapabase), "MAPABASE"); setLayersURL(this.getResources().getString(R.string.url_token), "TOKENSRV"); setLayersURL(this.getResources().getString(R.string.url_EquiposLinea), "EQUIPOS_LINEA"); setLayersURL(this.getResources().getString(R.string.url_TRAMOS), "TRAMOS"); setLayersURL(this.getResources().getString(R.string.url_EquiposPTO), "EQUIPOS_PTO"); setLayersURL(this.getResources().getString(R.string.url_Nodos), "NODOS"); setLayersURL(this.getResources().getString(R.string.url_Luminarias), "LUMINARIAS"); setLayersURL(this.getResources().getString(R.string.url_Clientes), "CLIENTES"); setLayersURL(this.getResources().getString(R.string.url_Concesiones), "CONCESIONES"); setLayersURL(this.getResources().getString(R.string.url_Direcciones), "DIRECCIONES"); setLayersURL(this.getResources().getString(R.string.url_medidores), "MEDIDORES"); setLayersURL(this.getResources().getString(R.string.url_Stx), "STX"); setLayersURL(this.getResources().getString(R.string.url_ECSE_varios), "ECSE"); setLayersURL(this.getResources().getString(R.string.url_Electrodependientes), "ELECTRODEP"); //Agrega layers dinmicos. addLayersToMap(credenciales, "DYNAMIC", "MAPABASECHQ", din_urlMapaBase, null, true); addLayersToMap(credenciales, "DYNAMIC", "SED", din_urlEquiposPunto, null, false); addLayersToMap(credenciales, "DYNAMIC", "SSEE", din_urlEquiposPunto, null, false); addLayersToMap(credenciales, "DYNAMIC", "SALIDAALIM", din_urlEquiposPunto, null, false); addLayersToMap(credenciales, "DYNAMIC", "REDMT", din_urlTramos, null, false); addLayersToMap(credenciales, "DYNAMIC", "REDBT", din_urlTramos, null, false); addLayersToMap(credenciales, "DYNAMIC", "REDAP", din_urlTramos, null, false); addLayersToMap(credenciales, "DYNAMIC", "POSTES", din_urlNodos, null, false); addLayersToMap(credenciales, "DYNAMIC", "EQUIPOS_LINEA", din_urlEquiposLinea, null, false); addLayersToMap(credenciales, "DYNAMIC", "EQUIPOS_PTO", din_urlEquiposPunto, null, false); addLayersToMap(credenciales, "DYNAMIC", "LUMINARIAS", din_urlLuminarias, null, false); addLayersToMap(credenciales, "DYNAMIC", "CLIENTES", din_urlClientes, null, false); addLayersToMap(credenciales, "DYNAMIC", "MEDIDORES", din_urlMedidores, null, false); addLayersToMap(credenciales, "DYNAMIC", "CONCESIONES", din_urlConcesiones, null, false); addLayersToMap(credenciales, "DYNAMIC", "DIRECCIONES", din_urlDirecciones, null, false); addLayersToMap(credenciales, "DYNAMIC", "EMPALMES", din_urlClientes, null, false); addLayersToMap(credenciales, "DYNAMIC", "REDSTX", din_urlStx, null, false); addLayersToMap(credenciales, "DYNAMIC", "TORRESSTX", din_urlStx, null, false); addLayersToMap(credenciales, "DYNAMIC", "ENCUESTADO", din_urlECSE, null, false); addLayersToMap(credenciales, "DYNAMIC", "REEMPLAZO", din_urlECSE, null, false); addLayersToMap(credenciales, "DYNAMIC", "ELECTRODEP", din_urlElectroDep, null, false); //Aade Layer al Mapa myMapView.addLayer(mRoadBaseMaps, 0); myMapView.addLayer(LySED, 1); myMapView.addLayer(LySSEE, 2); myMapView.addLayer(LySALIDAALIM, 3); myMapView.addLayer(LyPOSTES, 4); myMapView.addLayer(LyREDMT, 5); myMapView.addLayer(LyREDBT, 6); myMapView.addLayer(LyREDAP, 7); myMapView.addLayer(LyEQUIPOSLINEA, 8); myMapView.addLayer(LyEQUIPOSPTO, 9); myMapView.addLayer(LyLUMINARIAS, 10); myMapView.addLayer(LyCLIENTES, 11); myMapView.addLayer(LyMEDIDORES, 12); myMapView.addLayer(LyCONCESIONES, 13); myMapView.addLayer(LyDIRECCIONES, 14); myMapView.addLayer(LyEMPALMES, 15); myMapView.addLayer(LyREDSTX, 16); myMapView.addLayer(LyTORRESSTX, 17); myMapView.addLayer(LyENCUESTA, 18); myMapView.addLayer(LyREEMPLAZO, 19); myMapView.addLayer(LyELECTRODEP, 20); final FloatingActionButton btnGps = (FloatingActionButton) findViewById(R.id.action_gps); btnGps.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { alertNoGps(); } toogleGps(v); } }); btnGps.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(getApplicationContext(), "Funcin Gps", Toast.LENGTH_SHORT).show(); return true; } }); final FloatingActionButton btnVerData = (FloatingActionButton) findViewById(R.id.action_ver_data); btnVerData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { toogleData(v); } }); btnVerData.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(getApplicationContext(), "Ver Datos", Toast.LENGTH_SHORT).show(); return true; } }); drawOk = new ShapeDrawable(new OvalShape()); drawOk.getPaint().setColor(getResources().getColor(R.color.colorPrimary)); drawNo = new ShapeDrawable(new OvalShape()); drawNo.getPaint().setColor(getResources().getColor(R.color.black_overlay)); menuInspeccionActions = (FloatingActionsMenu) findViewById(R.id.inspection_actions); menuMultipleActions = (FloatingActionsMenu) findViewById(R.id.multiple_actions); fabShowDialog = (FloatingActionButton) findViewById(R.id.action_show_dialog); if (fabShowDialog != null) fabShowDialog.setVisibility(View.GONE); fabShowForm = (FloatingActionButton) findViewById(R.id.action_show_form); if (fabShowForm != null) fabShowForm.setVisibility(View.GONE); fabVerCapas = (FloatingActionButton) findViewById(R.id.action_ver_capa); if (fabVerCapas != null) fabVerCapas.setVisibility(View.GONE); fabNavRoute = (FloatingActionButton) findViewById(R.id.action_nav_route); if (fabNavRoute != null) { fabNavRoute.setVisibility(View.GONE); fabNavRoute.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (myMapView != null && myMapView.getCallout().isShowing()) { Point p = (Point) GeometryEngine.project(myMapView.getCallout().getCoordinates(), wm, egs); Util.QueryNavigation(InspActivity.this, p); } } }); fabNavRoute.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(getApplicationContext(), "Ir a Ruta", Toast.LENGTH_SHORT).show(); return true; } }); } if (modulo.replace(" ", "_").equals(modInspeccion)) { dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US); arrayTipoFaseInsp = getResources().getStringArray(R.array.fase_conexion_insp); arrayMarca = getResources().getStringArray(R.array.marca); arrayTipoMarca = getResources().getStringArray(R.array.tipo_marca); arrayFirmante = getResources().getStringArray(R.array.situacion_firmante); arrayWidgets = bundle.getStringArrayList("widgets"); arrayModulos = bundle.getStringArrayList("modulos"); final String sForm = bundle.getString("form"); if (sForm.contains("TELEMEDIDA")) { arrayMarcaTM = getResources().getStringArray(R.array.marca_tm); arrayTipoMarcaTM = getResources().getStringArray(R.array.tipo_marca_tm); } formCrear = new Dialog(InspActivity.this); fabShowForm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //bMapTap = false; //bCallOut = false; //myMapView.getCallout().hide(); formCrear.show(); } }); FloatingActionButton oFabForm = (FloatingActionButton) findViewById(R.id.action_form); oFabForm.setIconDrawable(drawOk); oFabForm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { abrirFormInsp(v, sForm); } }); FloatingActionButton oFabView = (FloatingActionButton) findViewById(R.id.action_view); oFabView.setIconDrawable(drawOk); oFabView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { abrirEsquema(v); } }); FloatingActionButton oFabDenuncio = (FloatingActionButton) findViewById(R.id.action_denuncio); oFabDenuncio.setIconDrawable(drawNo); oFabDenuncio.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //abrirFormDenuncio(v); Snackbar.make(v, "No tiene acceso a sta opcin", Snackbar.LENGTH_SHORT).show(); menuInspeccionActions.collapse(); } }); if (arrayModulos != null && arrayModulos.size() > 0 && arrayModulos.contains(empresa + "@" + modIngreso)) { arrayTipoPoste = getResources().getStringArray(R.array.tipo_poste); arrayTension = getResources().getStringArray(R.array.tipo_tension); arrayTipoEdif = getResources().getStringArray(R.array.tipo_edificacion); arrayMedidor = getResources().getStringArray(R.array.tipo_medidor); arrayEmpalme = getResources().getStringArray(R.array.tipo_empalme); arrayTecMedidor = getResources().getStringArray(R.array.tec_medidor); arrayTipoCnr = getResources().getStringArray(R.array.tipo_cnr); arrayTipoFase = getResources().getStringArray(R.array.fase_conexion); dialogCrear = new Dialog(InspActivity.this); fabShowDialog.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bMapTap = false; bCallOut = false; myMapView.getCallout().hide(); if (oUbicacion != null) { btnUbicacion.setColorFilter(Color.BLACK); setEnabledDialog(true); } dialogCrear.show(); if (mSeleccionLayer != null && myMapView.getLayerByID(mSeleccionLayer.getID()) != null) myMapView.removeLayer(mSeleccionLayer); } }); fabVerCapas.setVisibility(View.VISIBLE); fabVerCapas.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { toogleCapas(v); } }); fabVerCapas.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(getApplicationContext(), "Ver Capas de Ingreso", Toast.LENGTH_SHORT).show(); return true; } }); final FloatingActionButton actionA = (FloatingActionButton) findViewById(R.id.action_a); final FloatingActionButton actionB = (FloatingActionButton) findViewById(R.id.action_b); final FloatingActionButton actionC = (FloatingActionButton) findViewById(R.id.action_c); final FloatingActionButton actionD = (FloatingActionButton) findViewById(R.id.action_d); setOpcion(actionA, null); setOpcion(actionB, null); setOpcion(actionC, modIngreso + "_TECNO"); setOpcion(actionD, modIngreso + "_CNR"); setLayersURL(this.getResources().getString(R.string.srv_Postes), "SRV_POSTES"); setLayersURL(this.getResources().getString(R.string.srv_Direcciones), "SRV_DIRECCIONES"); setLayersURL(this.getResources().getString(R.string.srv_Clientes), "SRV_CLIENTES"); setLayersURL(this.getResources().getString(R.string.srv_Union_012), "SRV_UNIONES"); setLayersURL(din_urlTramos, "TRAMOS"); setLayersURL(this.getResources().getString(R.string.url_Mapabase), "SRV_CALLES"); setLayersURL(this.getResources().getString(R.string.srv_ClientesCnr), "SRV_CLIENTESCNR"); addLayersToMap(credenciales, "FEATURE", "ADDPOSTE", srv_urlPostes, null, true); addLayersToMap(credenciales, "FEATURE", "ADDADDRESS", srv_urlDireccion, null, true); addLayersToMap(credenciales, "FEATURE", "ADDCLIENTE", srv_urlClientes, null, true); addLayersToMap(credenciales, "FEATURE", "ADDUNION", srv_urlUnion012, null, true); addLayersToMap(credenciales, "FEATURE", "ASOCTRAMO", LyREDBT.getUrl(), null, false); addLayersToMap(credenciales, "FEATURE", "ASOCCALLE", srv_calles, null, false); addLayersToMap(credenciales, "FEATURE", "ADDCLIENTECNR", srv_urlClientesCnr, null, true); myMapView.addLayer(LyAddPoste, 21); myMapView.addLayer(LyAddDireccion, 22); myMapView.addLayer(LyAddCliente, 23); myMapView.addLayer(LyAddUnion, 24); myMapView.addLayer(LyAsocTramo, 25); myMapView.addLayer(LyAsocCalle, 26); myMapView.addLayer(LyAddClienteCnr, 27); setLayerAddToggle(false); } else { menuMultipleActions.setVisibility(View.GONE); } } else { menuInspeccionActions.setVisibility(View.GONE); } }
From source file:com.nogago.android.tracks.services.TrackRecordingService.java
private void registerLocationListener() { if (locationManager == null) { Log.e(TAG, "TrackRecordingService: Do not have any location manager."); return;//from w w w. jav a 2 s .c o m } Log.d(TAG, "Preparing to register location listener w/ TrackRecordingService..."); try { long desiredInterval = locationListenerPolicy.getDesiredPollingInterval(); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, desiredInterval, locationListenerPolicy.getMinDistance(), // , 0 /* minDistance, get all updates to properly time pauses */ locationListener); currentRecordingInterval = desiredInterval; Log.d(TAG, "...location listener now registered w/ TrackRecordingService @ " + currentRecordingInterval); } catch (RuntimeException e) { Log.e(TAG, "Could not register location listener: " + e.getMessage(), e); } }
From source file:gov.sfmta.sfpark.MainScreenActivity.java
void startLocation() { SharedPreferences preferences = getPreferences(MODE_PRIVATE); warningSeen = preferences.getBoolean(WARNING_KEY, false); if (warningSeen) { //once only, ever! return;/*www.j a va 2s .c om*/ } locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); speed = 0; lastSpeed = 0; thisProvider = LocationManager.GPS_PROVIDER; // Define a listener that responds to location updates locationListener = new LocationListener() { public void onStatusChanged(String provider, int status, Bundle extras) { MYLOG(String.format("onStatusChanged %d", status)); } public void onProviderEnabled(String provider) { MYLOG("onProviderEnabled" + provider); thisProvider = provider; } public void onProviderDisabled(String provider) { MYLOG("onProviderDisabled" + provider); thisProvider = null; } @Override public void onLocationChanged(Location loc) { MYLOG("onLocationChanged"); lastSpeed = speed; if (loc == null) { speed = 0; } else { // speed is returned in meters per second speed = loc.getSpeed(); userLocation = loc; mapView.invalidate(); } // need last speed > threshold as well. if (speed > SPEED_THRESHOLD) { if (lastSpeed > SPEED_THRESHOLD) { SharedPreferences preferences = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); warningSeen = preferences.getBoolean(WARNING_KEY, false); if (warningSeen == false) { warningSeen = true; editor.putBoolean(WARNING_KEY, warningSeen); editor.commit(); SpeedingViewActivity.present(mapView.getContext()); } } } if (SFparkActivity.DEBUG) { String locStr = String.format("speed:%f last speed:%f, when %d", speed, lastSpeed, System.currentTimeMillis()); debugText.setText(locStr); } } }; locationUpdates(true); }
From source file:com.zainsoft.ramzantimetable.QiblaActivity.java
private void registerForGPS() { Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); criteria.setPowerRequirement(Criteria.POWER_LOW); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false);//from w w w. j a va 2s . c o m criteria.setSpeedRequired(false); criteria.setCostAllowed(true); LocationManager locationManager = ((LocationManager) getSystemService(Context.LOCATION_SERVICE)); String provider = locationManager.getBestProvider(criteria, true); if (provider != null) { locationManager.requestLocationUpdates(provider, MIN_LOCATION_TIME, MIN_LOCATION_DISTANCE, qiblaManager); } locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_LOCATION_TIME, MIN_LOCATION_DISTANCE, qiblaManager); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_LOCATION_TIME, MIN_LOCATION_DISTANCE, qiblaManager); Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location == null) { location = ((LocationManager) getSystemService(Context.LOCATION_SERVICE)) .getLastKnownLocation(LocationManager.GPS_PROVIDER); } if (location != null) { qiblaManager.onLocationChanged(location); } }
From source file:com.landenlabs.all_devtool.GpsFragment.java
@Override public void onLocationChanged(Location location) { boolean isDupLoc = false; try {// ww w. j a v a 2 s .com Location gpsLoc = m_locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (gpsLoc != null) { showGPS(gpsLoc); isDupLoc = isDupLoc || (location.distanceTo(gpsLoc) == 0); } } catch (Exception ex) { Toast.makeText(this.getActivity(), "GPS " + ex.getMessage(), Toast.LENGTH_LONG).show(); } try { if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { Location netLoc = m_locMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (netLoc != null) { showGPS(netLoc); isDupLoc = isDupLoc || (location.distanceTo(netLoc) == 0); } } } catch (Exception ex) { Toast.makeText(this.getActivity(), "GPS needs location permission\n" + ex.getMessage(), Toast.LENGTH_LONG).show(); } try { Location passiveLoc = m_locMgr.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); if (null != passiveLoc) { showGPS(passiveLoc); isDupLoc = isDupLoc || (location.distanceTo(passiveLoc) == 0); } } catch (Exception ex) { Toast.makeText(this.getActivity(), "Passive " + ex.getMessage(), Toast.LENGTH_LONG).show(); } if (!isDupLoc) showGPS(location); }
From source file:com.trailbehind.android.iburn.map.MapActivity.java
/** * Sets the location source./* w ww . jav a 2 s. co m*/ */ private void setupLocationSource() { final AppLocationProvider locProvider = getActiveLocationProvider(); locProvider.setLocationMarker(createLocationMarker()); locProvider.setLocationListener(new AppLocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { if (LocationManager.GPS_PROVIDER.equalsIgnoreCase(provider)) { if (status == LocationProvider.OUT_OF_SERVICE) { mProgressBar.setVisibility(View.VISIBLE); mMessageTextView.setText(R.string.msg_locating); UIUtils.showPanel(getBaseContext(), mMessagePanel, false); } else { UIUtils.hidePanel(getBaseContext(), mMessagePanel, false); } } } @Override public void onProviderEnabled(String provider) { if (LocationManager.GPS_PROVIDER.equalsIgnoreCase(provider)) { checkGPSProvider(); } } @Override public void onProviderDisabled(String provider) { if (LocationManager.GPS_PROVIDER.equalsIgnoreCase(provider)) { checkGPSProvider(); } } @Override public void onLocationChanged(String provider, Location location) { if (LocationManager.GPS_PROVIDER.equalsIgnoreCase(provider)) { if (Globals.sCurrentGPSLocation == null) { CompassUtils.updateUserBearing(false, location.getBearing()); } else { final boolean hasBearing = location.hasBearing(); final float pointBearing = MapUtils.calculateBearing(Globals.sCurrentGPSLocation, location); CompassUtils.updateUserBearing(hasBearing, (hasBearing) ? location.getBearing() : pointBearing); } if (mMessagePanel.getVisibility() == View.VISIBLE) { mProgressBar.setVisibility(View.GONE); UIUtils.hidePanel(getBaseContext(), mMessagePanel, false); } } else { CompassUtils.updateUserBearing(false, location.getBearing()); if (mGetMyLocation) { final AppLocationProvider locProvider = getActiveLocationProvider(); final LocationMarker locationMarker = locProvider.getLocationMarker(); locationMarker.updatePosition(); } } } @Override public void onProviderChanged(String oldProvider, String newProvider) { if (LocationManager.GPS_PROVIDER.equalsIgnoreCase(newProvider)) { mMapComponent.removeLocationSource(); final AppLocationProvider locProvider = getActiveLocationProvider(); final LocationMarker locationMarker = createLocationMarker(); locProvider.setLocationMarker(locationMarker); mMapComponent.setLocationSource(locProvider); locationMarker.setTrackingEnabled(mGetMyLocation); } } }); mMapComponent.setLocationSource(locProvider); }