List of usage examples for android.content Context LOCATION_SERVICE
String LOCATION_SERVICE
To view the source code for android.content Context LOCATION_SERVICE.
Click Source Link
From source file:com.facebook.react.modules.location.LocationModule.java
/** * Get the current position. This can return almost immediately if the location is cached or * request an update, which might take a while. * * @param options map containing optional arguments: timeout (millis), maximumAge (millis) and * highAccuracy (boolean)/*from ww w .j a va 2 s . c o m*/ */ @ReactMethod public void getCurrentPosition(ReadableMap options, final Callback success, Callback error) { LocationOptions locationOptions = LocationOptions.fromReactMap(options); try { LocationManager locationManager = (LocationManager) getReactApplicationContext() .getSystemService(Context.LOCATION_SERVICE); String provider = getValidProvider(locationManager, locationOptions.highAccuracy); if (provider == null) { error.invoke(PositionError.buildError(PositionError.POSITION_UNAVAILABLE, "No location provider available.")); return; } Location location = locationManager.getLastKnownLocation(provider); if (location != null && (SystemClock.currentTimeMillis() - location.getTime()) < locationOptions.maximumAge) { success.invoke(locationToMap(location)); return; } new SingleUpdateRequest(locationManager, provider, locationOptions.timeout, success, error) .invoke(location); } catch (SecurityException e) { throwLocationPermissionMissing(e); } }
From source file:com.swetha.easypark.GetParkingLots.java
@Override protected void onCreate(Bundle savedInstanceState) { if (!isGooglePlayServicesAvailable()) { finish();/* w w w . ja va 2 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:com.m2dl.mini_projet.mini_projet_android.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (screenIsLarge()) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } else {/*from w w w. ja va 2 s. co m*/ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } myPhotoMarkers = new HashMap<>(); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, this); if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { buildAlertMessageNoGps(); } else { isGPSOn = true; } coordLat = 0.0; coordLong = 0.0; FloatingActionButton fabPhoto = (FloatingActionButton) findViewById(R.id.fabPhoto); fabPhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { takePhoto(view); } }); FloatingActionButton fabTagSelect = (FloatingActionButton) findViewById(R.id.fabTagSelect); fabTagSelect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { selectTags(); } }); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); pointInteretManager = new PointInteretManager(this); // Init tag list allTags = new TreeSet<>(); selectedTags = new TreeSet<>(); }
From source file:com.nextgis.rehacompdemo.RoutingActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_routing); String sRadius = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.PREF_RADIUS, "6"); mActivationDistance = Integer.parseInt(sRadius); int routeNum = -1; Bundle extras = getIntent().getExtras(); if (extras != null) { routeNum = extras.getInt(Constants.BUNDLE_ROUTE_ID); if (getSupportActionBar() != null) getSupportActionBar().setTitle(extras.getString(Constants.BUNDLE_ROUTE_NAME)); }/*from w ww . jav a 2s .c om*/ if (routeNum == -1) return; mRoute = "route_" + routeNum; mPoints = "points_" + routeNum; mSteps = (ListView) findViewById(R.id.lv_steps); mAdapter = new StepAdapter(this, R.layout.item_step, getRouteSteps()); mSteps.setAdapter(mAdapter); mSteps.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE); mSteps.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); mSteps.requestFocusFromTouch(); mSteps.setSelection(position); } }); mMap = (MapDrawable) ((GISApplication) getApplication()).getMap(); new MapLoader().execute(); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, Constants.GPS_MIN_TIME, Constants.GPS_MIN_DIST, this); }
From source file:com.android.transmart.PlaceActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Inflate the layout setContentView(R.layout.nearby);/*from ww w . ja v a 2s . co m*/ // Get a handle to the Fragments placeListFragment = (PlaceListFragment) getSupportFragmentManager().findFragmentById(R.id.list_fragment); checkinFragment = (CheckinFragment) getSupportFragmentManager().findFragmentById(R.id.checkin_fragment); // Get references to the managers packageManager = getPackageManager(); notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // Get a reference to the Shared Preferences and a Shared Preference Editor. prefs = getSharedPreferences(LocationConstants.SHARED_PREFERENCE_FILE, Context.MODE_PRIVATE); prefsEditor = prefs.edit(); // Instantiate a SharedPreferenceSaver class based on the available platform version. // This will be used to save shared preferences sharedPreferenceSaver = PlatformSpecific.getSharedPreferenceSaver(this); // Save that we've been run once. prefsEditor.putBoolean(LocationConstants.SP_KEY_RUN_ONCE, true); sharedPreferenceSaver.savePreferences(prefsEditor, false); // Specify the Criteria to use when requesting location updates while the application is Active criteria = new Criteria(); if (LocationConstants.USE_GPS_WHEN_ACTIVITY_VISIBLE) criteria.setAccuracy(Criteria.ACCURACY_FINE); else criteria.setPowerRequirement(Criteria.POWER_LOW); // Setup the location update Pending Intents Intent activeIntent = new Intent(this, LocationChangedReceiver.class); locationListenerPendingIntent = PendingIntent.getBroadcast(this, 0, activeIntent, PendingIntent.FLAG_UPDATE_CURRENT); Intent passiveIntent = new Intent(this, PassiveLocReceiver.class); locationListenerPassivePendingIntent = PendingIntent.getBroadcast(this, 0, passiveIntent, PendingIntent.FLAG_UPDATE_CURRENT); // Instantiate a LastLocationFinder class. // This will be used to find the last known location when the application starts. lastLocationFinder = PlatformSpecific.getLastLocationFinder(this); lastLocationFinder.setChangedLocationListener(oneShotLastLocationUpdateListener); // Instantiate a Location Update Requester class based on the available platform version. // This will be used to request location updates. locationUpdateRequester = PlatformSpecific.getLocationUpdateRequester(locationManager); // Create an Intent Filter to listen for checkins newCheckinReceiverName = new ComponentName(this, NewCheckinReceiver.class); newCheckinFilter = new IntentFilter(LocationConstants.NEW_CHECKIN_ACTION); // Check to see if an Place ID has been specified in the launch Intent. // If so, we should display the details for the specified venue. if (getIntent().hasExtra(LocationConstants.EXTRA_KEY_ID)) { Intent intent = getIntent(); String key = intent.getStringExtra(LocationConstants.EXTRA_KEY_ID); if (key != null) { selectDetail(null, key); // Remove the ID from the Intent (so that a resume doesn't reselect). intent.removeExtra(LocationConstants.EXTRA_KEY_ID); setIntent(intent); } } }
From source file:cubes.compass.service.WeatherActivity.java
private void getWeatherFromCurrentLocation() { // system's LocationManager LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); // medium accuracy for weather, good for 100 - 500 meters Criteria locationCriteria = new Criteria(); locationCriteria.setAccuracy(Criteria.ACCURACY_MEDIUM); String provider = locationManager.getBestProvider(locationCriteria, true); // single location update if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return;//from ww w. j av a2 s .co m } locationManager.requestSingleUpdate(provider, this, null); }
From source file:de.grundid.plusrad.recording.RecordingService.java
@Override public void onCreate() { super.onCreate(); Log.i(TAG, "recording service create"); lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); dbAdapter = new DbAdapter(getApplicationContext()); Intent intent = new Intent(this, ActivityRecognitionIntentService.class); pendingIntentForActivityRecorgnition = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); apiClient = new GoogleApiClient.Builder(this).addApi(ActivityRecognition.API).addApi(LocationServices.API) .addConnectionCallbacks(this).addOnConnectionFailedListener(this).build(); apiClient.connect();/*from w w w .j ava 2s . c o m*/ broadcastManager = LocalBroadcastManager.getInstance(getApplicationContext()); broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i("PRAD", "activity update: " + intent.getStringExtra("activityName")); activityType = intent.getIntExtra("activityType", DetectedActivity.UNKNOWN); } }; }
From source file:com.example.frodo.MapActivity.java
/** * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly * installed) and the map has not already been instantiated.. This will ensure that we only ever * call {@link #setUpMap()} once when {@link #mMap} is not null. * <p>/*from w w w . j ava 2s . c om*/ * If it isn't installed {@link SupportMapFragment} (and * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to * install/update the Google Play services APK on their device. * <p> * A user can return to this FragmentActivity after following the prompt and correctly * installing/updating/enabling the Google Play services. Since the FragmentActivity may not have been * completely destroyed during this process (it is likely that it would only be stopped or * paused), {@link #onCreate(Bundle)} may not be called again so we should call this method in * {@link #onResume()} to guarantee that it will be called. */ private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. fMapfragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)); mMap = fMapfragment.getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { setUpMap(); } } mapInformation = (TextView) findViewById(R.id.mapInformation); mapInformation.setText(R.string.pagetext_location_finding); // Acquire a reference to the system Location Manager LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // get location using same provider criteria as we use for the maps String provider = new CurrentLocationProvider(context).getProvider(); Location currentLocation = locationManager.getLastKnownLocation(provider); mapInformation.setText(R.string.pagetext_loading_quests); String lookupId = params.getString("ID"); getQuests(currentLocation, lookupId); }