Java Code Examples for android.location.LocationManager#NETWORK_PROVIDER

The following examples show how to use android.location.LocationManager#NETWORK_PROVIDER . 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: LocationUpdatesProvider.java    From PrivacyStreams with Apache License 2.0 6 votes vote down vote up
@Override
protected void provide() {
    Looper.prepare();
    locationManager = (LocationManager) this.getContext().getSystemService(Context.LOCATION_SERVICE);
    locationListener = new MyLocationListener();

    long minTime = this.interval;
    float minDistance = 0;
    String provider;
    if (Geolocation.LEVEL_EXACT.equals(level)) {
        provider = LocationManager.GPS_PROVIDER;
    }
    else {
        provider = LocationManager.NETWORK_PROVIDER;
    }
    locationManager.requestLocationUpdates(provider, minTime, minDistance, locationListener);
    Looper.loop();
}
 
Example 2
Source File: LocationModule.java    From DexKnifePlugin with Apache License 2.0 6 votes vote down vote up
public String getProvider(Context context) {
    if (context == null) {
        return null;
    }

    getLocationManager(context);
    if (null == mLM) {
        return null;
    }

    String strProvider = null;

    if (!mLM.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
            && !mLM.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        return null;
    }

    if (mLM.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        strProvider = LocationManager.NETWORK_PROVIDER;

    } else if (mLM.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        strProvider = LocationManager.GPS_PROVIDER;
    }

    return strProvider;
}
 
Example 3
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 4
Source File: LocationUtils.java    From iot-starter-for-android with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Enable location services
 */
public void connect() {
    Log.d(TAG, ".connect() entered");

    // Check if location provider is enabled
    String locationProvider = LocationManager.NETWORK_PROVIDER;
    if (!locationManager.isProviderEnabled(locationProvider)) {
        Log.d(TAG, "Location provider not enabled.");
        app.setCurrentLocation(null);
        return;
    }

    // register for location updates, if location provider and permission are available
    String bestProvider = locationManager.getBestProvider(criteria, false);
    if (bestProvider != null) {
        locationManager.requestLocationUpdates(bestProvider, Constants.LOCATION_MIN_TIME, Constants.LOCATION_MIN_DISTANCE, this);
        app.setCurrentLocation(locationManager.getLastKnownLocation(locationProvider));
    }
}
 
Example 5
Source File: LocationService.java    From privatelocation with GNU General Public License v3.0 6 votes vote down vote up
private void pushLocation(Intent intent) {
    try {
        if (intent.hasExtra("lat") && intent.hasExtra("lng") ) {
            double lat = intent.getDoubleExtra("lat", 45);
            double lng = intent.getDoubleExtra("lng", 45);

            mockNetwork = new LocationProvider(LocationManager.NETWORK_PROVIDER, context);
            mockGps = new LocationProvider(LocationManager.GPS_PROVIDER, context);

            mockNetwork.pushLocation(lat, lng);
            mockGps.pushLocation(lat, lng);

            if(sharedPreferences.getBoolean("RANDOMIZE_LOCATION", false)) {
                randomize();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 6
Source File: LocationUtil.java    From android_maplib with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static boolean isProviderEnabled(
        Context context,
        String provider,
        boolean isTracks)
{
    int currentProvider = 0;

    switch (provider) {
        case LocationManager.GPS_PROVIDER:
            currentProvider = GpsEventSource.GPS_PROVIDER;
            break;
        case LocationManager.NETWORK_PROVIDER:
            currentProvider = GpsEventSource.NETWORK_PROVIDER;
            break;
    }

    String tracks = SettingsConstants.KEY_PREF_TRACKS_SOURCE;
    String location = SettingsConstants.KEY_PREF_LOCATION_SOURCE;
    String preferenceKey = isTracks ? tracks : location;
    String preferences = context.getPackageName() + "_preferences";
    SharedPreferences sharedPreferences = context.getSharedPreferences(preferences, MODE_MULTI_PROCESS);
    String value = sharedPreferences.getString(preferenceKey, "1");
    int providers = value != null ? Integer.parseInt(value) : 1;
    return 0 != (providers & currentProvider);
}
 
Example 7
Source File: EditMicroBlogLocationClickListener.java    From YiBo with Apache License 2.0 5 votes vote down vote up
public void registerListener() {
	String provider;
	if (isFineLocation) {
		Toast.makeText(context, R.string.msg_fine_location, Toast.LENGTH_SHORT).show();
		return;
	}
	locationManager.removeUpdates(listener);
	if (isCoarseLocation) {
		provider = LocationManager.GPS_PROVIDER;
	} else {
		provider = LocationManager.NETWORK_PROVIDER;
	}

       try {
		locationManager.requestLocationUpdates(provider, 2000, 0, listener);
        Location location = locationManager.getLastKnownLocation(provider);
        if (location != null) {
        	geoLocation = new GeoLocation(location.getLatitude(), location.getLongitude());
        	context.setGeoLocation(geoLocation);
            if (Logger.isDebug()) {
            	Toast.makeText(context, location.getProvider() + " last known-->" + location.getLatitude() + ":" + location.getLongitude(), Toast.LENGTH_LONG).show();
            }
        }
       } catch(Exception e) {
       	if (provider.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)) {
			isCoarseLocation = true;
			registerListener();
		}
	}
}
 
Example 8
Source File: LocationUtils.java    From iot-starter-for-android with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Disable location services
 */
public void disconnect() {
    Log.d(TAG, ".disconnect() entered");

    String locationProvider = LocationManager.NETWORK_PROVIDER;
    if (locationManager.isProviderEnabled(locationProvider)) {
        locationManager.removeUpdates(this);
    }
}
 
Example 9
Source File: MainActivity.java    From FakeTraveler with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Apply a mocked location, and start an alarm to keep doing it if howManyTimes is > 1
 * This method is called when "Apply" button is pressed.
 */
protected static void applyLocation() {
    if (latIsEmpty() || lngIsEmpty()) {
        toast(context.getResources().getString(R.string.MainActivity_NoLatLong));
        return;
    }

    lat = Double.parseDouble(editTextLat.getText().toString());
    lng = Double.parseDouble(editTextLng.getText().toString());

    toast(context.getResources().getString(R.string.MainActivity_MockApplied));

    endTime = System.currentTimeMillis() + (howManyTimes - 1) * timeInterval * 1000;
    editor.putLong("endTime", endTime);
    editor.commit();

    changeButtonToStop();
    
    try {
        mockNetwork = new MockLocationProvider(LocationManager.NETWORK_PROVIDER, context);
        mockGps = new MockLocationProvider(LocationManager.GPS_PROVIDER, context);
    } catch (SecurityException e) {
        e.printStackTrace();
        MainActivity.toast(context.getResources().getString(R.string.ApplyMockBroadRec_MockNotApplied));
        stopMockingLocation();
        return;
    }

    exec(lat, lng);

    if (!hasEnded()) {
        toast(context.getResources().getString(R.string.MainActivity_MockLocRunning));
        setAlarm(timeInterval);
    } else {
        stopMockingLocation();
    }
}
 
Example 10
Source File: CameraMetadataNative.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static String translateProcessToLocationProvider(final String process) {
    if (process == null) {
        return null;
    }
    switch(process) {
        case GPS_PROCESS:
            return LocationManager.GPS_PROVIDER;
        case CELLID_PROCESS:
            return LocationManager.NETWORK_PROVIDER;
        default:
            return null;
    }
}
 
Example 11
Source File: LocationManagerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private String pickBest(List<String> providers) {
    if (providers.contains(LocationManager.GPS_PROVIDER)) {
        return LocationManager.GPS_PROVIDER;
    } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
        return LocationManager.NETWORK_PROVIDER;
    } else {
        return providers.get(0);
    }
}
 
Example 12
Source File: RNLocationModule.java    From react-native-gps with MIT License 5 votes vote down vote up
@Nullable
private static String getValidProvider(LocationManager locationManager, boolean highAccuracy) {
  String provider =
    highAccuracy ? LocationManager.GPS_PROVIDER : LocationManager.NETWORK_PROVIDER;
  if (!locationManager.isProviderEnabled(provider)) {
    provider = provider.equals(LocationManager.GPS_PROVIDER)
      ? LocationManager.NETWORK_PROVIDER
      : LocationManager.GPS_PROVIDER;
    if (!locationManager.isProviderEnabled(provider)) {
      return null;
    }
  }
  return provider;
}
 
Example 13
Source File: LocationManagerApi.java    From patrol-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void createLocationRequest(int type) {
    switch (type) {

        case LocationApi.LOW_ACCURACY_LOCATION:
            MIN_TIME_TO_UPDATE = 30 * 1000; //0,5 min
            provider = LocationManager.NETWORK_PROVIDER;
            break;

        case LocationApi.HIGH_ACCURACY_LOCATION:
            MIN_TIME_TO_UPDATE = 2000; // 2 sec
            provider = LocationManager.GPS_PROVIDER;
            break;
    }
}
 
Example 14
Source File: Util.java    From snowplow-android-tracker with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the location of the android
 * device.
 *
 * @param context the android context
 * @return the phones Location
 */
public static Location getLastKnownLocation(Context context) {
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    Location location = null;

    try {
        String locationProvider = null;
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            locationProvider = LocationManager.GPS_PROVIDER;
        } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            locationProvider = LocationManager.NETWORK_PROVIDER;
        } else {
            List<String> locationProviders = locationManager.getProviders(true);
            if (locationProviders.size() > 0) {
                locationProvider = locationProviders.get(0);
            }
        }

        if (locationProvider != null && !locationProvider.equals("")) {
            location = locationManager.getLastKnownLocation(locationProvider);
        }
    } catch (SecurityException ex) {
        Logger.e(TAG, "Exception occurred when retrieving location: %s", ex.toString());
    }

    return location;
}
 
Example 15
Source File: TrackerService.java    From android_maplibui with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    String targetActivity = "";

    if (intent != null) {
        targetActivity = intent.getStringExtra(ConstantsUI.TARGET_CLASS);
        String action = intent.getAction();

        if (action != null && !TextUtils.isEmpty(action)) {
            switch (action) {
                case ACTION_SYNC:
                    if (mIsRunning || mLocationSenderThread != null)
                        return START_STICKY;

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        int res = R.string.sync_started;
                        String title = getString(res);
                        NotificationCompat.Builder builder = createBuilder(this, res);
                        builder.setSmallIcon(mSmallIcon)
                                .setLargeIcon(mLargeIcon)
                                .setTicker(title)
                                .setWhen(System.currentTimeMillis())
                                .setAutoCancel(false)
                                .setContentTitle(title)
                                .setContentText(title)
                                .setOngoing(true);

                        startForeground(TRACK_NOTIFICATION_ID, builder.build());
                    }

                    mLocationSenderThread = createLocationSenderThread(500L);
                    mLocationSenderThread.start();
                    return START_NOT_STICKY;
                case ACTION_STOP:
                    removeNotification();
                    stopSelf();
                    return START_NOT_STICKY;
                case ACTION_SPLIT:
                    stopTrack();
                    startTrack();
                    addNotification();
                    return START_STICKY;
            }
        }
    }

    if (!mIsRunning) {
        if (!PermissionUtil.hasLocationPermissions(this)) {
            stopForeground(true);
            stopSelf();
            return START_NOT_STICKY;
        }

        mLocationManager.addGpsStatusListener(this);

        String time = SettingsConstants.KEY_PREF_TRACKS_MIN_TIME;
        String distance = SettingsConstants.KEY_PREF_TRACKS_MIN_DISTANCE;
        String minTimeStr = mSharedPreferences.getString(time, "2");
        String minDistanceStr = mSharedPreferences.getString(distance, "10");
        long minTime = Long.parseLong(minTimeStr) * 1000;
        float minDistance = Float.parseFloat(minDistanceStr);

        String provider = LocationManager.GPS_PROVIDER;
        if (mLocationManager.getAllProviders().contains(provider)) {
            mLocationManager.requestLocationUpdates(provider, minTime, minDistance, this);

            if (Constants.DEBUG_MODE)
                Log.d(Constants.TAG, "Tracker service request location updates for " + provider);
        }

        provider = LocationManager.NETWORK_PROVIDER;
        if (mLocationManager.getAllProviders().contains(provider)) {
            mLocationManager.requestLocationUpdates(provider, minTime, minDistance, this);

            if (Constants.DEBUG_MODE)
                Log.d(Constants.TAG, "Tracker service request location updates for " + provider);
        }

        NotificationHelper.showLocationInfo(this);

        // there are no tracks or last track correctly ended
        if (mSharedPreferencesTemp.getString(TRACK_URI, null) == null) {
            startTrack();
            mSharedPreferencesTemp.edit().putString(ConstantsUI.TARGET_CLASS, targetActivity).apply();
        } else {
            // looks like service was killed, restore data
            restoreData();
            targetActivity = mSharedPreferencesTemp.getString(ConstantsUI.TARGET_CLASS, "");
        }

        mLocationSenderThread = createLocationSenderThread(minTime);
        mLocationSenderThread.start();

        initTargetIntent(targetActivity);
        addNotification();
    }

    return START_STICKY;
}
 
Example 16
Source File: BetterWeatherExtension.java    From BetterWeather with Apache License 2.0 4 votes vote down vote up
/**
 * Starts the update process, will verify the reason before continuing
 *
 * @param reason Update reason, provided by DashClock or this app
 */
@Override
protected void onUpdateData(int reason) {

    LOGD(TAG, "Update reason: " + getReasonText(reason));

    // Whenever updating, set sLang to Yahoo's format(en-US, not en_US)
    // If sLang is set in elsewhere, and user changes phone's locale
    // without entering BW setting menu, then Yahoo's place name in widget
    // may be in wrong locale.
    Locale current = getResources().getConfiguration().locale;
    YahooPlacesAPIClient.sLang = current.getLanguage() + "-" + current.getCountry();

    if (reason != UPDATE_REASON_USER_REQUESTED &&
            reason != UPDATE_REASON_SETTINGS_CHANGED &&
            reason != UPDATE_REASON_INITIAL &&
            reason != UPDATE_REASON_INTERVAL_TOO_BIG) {
        LOGD(TAG, "Skipping update");
        if ((System.currentTimeMillis() - lastUpdateTime > (sRefreshInterval * 1000 * 60)) && sRefreshInterval > 0)
            onUpdateData(UPDATE_REASON_INTERVAL_TOO_BIG);

        return;
    }

    LOGD(TAG, "Updating data");

    if (sPebbleEnable) {
        LOGD(TAG, "Registered Pebble Data Receiver");
        Pebble.registerPebbleDataReceived(getApplicationContext());
    }

    getCurrentPreferences();

    NetworkInfo ni = ((ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
    if (ni == null || !ni.isConnected()) {
        LOGD(TAG, "No internet connection detected, scheduling refresh in 5 minutes");
        scheduleRefresh(5);
        return;
    }

    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    String provider;
    if (sUseOnlyNetworkLocation)
        provider = LocationManager.NETWORK_PROVIDER;
    else
        provider = lm.getBestProvider(sLocationCriteria, true);

    if (TextUtils.isEmpty(provider)) {
        LOGE(TAG, "No available location providers matching criteria, maybe permission is disabled.");
        provider = null;
    }

    requestLocationUpdate(lm, provider);
}
 
Example 17
Source File: NoteToSelfActivity.java    From narrate-android with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Get intent, action and MIME type
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();
    String text = intent.getStringExtra(Intent.EXTRA_TEXT);

    if ((action.equals("com.google.android.gm.action.AUTO_SEND") && type != null)) {

        if (text != null) {

            final Entry entry = new Entry();
            entry.creationDate = Calendar.getInstance();
            entry.modifiedDate = entry.creationDate.getTimeInMillis();

            entry.title = "";
            entry.text = text;

            if (Settings.getAutomaticLocation()) {

                String locationProvider = LocationManager.NETWORK_PROVIDER;
                LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                Location lastKnownLocation = mLocationManager.getLastKnownLocation(locationProvider);

                if (lastKnownLocation != null) {
                    LatLng location = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());

                    entry.hasLocation = true;
                    entry.latitude = location.latitude;
                    entry.longitude = location.longitude;

                    List<Pair<String, LatLng>> localPlaces = PlacesDao.getPlaces(location.latitude, location.longitude, 10);
                    MutableArrayList<Pair<String, Double>> places = new MutableArrayList();

                    if ( localPlaces.size() > 0 ) {
                        for (Pair<String, LatLng> p : localPlaces) {
                            double dist = LocationUtil.distanceBetweenLocations(location.latitude, location.longitude, p.second.latitude, p.second.longitude);
                            places.add(new Pair<>(p.first, dist));
                        }

                        places.sort(new Comparator<Pair<String, Double>>() {
                            @Override
                            public int compare(Pair<String, Double> lhs, Pair<String, Double> rhs) {
                                return lhs.second.compareTo(rhs.second);
                            }
                        });

                        entry.placeName = places.get(0).first;
                    }

                }
            }

            new Thread() {
                @Override
                public void run() {
                    super.run();
                    DataManager.getInstance().save(entry, true);
                }
            }.start();
        }
    }

    finish();
}
 
Example 18
Source File: PlacesFragment.java    From narrate-android with Apache License 2.0 4 votes vote down vote up
private void setup() {
    mSheetAdapter = new EntriesRecyclerAdapter(mainActivity.entries);

    mapView = (MapView) mRoot.findViewById(R.id.mapView);
    mapView.setAlwaysDrawnWithCacheEnabled(true);
    mapView.setPersistentDrawingCache(MapView.PERSISTENT_ALL_CACHES);
    mapView.onCreate(null);

    try {
        MapsInitializer.initialize(getActivity().getApplicationContext());
    } catch (Exception e) {
        e.printStackTrace();
    }

    map = mapView.getMap();

    mClusterManager = new ClusterManager<EntryMarker>(getActivity(), map);
    map.setOnCameraChangeListener(mClusterManager);
    map.setOnMarkerClickListener(mClusterManager);

    mClusterManager.setOnClusterClickListener(this);
    mClusterManager.setOnClusterItemClickListener(this);

    onDataUpdated();

    if (ActivityCompat.checkSelfPermission(mainActivity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mainActivity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        map.setMyLocationEnabled(false);

        if ( getActivity() != null && getActivity().getSystemService(Context.LOCATION_SERVICE) != null) {
            String locationProvider = LocationManager.NETWORK_PROVIDER;
            LocationManager mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
            lastKnownLocation = mLocationManager.getLastKnownLocation(locationProvider);
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if ( !isAdded() )
                    return;

                if ( lastKnownLocation != null ) {
                    LatLng position = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
                    CameraPosition newPosition = CameraPosition.fromLatLngZoom(position, 12.0f);
                    map.animateCamera(CameraUpdateFactory.newCameraPosition(newPosition));
                }

            }
        }, 500);
    }
}
 
Example 19
Source File: LoggingService.java    From WheelLogAndroid with GNU General Public License v3.0 4 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    instance = this;
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Constants.ACTION_WHEEL_DATA_AVAILABLE);
    intentFilter.addAction(Constants.ACTION_BLUETOOTH_CONNECTION_STATE);
    registerReceiver(mBluetoothUpdateReceiver, intentFilter);

    if (!PermissionsUtil.checkExternalFilePermission(this)) {
        showToast(R.string.logging_error_no_storage_permission);
        stopSelf();
        return START_STICKY;
    }

    if (!isExternalStorageReadable() || !isExternalStorageWritable()) {
        showToast(R.string.logging_error_storage_unavailable);
        stopSelf();
        return START_STICKY;
    }

    logLocationData = SettingsUtil.isLogLocationEnabled(this);

    if (logLocationData && !PermissionsUtil.checkLocationPermission(this)) {
        showToast(R.string.logging_error_no_location_permission);
        logLocationData = false;
    }

    sdf = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss.SSS", Locale.US);

    SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.US);

    filename = sdFormatter.format(new Date()) + ".csv";
    file = FileUtil.getFile(filename);

    if (file == null) {
        stopSelf();
        return START_STICKY;
    }

    if (logLocationData) {
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        // Getting GPS Provider status
        boolean isGPSEnabled = mLocationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // Getting Network Provider status
        boolean isNetworkEnabled = mLocationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        // Getting if the users wants to use GPS
        boolean useGPS = SettingsUtil.isUseGPSEnabled(this);

        if (!isGPSEnabled && !isNetworkEnabled) {
            logLocationData = false;
            mLocationManager = null;
            showToast(R.string.logging_error_all_location_providers_disabled);
        } else if (useGPS && !isGPSEnabled) {
            useGPS = false;
            showToast(R.string.logging_error_gps_disabled);
        } else if (!useGPS && !isNetworkEnabled) {
            logLocationData = false;
            mLocationManager = null;
            showToast(R.string.logging_error_network_disabled);
        }

        if (logLocationData) {
            FileUtil.writeLine(filename, "date,time,latitude,longitude,gps_speed,gps_alt,gps_heading,gps_distance,speed,voltage,current,power,battery_level,distance,totaldistance,system_temp,cpu_temp,tilt,roll,mode,alert");
            mLocation = getLastBestLocation();
            mLocationProvider = LocationManager.NETWORK_PROVIDER;
            if (useGPS)
                mLocationProvider = LocationManager.GPS_PROVIDER;
            // Acquire a reference to the system Location Manager
            mLocationManager.requestLocationUpdates(mLocationProvider, 250, 0, locationListener);
        } else
            FileUtil.writeLine(filename, "date,time,speed,voltage,current,power,battery_level,distance,totaldistance,system_temp,cpu_temp,tilt,roll,mode,alert");
    }
    else
        FileUtil.writeLine(filename, "date,time,speed,voltage,current,power,battery_level,distance,totaldistance,system_temp,cpu_temp,tilt,roll,mode,alert");

    Intent serviceIntent = new Intent(Constants.ACTION_LOGGING_SERVICE_TOGGLED);
    serviceIntent.putExtra(Constants.INTENT_EXTRA_LOGGING_FILE_LOCATION, file.getAbsolutePath());
    serviceIntent.putExtra(Constants.INTENT_EXTRA_IS_RUNNING, true);
    sendBroadcast(serviceIntent);

    Timber.i("DataLogger Started");

    return START_STICKY;
}
 
Example 20
Source File: GnssLocationProvider.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private void handleRequestLocation(boolean independentFromGnss) {
    if (isRequestLocationRateLimited()) {
        if (DEBUG) {
            Log.d(TAG, "RequestLocation is denied due to too frequent requests.");
        }
        return;
    }
    ContentResolver resolver = mContext.getContentResolver();
    long durationMillis = Settings.Global.getLong(
            resolver,
            Settings.Global.GNSS_HAL_LOCATION_REQUEST_DURATION_MILLIS,
            LOCATION_UPDATE_DURATION_MILLIS);
    if (durationMillis == 0) {
        Log.i(TAG, "GNSS HAL location request is disabled by Settings.");
        return;
    }

    LocationManager locationManager = (LocationManager) mContext.getSystemService(
            Context.LOCATION_SERVICE);
    String provider;
    LocationChangeListener locationListener;

    if (independentFromGnss) {
        // For fast GNSS TTFF
        provider = LocationManager.NETWORK_PROVIDER;
        locationListener = mNetworkLocationListener;
    } else {
        // For Device-Based Hybrid (E911)
        provider = LocationManager.FUSED_PROVIDER;
        locationListener = mFusedLocationListener;
    }

    Log.i(TAG,
            String.format(
                    "GNSS HAL Requesting location updates from %s provider for %d millis.",
                    provider, durationMillis));
    try {
        locationManager.requestLocationUpdates(provider,
                LOCATION_UPDATE_MIN_TIME_INTERVAL_MILLIS, /*minDistance=*/ 0,
                locationListener, mHandler.getLooper());
        locationListener.numLocationUpdateRequest++;
        mHandler.postDelayed(() -> {
            if (--locationListener.numLocationUpdateRequest == 0) {
                Log.i(TAG,
                        String.format("Removing location updates from %s provider.", provider));
                locationManager.removeUpdates(locationListener);
            }
        }, durationMillis);
    } catch (IllegalArgumentException e) {
        Log.w(TAG, "Unable to request location.", e);
    }
}