List of usage examples for android.location LocationManager NETWORK_PROVIDER
String NETWORK_PROVIDER
To view the source code for android.location LocationManager NETWORK_PROVIDER.
Click Source Link
From source file:com.platform.GeoLocationManager.java
public void startGeoSocket(Session sess) { session = sess;/*from www . ja v a 2 s. c o m*/ final MainActivity app = MainActivity.app; if (app == null) return; final LocationManager locationManager = (LocationManager) app.getSystemService(Context.LOCATION_SERVICE); app.runOnUiThread(new Runnable() { @Override public void run() { if (ActivityCompat.checkSelfPermission(app, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(app, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { RuntimeException ex = new RuntimeException("startGeoSocket, can't happen"); Log.e(TAG, "run: startGeoSocket, can't happen"); FirebaseCrash.report(ex); return; } locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, socketLocationListener); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, socketLocationListener); } }); }
From source file:androidmapsdefinitivo.android.bajaintec.com.androidmapsdefinitivo.MapsActivity.java
@Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap;/*w w w . j ava 2 s . co m*/ try { locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location == null) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) this); location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location == null) { Log.d("Falla de gps: ", "valio"); location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } } CameraUpdate center = CameraUpdateFactory .newLatLng(new LatLng(location.getLatitude(), location.getLongitude())); /* CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(32.595085, -115.482046)); */ //CameraUpdate zoom = CameraUpdateFactory.zoomTo(20); mMap.moveCamera(center); //mMap.animateCamera(zoom); point = new LatLng(location.getAltitude(), location.getLongitude()); getLines(location.getAltitude(), location.getLongitude()); //getLines(); mMap.setMyLocationEnabled(true); mMap.getUiSettings().setZoomControlsEnabled(false); } catch (SecurityException e) { System.exit(0); } catch (NullPointerException e) { System.exit(0); } final Snackbar snackStart = Snackbar.make(findViewById(R.id.map), "Selecciona una ruta de una calle", Snackbar.LENGTH_LONG); snackStart.show(); final Snackbar snackErr = Snackbar.make(findViewById(R.id.map), "Selecciona una sola calle", Snackbar.LENGTH_LONG); final Snackbar snackbar = Snackbar.make(findViewById(R.id.map), R.string.guardar_ruta, Snackbar.LENGTH_LONG); mBtnGuardar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MapsActivity.this, SeguridadActivity.class); intent.putExtra("calle", calleDestino); intent.putExtra("origen_n", String.valueOf(markerPoints.get(0).latitude)); intent.putExtra("origen_w", String.valueOf(markerPoints.get(0).longitude)); intent.putExtra("destino_n", String.valueOf(markerPoints.get(1).latitude)); intent.putExtra("destino_w", String.valueOf(markerPoints.get(1).longitude)); intent.putExtra("idUsuario", getIntent().getIntExtra("idUsuario", 0)); startActivity(intent); } }); mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() { @Override public void onCameraChange(CameraPosition cameraPosition) { LatLng li = cameraPosition.target; LatLngBounds bounds = mMap.getProjection().getVisibleRegion().latLngBounds; if (!bounds.contains(point)) { try { point = null; point = new LatLng(li.latitude, li.longitude); System.out.println("Sali"); getLines(point.latitude, point.longitude); //getLines(); } catch (SecurityException e) { e.printStackTrace(); } } } }); mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng point) { if (markerPoints.size() > 1) { markerPoints.clear(); mMap.clear(); mBtnGuardar.setEnabled(false); //snackbar.dismiss(); getLines(); //getLines(point.latitude,point.longitude); } markerPoints.add(point); /* try { Geocoder gc = new Geocoder(getBaseContext(), Locale.getDefault()); List<Address> addresses = gc.getFromLocation(point.latitude, point.longitude, 1); //Obtener nombres de las calles. if (markerPoints.size() == 1) { calleOrigen = addresses.get(0).getAddressLine(0); } else if (markerPoints.size() == 2) { calleDestino = addresses.get(0).getAddressLine(0); } } catch (IOException e) { e.printStackTrace(); }*/ MarkerOptions options = new MarkerOptions(); options.position(point); if (markerPoints.size() == 1) { options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)); } else if (markerPoints.size() == 2) { options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)); if (!calleOrigen.equalsIgnoreCase(calleDestino)) { Log.d("Calles: ", calleOrigen + "//" + calleDestino); Boolean msj = !calleOrigen.equalsIgnoreCase(calleDestino); Log.d("Calles: ", msj.toString()); markerPoints.clear(); mMap.clear(); //getLines(point.latitude,point.longitude); getLines(); snackErr.show(); return; } } mMap.addMarker(options); if (markerPoints.size() >= 2) { LatLng origin = markerPoints.get(0); LatLng dest = markerPoints.get(1); String url = getDirectionsUrl(origin, dest); DownloadTask downloadTask = new DownloadTask(); downloadTask.execute(url); snackbar.show(); mBtnGuardar.setEnabled(true); } } }); //getLines(); getLines(point.latitude, point.longitude); }
From source file:org.odk.collect.android.activities.GeoShapeGoogleMapActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.geoshape_google_layout); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.gmap)).getMap(); mHelper = new MapHelper(this, mMap); mMap.setMyLocationEnabled(true);/*from www. j a v a 2 s . c o m*/ mMap.setOnMapLongClickListener(this); mMap.setOnMarkerDragListener(this); mMap.getUiSettings().setMyLocationButtonEnabled(false); mMap.getUiSettings().setCompassEnabled(true); mMap.getUiSettings().setZoomControlsEnabled(false); polygonOptions = new PolygonOptions(); polygonOptions.strokeColor(Color.RED); List<String> providers = mLocationManager.getProviders(true); for (String provider : providers) { if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) { mGPSOn = true; curLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); } if (provider.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)) { mNetworkOn = true; curLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } } if (!mGPSOn & !mNetworkOn) { showGPSDisabledAlertToUser(); } gps_button = (Button) findViewById(R.id.gps); gps_button.setEnabled(false); gps_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // if(curLocation !=null){ // mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(curlatLng,16)); // } showZoomDialog(); } }); clear_button = (Button) findViewById(R.id.clear); clear_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (markerArray.size() != 0) { showClearDialog(); } } }); return_button = (Button) findViewById(R.id.save); return_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { returnLocation(); } }); Intent intent = getIntent(); if (intent != null && intent.getExtras() != null) { if (intent.hasExtra(GeoShapeWidget.SHAPE_LOCATION)) { data_loaded = true; clear_button.setEnabled(true); String s = intent.getStringExtra(GeoShapeWidget.SHAPE_LOCATION); gps_button.setEnabled(true); overlayIntentPolygon(s); } } layers_button = (Button) findViewById(R.id.layers); layers_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mHelper.showLayersDialog(); } }); zoomDialogView = getLayoutInflater().inflate(R.layout.geoshape_zoom_dialog, null); zoomLocationButton = (Button) zoomDialogView.findViewById(R.id.zoom_location); zoomLocationButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (curLocation != null) { mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(curlatLng, 17)); } zoomDialog.dismiss(); } }); zoomPointButton = (Button) zoomDialogView.findViewById(R.id.zoom_shape); zoomPointButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // zoomToCentroid(); zoomtoBounds(); zoomDialog.dismiss(); } }); // If there is a last know location go there if (curLocation != null) { curlatLng = new LatLng(curLocation.getLatitude(), curLocation.getLongitude()); foundFirstLocation = true; initZoom = true; gps_button.setEnabled(true); showZoomDialog(); } }
From source file:com.swetha.easypark.GetParkingLots.java
@Override protected void onCreate(Bundle savedInstanceState) { if (!isGooglePlayServicesAvailable()) { finish();/* ww w . j av a2 s . c o m*/ } super.onCreate(savedInstanceState); setContentView(R.layout.getparkinglots); SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); googleMap = supportMapFragment.getMap(); googleMap.setMyLocationEnabled(true); LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (gps_enabled) { Criteria criteria = new Criteria(); provider = locationManager.getBestProvider(criteria, true); if (provider != null && !provider.equals("")) { locationManager.requestLocationUpdates(provider, 500, 1, GetParkingLots.this); // Get the location from the given provider location = locationManager.getLastKnownLocation(provider); } } Log.i("GetParkingLots", "Value of network_enabled and location" + network_enabled + location); if (location == null && network_enabled) { location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500, 1, GetParkingLots.this); } if (location == null && !network_enabled && !gps_enabled) { Toast.makeText(getBaseContext(), "Enable your location services", Toast.LENGTH_LONG).show(); } if (location != null) onLocationChanged(location); else { Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show(); } tv_fromTime = (TextView) findViewById(R.id.tv_fromTime); fromTimeString = Constants.dtf.format(new Date()).toString(); tv_fromTime.setText(fromTimeString); long lval = DateTimeHelpers.convertToLongFromTime(Constants.dtf.format(new Date()).toString()); Log.i("GetParkingLots", "The value of current time:" + Constants.dtf.format(new Date()).toString() + "in long is" + lval); Log.i("GetParkingLots", "The value of current time:" + lval + "in long is" + DateTimeHelpers.convertToTimeFromLong(lval)); tv_toTime = (TextView) findViewById(R.id.tv_ToTime); // Parsing the date toTimeString = Constants.dtf.format(new Date()).toString(); tv_toTime.setText(toTimeString); btnFromTime = (Button) findViewById(R.id.fromButton); btnFromTime.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Create the dialog final Dialog mDateTimeDialog = new Dialog(GetParkingLots.this); // Inflate the root layout final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater() .inflate(R.layout.date_time_dialog, null); // Grab widget instance mDateTimePicker = (DateTimePicker) mDateTimeDialogView.findViewById(R.id.DateTimePicker); mDateTimePicker.setDateChangedListener(GetParkingLots.this); // Update demo TextViews when the "OK" button is clicked ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime)) .setOnClickListener(new OnClickListener() { Calendar cal; @SuppressWarnings("deprecation") public void onClick(View v) { mDateTimePicker.clearFocus(); try { cal = new GregorianCalendar(mDateTimePicker.getYear(), Integer.parseInt(mDateTimePicker.getMonth()), mDateTimePicker.getDay(), mDateTimePicker.getHour(), mDateTimePicker.getMinute()); fromTimeString = DateTimeHelpers.dtf.format(cal.getTime()); tv_fromTime.setText(fromTimeString); } catch (Exception e) { final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this) .create(); alertDialog.setMessage("Enter a valid date"); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { alertDialog.dismiss(); } }); alertDialog.show(); } mDateTimeDialog.dismiss(); } }); // Cancel the dialog when the "Cancel" button is clicked ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog)) .setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub mDateTimeDialog.cancel(); } }); // Reset Date and Time pickers when the "Reset" button is clicked ((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime)) .setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub mDateTimePicker.reset(); } }); // Setup TimePicker // No title on the dialog window mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // Set the dialog content view mDateTimeDialog.setContentView(mDateTimeDialogView); // Display the dialog mDateTimeDialog.show(); } }); btnToTime = (Button) findViewById(R.id.toButton); btnToTime.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Create the dialog final Dialog mDateTimeDialog = new Dialog(GetParkingLots.this); // Inflate the root layout final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater() .inflate(R.layout.date_time_dialog, null); // Grab widget instance final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView .findViewById(R.id.DateTimePicker); mDateTimePicker.setDateChangedListener(GetParkingLots.this); // Update demo TextViews when the "OK" button is clicked ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime)) .setOnClickListener(new OnClickListener() { Calendar cal; @SuppressWarnings("deprecation") public void onClick(View v) { mDateTimePicker.clearFocus(); Log.i("toButton", "Value of ToString before cal" + toTimeString); try { cal = new GregorianCalendar(mDateTimePicker.getYear(), Integer.parseInt(mDateTimePicker.getMonth()), mDateTimePicker.getDay(), mDateTimePicker.getHour(), mDateTimePicker.getMinute()); toTimeString = DateTimeHelpers.dtf.format(cal.getTime()); Log.i("toButton", "Value of ToString before cal" + toTimeString); tv_toTime.setText(toTimeString); } catch (Exception e) // fixing the bug where the user doesnt enter anything in the textbox { final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this) .create(); alertDialog.setMessage("Enter a valid date"); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { alertDialog.dismiss(); } }); alertDialog.show(); } //dateTimeTo = new DateTime(mDateTimePicker.getYear(), Integer.parseInt(mDateTimePicker.getMonth()) , mDateTimePicker.getDay(), mDateTimePicker.getHour(), mDateTimePicker.getMinute()); ; mDateTimeDialog.dismiss(); } }); ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog)) .setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub mDateTimeDialog.cancel(); } }); // Reset Date and Time pickers when the "Reset" button is clicked ((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime)) .setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub mDateTimePicker.reset(); } }); // Setup TimePicker // No title on the dialog window mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // Set the dialog content view mDateTimeDialog.setContentView(mDateTimeDialogView); // Display the dialog mDateTimeDialog.show(); } }); btnGetParkingLots = (Button) findViewById(R.id.getNearByParkingLotsButton); btnGetParkingLots.setOnClickListener(new View.OnClickListener() { @SuppressWarnings("deprecation") public void onClick(View v) { et_search = (EditText) findViewById(R.id.edittextsearch); rg = (RadioGroup) findViewById(R.id.rg); checkedRbId = rg.getCheckedRadioButtonId(); Log.i("LOG_TAG: GetParkingLots", "checked radiobutton id is" + checkedRbId); if (checkedRbId == R.id.rbradius) { isRadiusIndicator = true; radius = et_search.getText().toString(); } else { isRadiusIndicator = false; zipcode = et_search.getText().toString(); } final Intent intent = new Intent(GetParkingLots.this, DisplayVacantParkingLots.class); Log.i(TAG, "Inside getNearByParkingLots"); Log.i(TAG, "Value of fromString" + fromTimeString); long lFromVal = DateTimeHelpers.convertToLongFromTime(fromTimeString); Log.i(TAG, "Value of ToString" + toTimeString); long lToVal = DateTimeHelpers.convertToLongFromTime(toTimeString); if ((lToVal - lFromVal) < Constants.thrityMinInMilliSeconds) { final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this).create(); alertDialog.setMessage("You have to park the car for at least 30 min"); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { alertDialog.dismiss(); } }); alertDialog.show(); } else { intent.putExtra(LATITUDE, latitude); intent.putExtra(LONGITUDE, longitude); intent.putExtra(FROMTIME, lFromVal); intent.putExtra(TOTIME, lToVal); intent.putExtra(RadiusOrZIPCODE, isRadiusIndicator); if (isRadiusIndicator) try { intent.putExtra(RADIUS, Double.parseDouble(radius)); startActivity(intent); } catch (Exception e) { final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this).create(); alertDialog.setMessage("Enter valid radius"); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { alertDialog.dismiss(); } }); alertDialog.show(); } else { try { intent.putExtra(ZIPCODE, Long.parseLong(zipcode)); startActivity(intent); } catch (Exception e) { final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this).create(); alertDialog.setMessage("Enter a valid Zip code"); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { alertDialog.dismiss(); } }); alertDialog.show(); } } } } }); }
From source file:at.ac.tuwien.caa.docscan.camera.LocationHandler.java
public Location getLocation() { if (mLocation != null) return mLocation; else {/*w ww . j av a2s .c o m*/ // If no location has been found yet, use the last known location as a fallback: if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { Location l1 = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); Location l2 = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (l1 != null && l2 != null) { if (l1.getAccuracy() > l2.getAccuracy()) return l1; else return l2; } else { if (l1 != null) return l1; else return l2; } } } // If the user has given no permission to access location return nothing: return null; }
From source file:com.yoval.community.chatapp.DistanceActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_distance); displayLocationSettingsRequest(getApplicationContext()); if (googleServicesAvalaible()) { //Toast.makeText(this, "Perfect", Toast.LENGTH_LONG).show(); initMap();/*from w w w . ja v a2 s . c o m*/ } else { Toast.makeText(this, "Play services problem", Toast.LENGTH_LONG).show(); } //Check for WIfi services enabled WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); if (!wifi.isWifiEnabled()) { showWifiRequest(); } CustomizedLocationListener locationListener = new CustomizedLocationListener(getApplicationContext()); locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); if (ContextCompat.checkSelfPermission(this, Manifest.permission.MAPS_RECEIVE) != PackageManager.PERMISSION_GRANTED) { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5 * 60 * 1000, 10, locationListener); } if (FirebaseAuth.getInstance().getCurrentUser() == null) { // Start sign in/sign up activity startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_REQUEST_CODE); } else { // User is already signed in. Therefore, display // a welcome Toast Toast.makeText(this, R.string.Bienvenue + " " + FirebaseAuth.getInstance().getCurrentUser().getDisplayName(), Toast.LENGTH_LONG).show(); } Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarDistance); setSupportActionBar(toolbar); SeekBar distanceBar = (SeekBar) findViewById(R.id.seekBarDistance); // make seekbar object distanceBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // TODO Auto-generated method stub TextView textViewDistance = (TextView) findViewById(R.id.textViewDistance); textViewDistance.setText(progress + " Km"); radius = progress; SaveUserInformations(radius); updateZoomMap(); } }); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.distNext); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goToDetailView(); } }); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); }
From source file:edu.cmu.cs.quiltview.RequestPullingService.java
private void getLocation() { mLocationUpdated = false;// ww w.j a v a 2s . co m /* It is said that Google Glass has built-in GPS hardware. Unfortunately, * it is not activated at this time. So GPS is not available when Glass * is not paired with a phone. During the evolution of Glass software, * sometimes it just gives you a null result for GPS location, sometimes * it raises an exception. * * In this case, we get location from Network instead, which is not as * precise, but always works. * Wenlu Hu, April 2014 */ //String locationProvider = LocationManager.GPS_PROVIDER; String locationProvider = LocationManager.NETWORK_PROVIDER; // Register the listener with the Location Manager to receive location updates try { locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener); } catch (IllegalArgumentException ex) { Log.i(LOG_TAG, "GPS provider not available"); mLocation = null; } if (mLocation == null) mLocation = locationManager.getLastKnownLocation(locationProvider); }
From source file:org.y20k.trackbook.MainActivityMapFragment.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // get activity mActivity = getActivity();//from ww w .j a v a2 s .com // action bar has options menu setHasOptionsMenu(true); // restore first start state and tracking state mFirstStart = true; mTrackerServiceRunning = false; loadTrackerServiceState(mActivity); if (savedInstanceState != null) { mFirstStart = savedInstanceState.getBoolean(INSTANCE_FIRST_START, true); } // create storage helper mStorageHelper = new StorageHelper(mActivity); // acquire reference to Location Manager mLocationManager = (LocationManager) mActivity.getSystemService(Context.LOCATION_SERVICE); // CASE 1: get saved location if possible if (savedInstanceState != null) { Location savedLocation = savedInstanceState.getParcelable(INSTANCE_CURRENT_LOCATION); // check if saved location is still current if (LocationHelper.isNewLocation(savedLocation)) { mCurrentBestLocation = savedLocation; } else { mCurrentBestLocation = null; } } // CASE 2: get last known location if no saved location or saved location is too old if (mCurrentBestLocation == null && mLocationManager.getProviders(true).size() > 0) { mCurrentBestLocation = LocationHelper.determineLastKnownLocation(mLocationManager); } // CASE 3: location services are available but unable to get location - this should not happen if (mCurrentBestLocation == null) { mCurrentBestLocation = new Location(LocationManager.NETWORK_PROVIDER); mCurrentBestLocation.setLatitude(DEFAULT_LATITUDE); mCurrentBestLocation.setLongitude(DEFAULT_LONGITUDE); } // get state of location system setting mLocationSystemSetting = LocationHelper.checkLocationSystemSetting(mActivity); // create content observer for changes in System Settings mSettingsContentObserver = new SettingsContentObserver(new Handler()); // register broadcast receiver for new WayPoints mTrackUpdatedReceiver = createTrackUpdatedReceiver(); IntentFilter trackUpdatedIntentFilter = new IntentFilter(ACTION_TRACK_UPDATED); LocalBroadcastManager.getInstance(mActivity).registerReceiver(mTrackUpdatedReceiver, trackUpdatedIntentFilter); }
From source file:com.vonglasow.michael.satstat.ui.SettingsActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); // Show the Up button in the action bar. ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); // Display the fragment as the main content. getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit(); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); // some logic to use the pre-1.7 setting KEY_PREF_UPDATE_WIFI as a // fallback if KEY_PREF_UPDATE_NETWORKS is not set if (!mSharedPreferences.contains(Const.KEY_PREF_UPDATE_NETWORKS)) { Set<String> fallbackUpdateNetworks = new HashSet<String>(); if (mSharedPreferences.getBoolean(Const.KEY_PREF_UPDATE_WIFI, false)) { fallbackUpdateNetworks.add(Const.KEY_PREF_UPDATE_NETWORKS_WIFI); }//from ww w .j a va 2s.c o m SharedPreferences.Editor spEditor = mSharedPreferences.edit(); spEditor.putStringSet(Const.KEY_PREF_UPDATE_NETWORKS, fallbackUpdateNetworks); spEditor.commit(); } // by default, show GPS and network location in map if (!mSharedPreferences.contains(Const.KEY_PREF_LOC_PROV)) { Set<String> defaultLocProvs = new HashSet<String>( Arrays.asList(new String[] { LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER })); SharedPreferences.Editor spEditor = mSharedPreferences.edit(); spEditor.putStringSet(Const.KEY_PREF_LOC_PROV, defaultLocProvs); spEditor.commit(); } }
From source file:org.odk.collect.android.activities.GeoPointMapNotDraggableActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); if (savedInstanceState != null) { mLocationCount = savedInstanceState.getInt(LOCATION_COUNT); }/*www . j ava 2 s . co m*/ try { setContentView(R.layout.geopoint_layout); } catch (NoClassDefFoundError e) { e.printStackTrace(); Toast.makeText(getBaseContext(), getString(R.string.google_play_services_error_occured), Toast.LENGTH_SHORT).show(); finish(); return; } Intent intent = getIntent(); mLocationAccuracy = GeoPointWidget.DEFAULT_LOCATION_ACCURACY; if (intent != null && intent.getExtras() != null) { if (intent.hasExtra(GeoPointWidget.LOCATION)) { double[] location = intent.getDoubleArrayExtra(GeoPointWidget.LOCATION); mLatLng = new LatLng(location[0], location[1]); } if (intent.hasExtra(GeoPointWidget.ACCURACY_THRESHOLD)) { mLocationAccuracy = intent.getDoubleExtra(GeoPointWidget.ACCURACY_THRESHOLD, GeoPointWidget.DEFAULT_LOCATION_ACCURACY); } mCaptureLocation = !intent.getBooleanExtra(GeoPointWidget.READ_ONLY, false); mRefreshLocation = mCaptureLocation; } /* Set up the map and the marker */ mMarkerOption = new MarkerOptions(); mLocationStatus = (TextView) findViewById(R.id.location_status); /*Zoom only if there's a previous location*/ if (mLatLng != null) { mLocationStatus.setVisibility(View.GONE); mMarkerOption.position(mLatLng); mRefreshLocation = false; // just show this position; don't change it... mZoomed = true; } mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // make sure we have a good location provider before continuing List<String> providers = mLocationManager.getProviders(true); for (String provider : providers) { if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) { mGPSOn = true; } if (provider.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)) { mNetworkOn = true; } } if (!mGPSOn && !mNetworkOn) { Toast.makeText(getBaseContext(), getString(R.string.provider_disabled_error), Toast.LENGTH_SHORT) .show(); finish(); } if (mGPSOn) { Location loc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (loc != null) { InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " lastKnownLocation(GPS) lat: " + loc.getLatitude() + " long: " + loc.getLongitude() + " acc: " + loc.getAccuracy()); } else { InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " lastKnownLocation(GPS) null location"); } } if (mNetworkOn) { Location loc = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (loc != null) { InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " lastKnownLocation(Network) lat: " + loc.getLatitude() + " long: " + loc.getLongitude() + " acc: " + loc.getAccuracy()); } else { InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() + " lastKnownLocation(Network) null location"); } } mAcceptLocation = (Button) findViewById(R.id.accept_location); if (mCaptureLocation) { mAcceptLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "acceptLocation", "OK"); returnLocation(); } }); } else { mAcceptLocation.setVisibility(View.GONE); } mReloadLocation = (Button) findViewById(R.id.reload_location); if (mCaptureLocation) { mReloadLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mRefreshLocation = true; mReloadLocation.setVisibility(View.GONE); mLocationStatus.setVisibility(View.VISIBLE); if (mGPSOn) { mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, GeoPointMapNotDraggableActivity.this); } if (mNetworkOn) { mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, GeoPointMapNotDraggableActivity.this); } } }); mReloadLocation.setVisibility(!mRefreshLocation ? View.VISIBLE : View.GONE); } else { mReloadLocation.setVisibility(View.GONE); } // Focuses on marked location mShowLocation = ((Button) findViewById(R.id.show_location)); mShowLocation.setVisibility(View.VISIBLE); mShowLocation.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Collect.getInstance().getActivityLogger().logInstanceAction(this, "showLocation", "onClick"); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLatLng, 16)); } }); // not clickable until we have a marker set.... mShowLocation.setClickable(false); // Menu Layer Toggle mLayers = ((Button) findViewById(R.id.layer_menu)); mLayers.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mHelper.showLayersDialog(); } }); }