List of usage examples for android.location LocationManager requestLocationUpdates
@UnsupportedAppUsage private void requestLocationUpdates(LocationRequest request, LocationListener listener, Looper looper, PendingIntent intent)
From source file:com.example.angel.parkpanda.MainActivity.java
public Location getLocation() { Location location = null;/* w w w. j a v a 2 s . c o m*/ LocationManager locationManager; boolean isGPSEnabled = false; boolean isNetworkEnabled = false; final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; double longitude, latitude; long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; try { locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); // getting network status isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (!isGPSEnabled && !isNetworkEnabled) { // no network provider is enabled } else { if (isNetworkEnabled) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return null; } locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); if (locationManager != null) { location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } // if GPS Enabled get lat/long using GPS Services if (isGPSEnabled) { if (location == null) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); if (locationManager != null) { location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } } } } catch (Exception e) { Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show(); } return location; }
From source file:com.mparticle.MParticle.java
/** * Enables location tracking given a provider and update frequency criteria. The provider must * be available and the correct permissions must have been requested within your application's manifest XML file. * * @param provider the provider key//from w ww .ja va 2s . co m * @param minTime the minimum time (in milliseconds) to trigger an update * @param minDistance the minimum distance (in meters) to trigger an update */ public void enableLocationTracking(String provider, long minTime, long minDistance) { if (mConfigManager.isEnabled()) { try { LocationManager locationManager = (LocationManager) mAppContext .getSystemService(Context.LOCATION_SERVICE); if (!locationManager.isProviderEnabled(provider)) { ConfigManager.log(LogLevel.ERROR, "That requested location provider is not available"); return; } if (null == mLocationListener) { mLocationListener = new MPLocationListener(this); } else { // clear the location listener, so it can be added again locationManager.removeUpdates(mLocationListener); } locationManager.requestLocationUpdates(provider, minTime, minDistance, mLocationListener); SharedPreferences.Editor editor = mPreferences.edit(); editor.putString(PrefKeys.LOCATION_PROVIDER, provider).putLong(PrefKeys.LOCATION_MINTIME, minTime) .putLong(PrefKeys.LOCATION_MINDISTANCE, minDistance).apply(); } catch (SecurityException e) { ConfigManager.log(LogLevel.ERROR, "The app must require the appropriate permissions to track location using this provider"); } } }
From source file:at.ac.uniklu.mobile.sportal.service.MutingService.java
private void mute(int alarmId) { Log.d(TAG, "mute()"); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); if (Preferences.getLocationStatus(preferences) == Preferences.LOCATION_STATUS_WAITING) { Log.d(TAG, "mute() blocked - waiting for a location update"); return;/*w w w . java 2 s. c om*/ } // check if phone is already muted by the user AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); boolean isPhoneAlreadyMuted = audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL && !Preferences.isMutingPeriod(preferences); if (isPhoneAlreadyMuted) { Log.d(TAG, "phone is already muted, scheduling next mute"); scheduleMute(true); return; } // load the current period from the db MutingPeriod mutingPeriod = null; Log.d(TAG, "muting period id: " + alarmId); if (DEBUG_WITH_FAKE_ALARMS) { mutingPeriod = new MutingPeriod(); mutingPeriod.setId(-1); mutingPeriod.setBegin(System.currentTimeMillis()); mutingPeriod.setEnd(mutingPeriod.getBegin() + 10000); mutingPeriod.setName("Fakeevent"); } else { mutingPeriod = Studentportal.getStudentPortalDB().mutingPeriods_getPeriod(alarmId); } // check if phone is located at university notifyUser(Studentportal.NOTIFICATION_MS_INFO, true, mutingPeriod.getName(), mutingPeriod.getName(), getString(R.string.automute_notification_course_started_locating)); boolean isPhoneLocationKnown = false; boolean isPhoneLocatedAtUniversity = false; String locationSource = null; WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); if (wifiManager.isWifiEnabled()) { ScanResult scanResult = MutingUtils.findMutingWifiNetwork(wifiManager.getScanResults()); if (scanResult != null) { Log.d(TAG, "phone located by wifi: " + scanResult.SSID); isPhoneLocationKnown = true; isPhoneLocatedAtUniversity = true; locationSource = "wifi (" + scanResult.SSID + ")"; } } if (!isPhoneLocationKnown) { // phone location could not be determined by wifi, trying network location instead... LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { Intent locationIntent = new Intent("at.ac.uniklu.mobile.sportal.LOCATION_UPDATE") .putExtra(EXTRA_ALARM_ID, alarmId); PendingIntent pendingLocationIntent = PendingIntent.getBroadcast(this, 0, locationIntent, PendingIntent.FLAG_UPDATE_CURRENT); // remove the location receiver (so it doesn't get registered multiple times [could also happen on overlapping mute() calls) locationManager.removeUpdates(pendingLocationIntent); if (Preferences.getLocationStatus(preferences) == Preferences.LOCATION_STATUS_RECEIVED) { isPhoneLocationKnown = true; pendingLocationIntent.cancel(); Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location == null) { Log.d(TAG, "location received but still null"); } else { MutingRegion mutingRegion = MutingUtils.findOverlappingMutingRegion(location); if (mutingRegion != null) { Log.d(TAG, "phone located by network @ " + mutingRegion.getName()); isPhoneLocatedAtUniversity = true; locationSource = "location (" + mutingRegion.getName() + ")"; } } } else { Log.d(TAG, "trying to locate the phone by network..."); // wait for a location update Preferences.setLocationStatus(preferences, Preferences.LOCATION_STATUS_WAITING); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, pendingLocationIntent); return; // exit method - it will be re-called from the location broadcast receiver on a location update } } } boolean isAlwaysMuteEnabled = Preferences.isAutomuteWithoutLocation(this, preferences); if (isPhoneLocationKnown) { if (!isPhoneLocatedAtUniversity) { Log.d(TAG, "phone is not located at university, scheduling next mute"); scheduleMute(true); removeNotification(Studentportal.NOTIFICATION_MS_INFO); return; } } else { Log.d(TAG, "phone cannot be located"); if (!isAlwaysMuteEnabled) { Log.d(TAG, "alwaysmute is disabled, scheduling next mute"); Preferences.setLocationStatus(preferences, Preferences.LOCATION_STATUS_NONE); scheduleMute(true); removeNotification(Studentportal.NOTIFICATION_MS_INFO); return; } } // only turn the ringtone off if we aren't currently in a muting period. // if we are in a muting period the ringtone is already muted and the request should be ignored, // else rintoneTurnOn() won't turn the ringtone back on because ringtone override will be set to true if (!Preferences.isMutingPeriod(preferences)) { MutingUtils.ringtoneTurnOff(this); } // persist that from now on the phone is in a muting period Preferences.setMutingPeriod(preferences, true); // inform user via a notification that a course has started and the phone has been muted notifyUser(Studentportal.NOTIFICATION_MS_INFO, true, mutingPeriod.getName(), mutingPeriod.getName(), getString(R.string.automute_notification_course_muted)); final boolean isPhoneLocationKnownAnalytics = isPhoneLocationKnown; final String locationSourceAnalytics = locationSource; Analytics.onEvent(Analytics.EVENT_MUTINGSERVICE_MUTE, "isPhoneLocationKnown", isPhoneLocationKnownAnalytics + "", "locationSource", locationSourceAnalytics); scheduleUnmute(mutingPeriod.getEnd()); }
From source file:pandroid.agent.PandroidAgentListener.java
private void gpsLocation() { // Starts with GPS, if no GPS then gets network location // /*from w w w. j a v a2 s . com*/ LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); List<String> providers = lm.getProviders(true); Log.d("PANDROID providers count", "" + providers.size()); /* Loop over the array backwards, and if you get an accurate location, then break out the loop*/ Location loc = null; for (int i = providers.size() - 1; i >= 0; i--) { Log.d("PANDROID providers", providers.get(i)); loc = lm.getLastKnownLocation(providers.get(i)); if (loc != null) break; } if (loc != null) { Log.d("PANDROID", "loc != null"); //if(latitude != loc.getLatitude() || longitude != loc.getLongitude()) { lastGpsContactDateTime = getHumanDateTime(-1); //`} Log.d("LATITUDE", Double.valueOf(loc.getLatitude()).toString()); Log.d("LONGITUDE", Double.valueOf(loc.getLongitude()).toString()); putSharedData("PANDROID_DATA", "latitude", Double.valueOf(loc.getLatitude()).toString(), "float"); putSharedData("PANDROID_DATA", "longitude", Double.valueOf(loc.getLongitude()).toString(), "float"); } Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); criteria.setPowerRequirement(Criteria.POWER_LOW); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setCostAllowed(true); String bestProvider = lm.getBestProvider(criteria, true); // If not provider found, abort GPS retrieving if (bestProvider == null) { Log.e("LOCATION", "No location provider found!"); return; } lm.requestLocationUpdates(bestProvider, Core.interval, 15, new LocationListener() { public void onLocationChanged(Location location) { Log.d("Best latitude", Double.valueOf(location.getLatitude()).toString()); putSharedData("PANDROID_DATA", "latitude", Double.valueOf(location.getLatitude()).toString(), "float"); Log.d("Best longitude", Double.valueOf(location.getLongitude()).toString()); putSharedData("PANDROID_DATA", "longitude", Double.valueOf(location.getLongitude()).toString(), "float"); } public void onStatusChanged(String s, int i, Bundle bundle) { } public void onProviderEnabled(String s) { // try switching to a different provider } public void onProviderDisabled(String s) { putSharedData("PANDROID_DATA", "enabled_location_provider", "disabled", "string"); } }); //} }
From source file:com.coincide.alphafitness.ui.Fragment_Main.java
@Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { // final View v = inflater.inflate(R.layout.fragment_overview, null); View v = null;/* w w w. ja v a2s .c om*/ v = inflater.inflate(R.layout.fragment_main, container, false); // stepsView = (TextView) v.findViewById(R.id.steps); // totalView = (TextView) v.findViewById(R.id.total); totalView = (TextView) v.findViewById(R.id.tv_distance); tv_avg = (TextView) v.findViewById(R.id.tv_avg); tv_max = (TextView) v.findViewById(R.id.tv_max); tv_min = (TextView) v.findViewById(R.id.tv_min); // averageView = (TextView) v.findViewById(R.id.average); /* pg = (PieChart) v.findViewById(R.id.graph); // slice for the steps taken today sliceCurrent = new PieModel("", 0, Color.parseColor("#99CC00")); pg.addPieSlice(sliceCurrent); // slice for the "missing" steps until reaching the goal sliceGoal = new PieModel("", Fragment_Settings.DEFAULT_GOAL, Color.parseColor("#CC0000")); pg.addPieSlice(sliceGoal); pg.setOnClickListener(new OnClickListener() { @Override public void onClick(final View view) { showSteps = !showSteps; stepsDistanceChanged(); } }); pg.setDrawValueInPie(false); pg.setUsePieRotation(true); pg.startAnimation(); */ /* * MainActivity * */ // Always cast your custom Toolbar here, and set it as the ActionBar. Toolbar tb = (Toolbar) v.findViewById(R.id.toolbar); ((AppCompatActivity) getActivity()).setSupportActionBar(tb); TextView tv_tb_center = (TextView) tb.findViewById(R.id.tv_tb_center); tv_tb_center.setText("ALPHA FITNESS"); /* ImageButton imgbtn_cart = (ImageButton) tb.findViewById(R.id.imgbtn_cart); imgbtn_cart.setVisibility(View.GONE);*/ tb.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().onBackPressed(); } }); // Get the ActionBar here to configure the way it behaves. final ActionBar ab = ((AppCompatActivity) getActivity()).getSupportActionBar(); //ab.setHomeAsUpIndicator(R.drawable.ic_menu); // set a custom icon for the default home button ab.setDisplayShowHomeEnabled(false); // show or hide the default home button ab.setDisplayHomeAsUpEnabled(false); ab.setDisplayShowCustomEnabled(false); // enable overriding the default toolbar layout ab.setDisplayShowTitleEnabled(false); // disable the default title element here (for centered title) tv_duration = (TextView) v.findViewById(R.id.tv_duration); startButton = (Button) v.findViewById(R.id.btn_start); if (isButtonStartPressed) { startButton.setBackgroundResource(R.drawable.btn_stop_states); startButton.setText(R.string.btn_stop); try { SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE); sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER), SensorManager.SENSOR_DELAY_UI, 0); } catch (Exception e) { e.printStackTrace(); } } else { try { SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE); sm.unregisterListener(this); } catch (Exception e) { e.printStackTrace(); } } startButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { onSWatchStart(); } }); iv_profile = (ImageView) v.findViewById(R.id.iv_profile); iv_profile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Database db = Database.getInstance(getActivity()); tot_workouts = db.getTotWorkouts(); tot_workTime = db.getWorkTime(); Log.e("Tot Work time", tot_workTime + ""); // int seconds = (int) (tot_workTime / 1000) % 60; // int minutes = (int) ((tot_workTime / (1000 * 60)) % 60); long millis = tot_workTime * 100; // obtained from StopWatch long hours = (millis / 1000) / 3600; long minutes = (millis / 1000) / 60; long seconds = (millis / 1000) % 60; db.close(); Intent i = new Intent(getActivity(), ProfileActivity.class); i.putExtra("avg_distance", avg_distance + ""); i.putExtra("all_distance", all_distance + ""); i.putExtra("avg_time", tv_duration.getText().toString()); i.putExtra("all_time", tv_duration.getText().toString()); i.putExtra("avg_calories", avg_calories + ""); i.putExtra("all_calories", all_calories + ""); i.putExtra("tot_workouts", tot_workouts + ""); i.putExtra("avg_workouts", tot_workouts + ""); i.putExtra("tot_workTime", hours + " hrs " + minutes + " min " + seconds + " sec"); startActivity(i); } }); // Getting Google Play availability status int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity().getBaseContext()); if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available int requestCode = 10; Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getActivity(), requestCode); dialog.show(); } else { // Google Play Services are available // Initializing mMarkerPoints = new ArrayList<LatLng>(); // Getting reference to SupportMapFragment of the activity_main // SupportMapFragment fm = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map); MapFragment fm = (MapFragment) getActivity().getFragmentManager().findFragmentById(R.id.map); // Getting Map for the SupportMapFragment mGoogleMap = fm.getMap(); // Enable MyLocation Button in the Map mGoogleMap.setMyLocationEnabled(true); // Getting LocationManager object from System Service LOCATION_SERVICE LocationManager locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE); // Creating a criteria object to retrieve provider Criteria criteria = new Criteria(); // Getting the name of the best provider String provider = locationManager.getBestProvider(criteria, true); // Getting Current Location From GPS Location location; if (provider != null) { if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return null; } location = locationManager.getLastKnownLocation(provider); locationManager.requestLocationUpdates(provider, 20000, 0, this); } else { location = new Location(""); location.setLatitude(0.0d);//your coords of course location.setLongitude(0.0d); } if (location != null) { onLocationChanged(location); } // Setting onclick event listener for the map mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng point) { // Already map contain destination location if (mMarkerPoints.size() > 1) { FragmentManager fm = getActivity().getSupportFragmentManager(); mMarkerPoints.clear(); mGoogleMap.clear(); LatLng startPoint = new LatLng(mLatitude, mLongitude); drawMarker(startPoint); } drawMarker(point); // Checks, whether start and end locations are captured if (mMarkerPoints.size() >= 2) { LatLng origin = mMarkerPoints.get(0); LatLng dest = mMarkerPoints.get(1); // Getting URL to the Google Directions API String url = getDirectionsUrl(origin, dest); DownloadTask downloadTask = new DownloadTask(); // Start downloading json data from Google Directions API downloadTask.execute(url); } } }); fixedCentreoption = new MarkerOptions(); mGoogleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() { @Override public void onCameraChange(CameraPosition position) { // TODO Auto-generated method stub // Get the center of the Map. mGoogleMap.clear(); LatLng centerOfMap = mGoogleMap.getCameraPosition().target; // Update your Marker's position to the center of the Map. fixedCentreoption.position(centerOfMap); // mGoogleMap.addMarker(fixedCentreoption); // drawMarker(centerOfMap); LatLng origin = new LatLng(0.0d, 0.0d); ; if (mMarkerPoints.size() > 0) { origin = mMarkerPoints.get(0); } // LatLng dest = mMarkerPoints.get(1); LatLng dest = centerOfMap; // Getting URL to the Google Directions API String url = getDirectionsUrl(origin, dest); DownloadTask downloadTask = new DownloadTask(); // Start downloading json data from Google Directions API downloadTask.execute(url); GPSTracker gpsTracker = new GPSTracker(getActivity().getApplicationContext()); // String Addrs = gpsTracker.location(); Addrs = gpsTracker.locationBasedOnLatlng(centerOfMap); // Toast.makeText(getApplicationContext(), Addrs, Toast.LENGTH_LONG).show(); } }); } SharedPreferences sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); mBodyWeight = Float.parseFloat(sharedpreferences.getString(sp_weight, "50")); return v; }
From source file:com.caju.uheer.app.services.infrastructure.ContactablesLoaderCallbacks.java
@Override public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) { final ArrayList<String> infoAndName = new ArrayList<String>(); try {/* w w w . j a v a2s. c o m*/ for (int i = 0; i < usersFound.length(); i++) { infoAndName.add(usersFound.getJSONObject(i).getString("name")); } } catch (JSONException e) { e.printStackTrace(); } LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { Location geoPointLocation = new Location("geoPoint"); try { infoAndName.clear(); for (int i = 0; i < usersFound.length(); i++) { String appendedText = ""; if (!usersFound.getJSONObject(i).has("channel")) { geoPointLocation.setLongitude(usersFound.getJSONObject(i).getDouble("lon")); geoPointLocation.setLatitude(usersFound.getJSONObject(i).getDouble("lat")); float distance = location.distanceTo(geoPointLocation) / 1000; appendedText = String.format("%.1f", distance) + "Km"; } else { appendedText = usersFound.getJSONObject(i).getString("channel"); } infoAndName.add(appendedText + usersFound.getJSONObject(i).getString("name")); Log.e("infoandname", infoAndName.toString() + infoAndName.get(0) + infoAndName.get(1)); Toast.makeText(mContext, infoAndName.toString() + infoAndName.get(0) + infoAndName.get(1), Toast.LENGTH_LONG).show(); // infoAndName tem a informacao de distancia ou canal e o nome. Precisa editar //essa parte de baixo pra usar o infoAndName. ArrayList<String> friendsEmails = new ArrayList<>(); friendsEmails.addAll(infoAndName); friendsEmails = new ArrayList<>(); for (ArrayList<String> array : ServerInformation.getAllActiveListeners()) { friendsEmails.addAll(array); while (friendsEmails.contains(connectedEmail)) friendsEmails.remove(connectedEmail); } EmailListAdapter listAdapter = new EmailListAdapter(mContext, R.layout.adapter_email_list, friendsEmails); ListView emails = (ListView) ((Activity) mContext) .findViewById(R.id.gps_friends_from_drawer); emails.setAdapter(listAdapter); } } catch (JSONException e) { e.printStackTrace(); } } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } }; // Minimum of 2 minutes between checks (120000 milisecs). locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 120000, 0, locationListener); }