Java Code Examples for android.location.LocationManager#requestSingleUpdate()

The following examples show how to use android.location.LocationManager#requestSingleUpdate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GPSTracker.java    From AsteroidOSSync with GNU General Public License v3.0 6 votes vote down vote up
public void updateLocation() {
    try {
        mLocationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_LOW);
        criteria.setSpeedRequired(false);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        String provider = mLocationManager.getBestProvider(criteria, true);
        if(provider != null) {
            mLocationManager.requestSingleUpdate(provider, this, null);
            mCanGetLocation = true;
        }
    }
    catch (SecurityException | NullPointerException e) {
        e.printStackTrace();
    }
}
 
Example 2
Source File: GeolocationTracker.java    From delion with Apache License 2.0 6 votes vote down vote up
/**
 * Requests an updated location if the last known location is older than maxAge milliseconds.
 *
 * Note: this must be called only on the UI thread.
 */
@SuppressFBWarnings("LI_LAZY_INIT_UPDATE_STATIC")
static void refreshLastKnownLocation(Context context, long maxAge) {
    ThreadUtils.assertOnUiThread();

    // We're still waiting for a location update.
    if (sListener != null) return;

    LocationManager locationManager =
            (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    if (location == null || getLocationAge(location) > maxAge) {
        String provider = LocationManager.NETWORK_PROVIDER;
        if (locationManager.isProviderEnabled(provider)) {
            sListener = new SelfCancelingListener(locationManager);
            locationManager.requestSingleUpdate(provider, sListener, null);
        }
    }
}
 
Example 3
Source File: GeolocationTracker.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
/**
 * Requests an updated location if the last known location is older than maxAge milliseconds.
 *
 * Note: this must be called only on the UI thread.
 */
@SuppressFBWarnings("LI_LAZY_INIT_UPDATE_STATIC")
static void refreshLastKnownLocation(Context context, long maxAge) {
    ThreadUtils.assertOnUiThread();

    // We're still waiting for a location update.
    if (sListener != null) return;

    LocationManager locationManager =
            (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    if (location == null || getLocationAge(location) > maxAge) {
        String provider = LocationManager.NETWORK_PROVIDER;
        if (locationManager.isProviderEnabled(provider)) {
            sListener = new SelfCancelingListener(locationManager);
            locationManager.requestSingleUpdate(provider, sListener, null);
        }
    }
}
 
Example 4
Source File: TestActivity.java    From SimpleSmsRemote with MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);

    LocationManager locationManager = (LocationManager)
            this.getSystemService(Context.LOCATION_SERVICE);

    startTime = System.currentTimeMillis();
    try {
        locationManager.requestSingleUpdate(criteria, this, null);
    } catch (SecurityException e) {
        Log.e(TAG, "permission not granted");
    }
}
 
Example 5
Source File: GeolocationTracker.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Requests an updated location if the last known location is older than maxAge milliseconds.
 *
 * Note: this must be called only on the UI thread.
 */
@SuppressFBWarnings("LI_LAZY_INIT_UPDATE_STATIC")
static void refreshLastKnownLocation(Context context, long maxAge) {
    ThreadUtils.assertOnUiThread();

    if (!hasPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)) {
        return;
    }

    // We're still waiting for a location update.
    if (sListener != null) return;

    LocationManager locationManager =
            (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    if (location == null || getLocationAge(location) > maxAge) {
        String provider = LocationManager.NETWORK_PROVIDER;
        if (locationManager.isProviderEnabled(provider)) {
            sListener = new SelfCancelingListener(locationManager);
            locationManager.requestSingleUpdate(provider, sListener, null);
        }
    }
}
 
Example 6
Source File: LocationReceiver.java    From prayer-times-android with Apache License 2.0 5 votes vote down vote up
public static void triggerUpdate(Context c) {
    if (!hasPermission(c) || !useAutoLocation())
        return;
    if (System.currentTimeMillis() - sLastLocationUpdate > 60 * 60 * 1000) {
        LocationManager lm = (LocationManager) c.getSystemService(Context.LOCATION_SERVICE);
        lm.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, getPendingIntent(c));
    }
}
 
Example 7
Source File: LocationReceiver.java    From prayer-times-android with Apache License 2.0 5 votes vote down vote up
public static void triggerUpdate(Context c) {
    if (!hasPermission(c) || !useAutoLocation())
        return;
    if (System.currentTimeMillis() - sLastLocationUpdate > 60 * 60 * 1000) {
        LocationManager lm = (LocationManager) c.getSystemService(Context.LOCATION_SERVICE);
        lm.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, getPendingIntent(c));
    }
}
 
Example 8
Source File: CapturePosition.java    From itracing2 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent)
{
    // because some customers don't like Google Play Services…
    Location bestLocation = null;
    final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    for (final String provider : locationManager.getAllProviders()) {
        final Location location = locationManager.getLastKnownLocation(provider);
        final long now = System.currentTimeMillis();
        if (location != null
                && (bestLocation == null || location.getTime() > bestLocation.getTime())
                && location.getTime() > now - MAX_AGE) {
            bestLocation = location;
        }
    }

    if (bestLocation == null) {
        final PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        locationManager.requestSingleUpdate(criteria, pendingIntent);
    }

    if (bestLocation != null) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        final String position = bestLocation.getLatitude() + "," + bestLocation.getLongitude();
        final Intent mapIntent = getMapIntent(position);

        final Notification notification = new Notification.Builder(context)
                .setContentText(context.getString(R.string.display_last_position))
                .setContentTitle(context.getString(R.string.app_name))
                .setSmallIcon(R.drawable.ic_launcher)
                .setAutoCancel(false)
                .setContentIntent(PendingIntent.getActivity(context, 0, mapIntent, PendingIntent.FLAG_UPDATE_CURRENT))
                .build();
        notificationManager.notify(NOTIFICATION_ID, notification);

        final String address = intent.getStringExtra(Devices.ADDRESS);
        Events.insert(context, NAME, address, position);
    }
}
 
Example 9
Source File: LocationReceiver.java    From beaconloc with Apache License 2.0 4 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    retryCount = intent.getIntExtra("RETRY_COUNT", 0);
    Location bestLocation = null;
    final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    for (final String provider : locationManager.getAllProviders()) {
        if (provider != null) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                Log.w(Constants.TAG, "No permissions to use GPS ");

                return;
            }
            final Location location = locationManager.getLastKnownLocation(provider);
            final long now = System.currentTimeMillis();
            if (location != null
                    && (bestLocation == null || location.getTime() > bestLocation.getTime())
                    && location.getTime() > now - MAX_AGE_TIME) {
                bestLocation = location;
            }
        }
    }

    if (bestLocation != null) {
        final String position = bestLocation.getLatitude() + "," + bestLocation.getLongitude();
        final Uri uri = Uri.parse("geo:" + position + "?z=16&q=" + position);
        final Intent mapIntent = new Intent(Intent.ACTION_VIEW, uri);

        PendingIntent notificationIntent = PendingIntent.getActivity(context, 0, mapIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationBuilder notificationBuilder = new NotificationBuilder(context);
        notificationBuilder.createNotification(context.getString(R.string.action_alarm_text_title), null,true, notificationIntent);
        notificationBuilder.setMessage(context.getString(R.string.notification_display_last_position));
        notificationBuilder.show(1);

    } else {
        if (retryCount < RETRY_COUNT_MAX) {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
            }
            retryCount++;
            intent.putExtra("RETRY_COUNT", retryCount);
            final PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                Log.w(Constants.TAG, "No permissions to use GPS ");

                return;
            }
            locationManager.requestSingleUpdate(criteria, pendingIntent);
        }
    }
}
 
Example 10
Source File: BetterWeatherExtension.java    From BetterWeather with Apache License 2.0 4 votes vote down vote up
/**
 * Requests a location update if setting is Automatic, else it will give a dummy location
 *
 * @param lm       Location Manager from {@link net.imatruck.betterweather.BetterWeatherExtension#onUpdateData(int)}
 * @param provider Provider determined in {@link net.imatruck.betterweather.BetterWeatherExtension#onUpdateData(int)}
 */
private void requestLocationUpdate(final LocationManager lm, final String provider) {
    if (provider != null && sUseCurrentLocation) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            handleMissingPermission();
            return;
        }
        final Location lastLocation = lm.getLastKnownLocation(provider);
        if (lastLocation == null ||
                (SystemClock.elapsedRealtimeNanos() - lastLocation.getElapsedRealtimeNanos())
                        >= STALE_LOCATION_NANOS) {
            LOGW(TAG, "Stale or missing last-known location; requesting single coarse location "
                    + "update. " + ((lastLocation != null) ? lastLocation.getLatitude() + ", " + lastLocation.getLongitude() : "Last location is null"));
            try {
                disableOneTimeLocationListener();
                mOneTimeLocationListenerActive = true;
                lm.requestSingleUpdate(provider, mOneTimeLocationListener, null);
                gpsFixHandler.postDelayed(new Runnable() {
                    public void run() {
                        disableOneTimeLocationListener();
                        LOGD(TAG, "We didn't get a GPS fix quick enough, we'll try again later");
                        scheduleRefresh(0);
                    }
                }, 30 * 1000);
                LOGD(TAG, "Requested single location update");
                if (lastLocation != null) {
                    new RefreshWeatherTask(lastLocation).execute();
                }
            } catch (Exception e) {
                LOGW(TAG, "RuntimeException on requestSingleUpdate. " + e.toString());
                scheduleRefresh(2);
            }
        } else {
            new RefreshWeatherTask(lastLocation).execute();
        }
    } else if (!sUseCurrentLocation) {
        LOGD(TAG, "Using set location");
        disableOneTimeLocationListener();
        Location dummyLocation = new Location(provider);
        new RefreshWeatherTask(dummyLocation).execute();
    } else {
        handleMissingPermission();
    }
}