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

The following examples show how to use android.location.LocationManager#getAllProviders() . 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: LocationService.java    From io.appium.settings with Apache License 2.0 6 votes vote down vote up
private List<MockLocationProvider> createMockProviders(LocationManager locationManager) {
    List<String> providers = locationManager.getAllProviders();
    List<MockLocationProvider> mockProviders = new LinkedList<>();
    for (String providerName : providers) {
        // The passive provider is not required to be mocked.
        if (providerName.equals(LocationManager.PASSIVE_PROVIDER)) {
            continue;
        }
        MockLocationProvider mockProvider = createLocationManagerMockProvider(locationManager, providerName);
        if (mockProvider == null) {
            Log.e(TAG, String.format("Could not create mock provider for '%s'", providerName));
            continue;
        }
        mockProviders.add(mockProvider);
    }
    return mockProviders;
}
 
Example 2
Source File: PlacePickerActivity.java    From android_packages_apps_GmsCore with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("MissingPermission")
    private void updateMapFromLocationManager() {
        LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
        Location last = null;
        for (String provider : lm.getAllProviders()) {
            if (lm.isProviderEnabled(provider)) {
                Location t = lm.getLastKnownLocation(provider);
                if (t != null && (last == null || t.getTime() > last.getTime())) {
                    last = t;
                }
            }
        }
        Log.d(TAG, "Set location to " + last);
        if (last != null) {
//            mapView.map().setMapPosition(new MapPosition(last.getLatitude(), last.getLongitude(), 4096));
        }
    }
 
Example 3
Source File: DeviceHelper.java    From BigApp_Discuz_Android with Apache License 2.0 5 votes vote down vote up
private Location getLocation() {
	if(!checkPermissions("android.permission.ACCESS_FINE_LOCATION") || !checkPermissions("android.permission.ACCESS_COARSE_LOCATION")){
		Ln.e("getLocation ==>>", "Could not get location from GPS or Cell-id, lack ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permission?");
		return null;
	}
	LocationManager loctionManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
	List<String> matchingProviders = loctionManager.getAllProviders();
	Location location = null;
	for (String prociderString : matchingProviders) {
		Ln.d(" Location provider ==>>", prociderString);
		location = loctionManager.getLastKnownLocation(prociderString);
	}
	return location;
}
 
Example 4
Source File: MapPickerActivity.java    From actor-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This is where we can add markers or lines, add listeners or move the camera. In this case, we
 * just add a marker near Africa.
 * <p/>
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 */
private void setUpMap() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQ_LOCATION);
            im.actor.runtime.Log.d("Permissions", "MapPickerActivity.setUpMap - no permission :c");
            return;
        }
    }

    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    for (String provider : locationManager.getAllProviders()) {
        currentLocation = locationManager.getLastKnownLocation(provider);
        if (currentLocation != null) {
            break;
        }
    }

    if (currentLocation != null) {
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()), 14));
        fetchPlaces(null);
    }
    mMap.setOnMyLocationChangeListener(this);
    mMap.getUiSettings().setMyLocationButtonEnabled(false);
    mMap.getUiSettings().setZoomControlsEnabled(false);
    mMap.getUiSettings().setCompassEnabled(false);
    mMap.setMyLocationEnabled(true);
    mMap.setOnMapLongClickListener(this);
    mMap.setOnMarkerClickListener(this);
}
 
Example 5
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 6
Source File: DalvikPositionService.java    From attach with GNU General Public License v3.0 4 votes vote down vote up
private void initialize() {    
        
        Object systemService = activityContext.getSystemService(Activity.LOCATION_SERVICE);
        locationManager = (LocationManager) systemService;

        List<String> locationProviders = locationManager.getAllProviders();
        if (debug) {
            Log.v(TAG, String.format("Available location providers on this device: %s.", locationProviders.toString()));
        }
        
        locationProvider = locationManager.getBestProvider(getLocationProvider(), false);
        if (debug) {
            Log.v(TAG, String.format("Picked %s as best location provider.", locationProvider));
        }
        
        boolean locationProviderEnabled = locationManager.isProviderEnabled(locationProvider);
        if (!locationProviderEnabled) {
            if (debug) {
                Log.v(TAG, String.format("Location provider %s is not enabled, starting intent to ask user to activate the location provider.", locationProvider));
            }
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            activityContext.startActivity(intent);
        }

        Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
        if (lastKnownLocation != null) {
            if (debug) {
                Log.v(TAG, String.format("Last known location for provider %s: %f / %f / %f",
                        locationProvider, lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude(), lastKnownLocation.getAltitude()));
            }
            updatePosition(lastKnownLocation);
        }

/*
        final Intent serviceIntent = new Intent(activityContext, AndroidPositionBackgroundService.class);
        final IntentFilter intentFilter = new IntentFilter(AndroidPositionBackgroundService.class.getName());
        
        Services.get(LifecycleService.class).ifPresent(l -> {
            l.addListener(LifecycleEvent.PAUSE, () -> {
                quitLooperTask();
                // if the PositionService is still running and backgroundModeEnabled 
                // then start background service when the app goes to background
                if (running && parameters.isBackgroundModeEnabled()) {
                    activityContext.registerReceiver(broadcastReceiver, intentFilter);
                    activityContext.startService(serviceIntent);
                }
            });
            l.addListener(LifecycleEvent.RESUME, () -> {
                // if backgroundModeEnabled then stop the background service when
                // the app goes to foreground and resume PositionService
                if (parameters.isBackgroundModeEnabled()) {
                    try {
                        activityContext.unregisterReceiver(broadcastReceiver);
                    } catch (IllegalArgumentException e) {}
                    activityContext.stopService(serviceIntent);
                }
                createLooperTask();
            });
        });
*/
        createLooperTask();
    }
 
Example 7
Source File: MainActivity.java    From mockgeofix with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    pref.registerOnSharedPreferenceChangeListener(this);

    mTextStatus = (TextView)findViewById(R.id.text_status);
    mStartStopButton = (Button)findViewById(R.id.startstop_button);
    mDescription = (TextView)findViewById(R.id.description);
    mIPs = (TextView)findViewById(R.id.ips);

    updateDescription();
    updateListensOn();

    bindService(new Intent(getApplicationContext(),MockLocationService.class),
                mConn,
                Context.BIND_AUTO_CREATE
            );
    registerReceiver(receiver, new IntentFilter(MockLocationService.STARTED));
    registerReceiver(receiver, new IntentFilter(MockLocationService.STOPPED));
    registerReceiver(receiver, new IntentFilter(MockLocationService.ERROR));

    // show a dialog when "allow mock location" is not enabled
    if (Build.VERSION.SDK_INT < 23) {
        if (Settings.Secure.getString(getApplicationContext().getContentResolver(),
                Settings.Secure.ALLOW_MOCK_LOCATION).equals("0")) {
            if (!((MockGeoFixApp) getApplication()).enableMockLocationDialogShown) {
                ((MockGeoFixApp) getApplication()).enableMockLocationDialogShown = true;
                (new EnableMockLocationDialogFragment()).show(getSupportFragmentManager(),
                        "enable_mock_location_dialog");
            }
        }
    }

    // show a dialog when other location providers apart from the GPS one are enabled
    LocationManager locationManager =
            (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    for (String provider : locationManager.getAllProviders()) {
        if (locationManager.isProviderEnabled(provider) &&
                !provider.equals(LocationManager.PASSIVE_PROVIDER) &&
                !provider.equals(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(getApplicationContext(),
                String.format(getString(R.string.provider_enabled), provider), Toast.LENGTH_LONG).show();
        }
    }

    if (! ((MockGeoFixApp)getApplication()).openLocationSourceSettingsDialogShown ) {
        if ( ! locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
             || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            ((MockGeoFixApp) getApplication()).openLocationSourceSettingsDialogShown = true;
            (new OpenLocationSourceSettingsDialogFragment()).show(getSupportFragmentManager(),
                    "open_location_source_settings_dialog");
        }
    }

}
 
Example 8
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 9
Source File: GpsEventReceiver.java    From satstat with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @param args[0] A {@link Context} for connecting to the various system services
 * @param args[1] The {@link Intent} to raise when the next update is due
 * @param args[2] A {@link SharedPreferences} instance in which the timestamp of the update will be stored
 * @param args[3] The update frequency, of type {@link Long}, in milliseconds
 */
@Override
protected Integer doInBackground(Object... args) {
	mContext = (Context) args[0];
	Intent agpsIntent = (Intent) args[1];
	SharedPreferences sharedPref = (SharedPreferences) args[2];
	long freqMillis = (Long) args[3];
	
	int nc = WifiCapabilities.getNetworkConnectivity();
	if (nc == WifiCapabilities.NETWORK_CAPTIVE_PORTAL) {
		// portale cattivo che non ci permette di scaricare i dati AGPS
		Log.i(GpsEventReceiver.class.getSimpleName(), "Captive portal detected, cannot update AGPS data");
		return nc;
	} else if (nc == WifiCapabilities.NETWORK_ERROR) {
		Log.i(GpsEventReceiver.class.getSimpleName(), "No network available, cannot update AGPS data");
		return nc;
	}
	
	AlarmManager alm = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
	PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, agpsIntent, PendingIntent.FLAG_UPDATE_CURRENT);
	alm.cancel(pi);

	LocationManager locman = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
	List<String> allProviders = locman.getAllProviders();
	PendingIntent tempIntent = PendingIntent.getBroadcast(mContext, 0, mLocationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
	Log.i(GpsEventReceiver.class.getSimpleName(), "Requesting AGPS data update");
	try {
		if (allProviders.contains(LocationManager.GPS_PROVIDER))
			locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, tempIntent);
		locman.sendExtraCommand("gps", "force_xtra_injection", null);
		locman.sendExtraCommand("gps", "force_time_injection", null);
		locman.removeUpdates(tempIntent);
		
		SharedPreferences.Editor spEditor = sharedPref.edit();
		spEditor.putLong(Const.KEY_PREF_UPDATE_LAST, System.currentTimeMillis());
		spEditor.commit();
	} catch (SecurityException e) {
		Log.w(GpsEventReceiver.class.getSimpleName(), "Permissions not granted, cannot update AGPS data");
	}
	
	if (freqMillis > 0) {
		// if an update interval is set, prepare an alarm to trigger a new
		// update when it elapses (if no interval is set, do nothing as we
		// cannot determine a point in time for re-running the update)
		long next = System.currentTimeMillis() + freqMillis;
		alm.set(AlarmManager.RTC, next, pi);
		Log.i(GpsEventReceiver.class.getSimpleName(), String.format("Next update due %1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS (after %2$d ms)", next, freqMillis));
	}

	return nc;
}