Java Examples for android.location.Location

The following java examples will help you to understand the usage of android.location.Location. These source code samples are taken from different open source projects.

Example 1
Project: NetworkLocation-master  File: Reflected.java View source code
public static void androidLocationLocationSetExtraLocation(Location location, String key, Location value) {
    try {
        Class clazz = Class.forName("android.location.Location");
        Method setExtraLocation = clazz.getDeclaredMethod("setExtraLocation", String.class, Location.class);
        setExtraLocation.invoke(location, key, value);
    } catch (Exception e) {
        Log.w("android.location.Location.setExtraLocation", e);
    }
}
Example 2
Project: SimpleWeatherForecast-master  File: LocationUtils.java View source code
/**
     * Get the last known {@link android.location.Location} with a coarse accuracy.
     *
     * @param context the {@link android.content.Context} used to retrieve the {@link android.location.LocationManager}.
     * @return the last known {@link android.location.Location} or null.
     */
public static Location getLastKnownLocation(Context context) {
    Location lastKnownLocation = null;
    final LocationManager locationManager = (LocationManager) context.getSystemService(Service.LOCATION_SERVICE);
    final Criteria locationCriteria = new Criteria();
    locationCriteria.setAccuracy(Criteria.ACCURACY_COARSE);
    final String providerName = locationManager.getBestProvider(locationCriteria, true);
    if (providerName != null) {
        lastKnownLocation = locationManager.getLastKnownLocation(providerName);
    }
    return lastKnownLocation;
}
Example 3
Project: overpasser-master  File: LocationHelper.java View source code
public Location getLastKnownLocation() {
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (location == null) {
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }
    if (location == null) {
        location = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
    }
    return location;
}
Example 4
Project: RadarApp-master  File: ServiceLocationListener.java View source code
@Override
public void onLocationChanged(Location location) {
    Log.d(ServiceLocationListener.class.getSimpleName(), "Provider: " + location.getProvider() + "|" + "Lat/Lng: " + location.getLatitude() + "/" + location.getLongitude());
    if (LocalDb.getInstance() != null) {
        mCurrentUser = LocalDb.getInstance().getCurrentUser();
        UserDetail userDetail = mCurrentUser.getUserDetail();
        userDetail.setLocation(new ParseGeoPoint(location.getLatitude(), location.getLongitude()));
        userDetail.setProvider(location.getProvider());
        userDetail.setActive(true);
        try {
            userDetail.save();
        } catch (ParseException e) {
            Log.d(ServiceLocationListener.class.getSimpleName(), e.getMessage());
        }
    }
}
Example 5
Project: dronekit-android-master  File: LocationRelay.java View source code
/**
     * Convert the specified Android location to a local Location, and track speed/accuracy
     */
public Location toGcsLocation(android.location.Location androidLocation) {
    if (androidLocation == null)
        return null;
    Location gcsLocation = null;
    if (VERBOSE)
        Timber.d("toGcsLocation(): followLoc=" + androidLocation);
    // previous location (or 0 if no previous location).
    if (!androidLocation.hasBearing()) {
        if (mLastLocation != null) {
            LatLong last = new LatLong(mLastLocation.getLatitude(), mLastLocation.getLongitude());
            LatLong newLoc = new LatLong(androidLocation.getLatitude(), androidLocation.getLongitude());
            androidLocation.setBearing((float) GeoTools.getHeadingFromCoordinates(last, newLoc));
        } else {
            androidLocation.setBearing(0);
        }
    }
    boolean ok = (androidLocation.hasAccuracy() && androidLocation.hasBearing() && androidLocation.getTime() > 0);
    if (!ok) {
        Timber.w("toGcsLocation(): Location needs accuracy, bearing, and time.");
    } else {
        float distanceToLast = -1.0f;
        long timeSinceLast = -1L;
        final long androidLocationTime = androidLocation.getTime();
        if (mLastLocation != null) {
            distanceToLast = androidLocation.distanceTo(mLastLocation);
            timeSinceLast = (androidLocationTime - mLastLocation.getTime());
        }
        // mm/ms (does a better job calculating for locations that arrive at < 1-second intervals)
        final float currentSpeed = (distanceToLast > 0f && timeSinceLast > 0) ? ((distanceToLast * 1000) / timeSinceLast) : 0f;
        final boolean isAccurate = isLocationAccurate(androidLocation.getAccuracy(), currentSpeed);
        if (VERBOSE) {
            Timber.d("toLocation(): distancetoLast=%.2f timeToLast=%d currSpeed=%.2f accurate=%s", distanceToLast, timeSinceLast, currentSpeed, isAccurate);
        }
        // Make a new location
        gcsLocation = new Location(new LatLongAlt(androidLocation.getLatitude(), androidLocation.getLongitude(), androidLocation.getAltitude()), androidLocation.getBearing(), androidLocation.getSpeed(), isAccurate, androidLocation.getTime());
        mLastLocation = androidLocation;
        if (VERBOSE)
            Timber.d("External location lat/lng=" + getLatLongFromLocation(androidLocation));
    }
    return gcsLocation;
}
Example 6
Project: weather-notification-android-master  File: AndroidGoogleLocation.java View source code
//@Override
public String getText() {
    if (location == null) {
        return "";
    }
    if (address == null) {
        return android.location.Location.convert(location.getLatitude(), android.location.Location.FORMAT_DEGREES) + " " + android.location.Location.convert(location.getLongitude(), android.location.Location.FORMAT_DEGREES);
    }
    StringBuilder result = new StringBuilder();
    result.append(stringOrEmpty(address.getLocality()));
    if (result.length() > 0) {
        result.append(", ");
    }
    result.append(stringOrEmpty(address.getAdminArea()));
    if (result.length() == 0) {
        result.append(stringOrEmpty(address.getCountryName()));
    }
    return result.toString();
}
Example 7
Project: android_external_UnifiedNlpApi-master  File: ThirdSampleService.java View source code
@Override
public void run() {
    synchronized (regular) {
        while (!regular.isInterrupted()) {
            try {
                regular.wait(60000);
            } catch (InterruptedException e) {
                return;
            }
            Location location = LocationHelper.create("random", random.nextDouble() * 90, random.nextDouble() * 90, random.nextFloat() * 90);
            Log.d(TAG, "Just reported: " + location);
            report(location);
        }
    }
}
Example 8
Project: android_programmering_2014-master  File: MainActivity.java View source code
public void run() {
    Worker worker = new Worker(MainActivity.this);
    updateUI("Starting");
    Location location = worker.getLocation();
    updateUI("Retrieved Location");
    String address = worker.reverseGeocode(location);
    updateUI("Retrieved Address");
    worker.save(location, address, "FancyFileName.out");
    updateUI("Done");
}
Example 9
Project: apps-android-wikipedia-master  File: GeoIPCookieUnmarshaller.java View source code
@VisibleForTesting
@NonNull
static GeoIPCookie unmarshal(@Nullable String cookie) throws IllegalArgumentException {
    if (TextUtils.isEmpty(cookie)) {
        throw new IllegalArgumentException("Cookie is empty.");
    }
    String[] components = cookie.split(":");
    if (components.length < Component.values().length) {
        throw new IllegalArgumentException("Cookie is malformed.");
    } else if (!components[Component.VERSION.ordinal()].equals("v4")) {
        throw new IllegalArgumentException("Incorrect cookie version.");
    }
    Location location = null;
    if (!TextUtils.isEmpty(components[Component.LATITUDE.ordinal()]) && !TextUtils.isEmpty(components[Component.LONGITUDE.ordinal()])) {
        location = new Location("");
        try {
            location.setLatitude(Double.parseDouble(components[Component.LATITUDE.ordinal()]));
            location.setLongitude(Double.parseDouble(components[Component.LONGITUDE.ordinal()]));
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Location is malformed.");
        }
    }
    return new GeoIPCookie(components[Component.COUNTRY.ordinal()], components[Component.REGION.ordinal()], components[Component.CITY.ordinal()], location);
}
Example 10
Project: criticalmaps-android-master  File: LocationUtils.java View source code
@Nullable
public static GeoPoint getBestLastKnownLocation(LocationManager locationManager) {
    final String[] providers = new String[] { GPS_PROVIDER, NETWORK_PROVIDER, PASSIVE_PROVIDER };
    for (String provider : providers) {
        if (locationManager.isProviderEnabled(provider)) {
            final Location location = locationManager.getLastKnownLocation(provider);
            if (location != null) {
                return new GeoPoint(location.getLatitude(), location.getLongitude());
            }
        }
    }
    return null;
}
Example 11
Project: itrackmygps-android-master  File: LocationReceiver.java View source code
@Override
public void onReceive(Context context, Intent intent) {
    // If you got a Location extra, use it
    Location loc = (Location) intent.getParcelableExtra(LocationManager.KEY_LOCATION_CHANGED);
    int ctr = intent.getIntExtra("counter", 0);
    if (loc != null) {
        onLocationReceived(context, loc, ctr);
        return;
    }
    // If you get here, something else has happened
    if (intent.hasExtra(LocationManager.KEY_PROVIDER_ENABLED)) {
        boolean enabled = intent.getBooleanExtra(LocationManager.KEY_PROVIDER_ENABLED, false);
        onProviderEnabledChanged(enabled);
    }
}
Example 12
Project: Team5GeoTopics-master  File: UserLocationServiceTests.java View source code
/*
	 * test used case 18: DefaultCommentLocationLocal
	 * 
	 * this simply tests the function that is called to retrieve the location by default.
	 * Since there is no provider in the test it gets the last known location which should be (0.0, 0.0)
	 */
public void testGetCurrentLocation() {
    UserLocationServices uls = new UserLocationServices();
    Location myLoc = null;
    assertNull(myLoc);
    myLoc = uls.getCurrentLocation();
    assertNotNull(myLoc);
    assertEquals("Since there is no provider the last location is (0,0)", 0.0, myLoc.getLatitude());
    assertEquals("Since there is no provider the last location is (0,0)", 0.0, myLoc.getLongitude());
}
Example 13
Project: traccar-client-android-master  File: DatabaseHelperTest.java View source code
@Test
public void test() throws Exception {
    DatabaseHelper databaseHelper = new DatabaseHelper(RuntimeEnvironment.application);
    SQLiteDatabase db = databaseHelper.getWritableDatabase();
    Position position = new Position("123456789012345", new Location("gps"), 0);
    position.setTime(new Date(0));
    assertNull(databaseHelper.selectPosition());
    databaseHelper.insertPosition(position);
    position = databaseHelper.selectPosition();
    assertNotNull(position);
    databaseHelper.deletePosition(position.getId());
    assertNull(databaseHelper.selectPosition());
}
Example 14
Project: ulysses-master  File: UlyssesStreetViewPanoramaFragment_OLD.java View source code
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
//		LinearLayout layoutPanorama = (LinearLayout) getActivity().findViewById(R.id.layout_panorama);
//		layoutPanorama.setVisibility(View.VISIBLE);
//		buttonGetPanorama = (Button) getActivity().findViewById(R.id.button_get_panorama);
//		buttonGetPanorama.setOnClickListener( new OnClickListener() {
//			@Override
//			public void onClick(View v) {
////				arguments = getArguments();
//				Ln.d("clicked for panorama");
//				layoutPanorama.setVisibility(View.VISIBLE);
////		    	Location location = StreetViewFragment.this.activity.getPlace().getLocation();
////		    	latitude = location.getLatitude();
////		    	longitude = location.getLongitude();
////		    	StreetViewFragment.newInstance(location.getLatitude(), location.getLongitude());
//		    	getStreetViewPanoramaAsync(onStreetViewPanoramaReadyCallback );
//			}
//		});
}
Example 15
Project: Sapelli-master  File: LocationUtils.java View source code
/**
	 * Converts an Android Location object (android.location.Location) into an equivalent "ExCiteS" location object (uk.ac.ucl.excites.storage.types.Location)
	 * 
	 * @param androidLocation
	 * @return
	 */
public static Location getSapelliLocation(android.location.Location androidLocation) {
    if (androidLocation == null)
        return null;
    int provider = Location.PROVIDER_UNKNOWN;
    if (LocationManager.GPS_PROVIDER.equals(androidLocation.getProvider()))
        provider = Location.PROVIDER_GPS;
    else if (LocationManager.NETWORK_PROVIDER.equals(androidLocation.getProvider()))
        provider = Location.PROVIDER_NETWORK;
    return new Location(androidLocation.getLatitude(), androidLocation.getLongitude(), (androidLocation.hasAltitude() ? androidLocation.getAltitude() : null), (androidLocation.hasBearing() ? androidLocation.getBearing() : null), (androidLocation.hasSpeed() ? androidLocation.getSpeed() : null), (androidLocation.hasAccuracy() ? androidLocation.getAccuracy() : null), androidLocation.getTime(), provider);
}
Example 16
Project: bearing-master  File: CurrentLocationTask.java View source code
/**
	 * Begin the lookup task using the set configuration.
	 * Returns the task for cancellation if required.
	 */
@SuppressWarnings("unused")
public CurrentLocationTask start() {
    super.start();
    this.taskId = locationProvider.requestSingleLocationUpdate(request, new LocationListener() {

        @Override
        public void onUpdate(Location location) {
            if (running) {
                // Cancel current task
                running = false;
                if (listener != null) {
                    listener.onUpdate(location);
                }
            }
        }

        @Override
        public void onFailure() {
            listener.onFailure();
        }

        @Override
        public void onTimeout() {
            listener.onTimeout();
        }
    });
    return this;
}
Example 17
Project: Buddy-Android-SDK-master  File: BuddyLocationDeserializer.java View source code
@Override
public Location deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) throws JsonParseException {
    JsonObject jsonObj = json.getAsJsonObject();
    if (jsonObj != null && jsonObj.has("lat") && jsonObj.has("lng")) {
        Location l = new Location("Buddy");
        l.setLatitude(jsonObj.get("lat").getAsDouble());
        l.setLongitude(jsonObj.get("lng").getAsDouble());
        return l;
    }
    throw new JsonParseException("Invalid location: " + json.toString());
}
Example 18
Project: foursquared-dz-master  File: GeoUtils.java View source code
/**
     * To be used if you just want a one-shot best last location, iterates over
     * all providers and returns the most accurate result.
     */
public static Location getBestLastGeolocation(Context context) {
    LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = manager.getAllProviders();
    Location bestLocation = null;
    for (String it : providers) {
        Location location = manager.getLastKnownLocation(it);
        if (location != null) {
            if (bestLocation == null || location.getAccuracy() < bestLocation.getAccuracy()) {
                bestLocation = location;
            }
        }
    }
    return bestLocation;
}
Example 19
Project: foursquared-master  File: GeoUtils.java View source code
/**
     * To be used if you just want a one-shot best last location, iterates over
     * all providers and returns the most accurate result.
     */
public static Location getBestLastGeolocation(Context context) {
    LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = manager.getAllProviders();
    Location bestLocation = null;
    for (String it : providers) {
        Location location = manager.getLastKnownLocation(it);
        if (location != null) {
            if (bestLocation == null || location.getAccuracy() < bestLocation.getAccuracy()) {
                bestLocation = location;
            }
        }
    }
    return bestLocation;
}
Example 20
Project: location-tracker-background-master  File: LocationReceiver.java View source code
@Override
public void onReceive(Context context, Intent intent) {
    if (null != intent && intent.getAction().equals("my.action")) {
        Location locationData = (Location) intent.getParcelableExtra(SettingsLocationTracker.LOCATION_MESSAGE);
        Log.d("Location: ", "Latitude: " + locationData.getLatitude() + "Longitude:" + locationData.getLongitude());
    //send your call to api or do any things with the of location data
    }
}
Example 21
Project: PartyBolle-master  File: LocationUtils.java View source code
public static final Location createFoursquareLocation(android.location.Location location) {
    if (location == null) {
        return new Location(null, null, null, null, null);
    }
    String geolat = null;
    if (location.getLatitude() != 0.0) {
        geolat = String.valueOf(location.getLatitude());
    }
    String geolong = null;
    if (location.getLongitude() != 0.0) {
        geolong = String.valueOf(location.getLongitude());
    }
    String geohacc = null;
    if (location.hasAccuracy()) {
        geohacc = String.valueOf(location.getAccuracy());
    }
    String geoalt = null;
    if (location.hasAccuracy()) {
        geoalt = String.valueOf(location.hasAltitude());
    }
    return new Location(geolat, geolong, geohacc, null, geoalt);
}
Example 22
Project: SMRTMS-master  File: GPSTrackerTest.java View source code
@Test
public void testGPSdata() {
    testGPSTracker = Mockito.mock(GPSTracker.class);
    Mockito.when(testGPSTracker.canGetLocation()).thenReturn(true);
    Location n = Mockito.mock(Location.class);
    n.setLatitude(47.265);
    n.setLongitude(11.395);
    Mockito.when(testGPSTracker.getLatitude()).thenReturn(47.265);
    Mockito.when(testGPSTracker.getLongitude()).thenReturn(11.395);
    Mockito.when(testGPSTracker.getLocation()).thenReturn(n);
    Mockito.when(testGPSTracker.calculateDistance(Mockito.anyDouble(), Mockito.anyDouble())).thenCallRealMethod();
    testGPSTracker.location = n;
    assertTrue(testGPSTracker.calculateDistance(47.273333, 11.241389) > 10 && testGPSTracker.calculateDistance(47.273333, 11.241389) < 12);
}
Example 23
Project: traffic-balance-master  File: DataSenderImpl.java View source code
public void sendData(int from, int to) {
    List<Location> data = locationDataSource.getLocationData();
    List<Location> toSend = new ArrayList<Location>();
    for (int i = from; i < to; i++) {
        Location loc = data.remove(i);
        toSend.add(loc);
    }
    try {
        LocationDataBatch batchToSend = LocationDataBatchAssembler.convert(toSend);
        trafficService.sendTrafficData(batchToSend);
    } catch (JSONRPCException ex) {
        Log.e("DataSender", "Error while sending data to server", ex);
    }
}
Example 24
Project: trigger.io-background_geolocation-master  File: LocationReceiver.java View source code
@Override
public void onReceive(Context context, Intent intent) {
    Location location = (Location) intent.getExtras().get(LocationClient.KEY_LOCATION_CHANGED);
    JsonObject json = new JsonObject();
    json.addProperty("lat", location.getLatitude());
    json.addProperty("lon", location.getLongitude());
    ForgeApp.event("background_geolocation.locationChanged", json);
}
Example 25
Project: whatstodo-master  File: LocationUtils.java View source code
public static String[] addressFromLocation(Location location) {
    List<Address> addresses = null;
    Geocoder geocoder = new Geocoder(WhatsToDo.getContext(), Locale.GERMANY);
    try {
        addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 5);
    } catch (IOException e) {
        String[] ret = { "Es konnte keine Adresse gefunden werden." };
        return ret;
    }
    String[] addressStrings = new String[addresses.size()];
    int i = 0;
    for (Address address : addresses) {
        addressStrings[i++] = fromAddress(address);
    }
    return addressStrings;
}
Example 26
Project: YourAppIdea-master  File: WordpressServiceFactory.java View source code
public static WordpressService create(Context context) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Timestamp.class, new TimestampDeserializer());
    gsonBuilder.registerTypeAdapter(Location.class, new LocationDeserializer());
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new LoggingInterceptor()).build();
    Retrofit retrofit = new Retrofit.Builder().baseUrl(context.getString(R.string.tutorial_sync_url)).client(client).addConverterFactory(GsonConverterFactory.create(gsonBuilder.create())).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
    return retrofit.create(WordpressService.class);
}
Example 27
Project: sthlmtraveling-master  File: LocationUtils.java View source code
/**
     * Converts a string representation to {@link android.location.Location}.
     * @param locationData the location (latitude,longitude)
     * @return android location.
     */
public static Location parseLocation(String locationData) {
    String[] longAndLat = locationData.split(",");
    //Defualt to the world center, The Royal Palace
    float latitude = 59.3270053f;
    float longitude = 18.0723166f;
    try {
        latitude = Float.parseFloat(longAndLat[0]);
        longitude = Float.parseFloat(longAndLat[1]);
    } catch (NumberFormatException nfe) {
        Log.e(TAG, nfe.toString());
    } catch (ArrayIndexOutOfBoundsException aioobe) {
        Log.e(TAG, aioobe.toString());
    }
    Location location = new Location("sthlmtraveling");
    location.setLatitude(latitude);
    location.setLongitude(longitude);
    return location;
}
Example 28
Project: hk-master  File: GeolocationDataHooker.java View source code
/**
   * Hook calls to specific methods of the location class
   */
private void attachOnLocationClass() {
    Map<String, Integer> methodsFromLocationToHook = new HashMap<String, Integer>();
    methodsFromLocationToHook.put("getBearing", 1);
    methodsFromLocationToHook.put("getLatitude", 1);
    methodsFromLocationToHook.put("setLatitude", 2);
    methodsFromLocationToHook.put("getLongitude", 1);
    methodsFromLocationToHook.put("setLongitude", 2);
    methodsFromLocationToHook.put("getAltitude", 1);
    methodsFromLocationToHook.put("setAltitude", 2);
    methodsFromLocationToHook.put("getSpeed", 1);
    methodsFromLocationToHook.put("SetSpeed", 2);
    methodsFromLocationToHook.put("getTime", 1);
    methodsFromLocationToHook.put("setTime", 2);
    methodsFromLocationToHook.put("hasBearing", 0);
    methodsFromLocationToHook.put("hasAccuracy", 0);
    methodsFromLocationToHook.put("hasAltitude", 0);
    methodsFromLocationToHook.put("hasSpeed", 0);
    try {
        hookMethods(null, "android.location.Location", methodsFromLocationToHook);
        SubstrateMain.log("hooking android.location.Location methods sucessful");
    } catch (HookerInitializationException e) {
        SubstrateMain.log("hooking android.location.Location methods has failed", e);
    }
}
Example 29
Project: RxLocation-master  File: MainPresenterTest.java View source code
@Test
public void settingsSatisfied_1Location() {
    Location loc = Mockito.mock(Location.class);
    Address address = Mockito.mock(Address.class);
    doReturn(Single.just(true)).when(locationSettings).checkAndHandleResolution(Matchers.any(LocationRequest.class));
    doReturn(Observable.just(loc)).when(fusedLocation).updates(Matchers.any(LocationRequest.class));
    doReturn(Maybe.just(address)).when(geocoding).fromLocation(Matchers.any(android.location.Location.class));
    mainPresenter.attachView(mainView);
    verify(mainView).onLocationUpdate(loc);
    verify(mainView).onAddressUpdate(address);
    verifyNoMoreInteractions(mainView);
}
Example 30
Project: AdobeAir-master  File: SetLocationFunction.java View source code
@Override
public FREObject call(FREContext freContext, FREObject[] freObjects) {
    try {
        double latitude = freObjects[0].getAsDouble();
        double longitude = freObjects[1].getAsDouble();
        Location location = new Location("");
        location.setLatitude(latitude);
        location.setLongitude(longitude);
        TapForTap.setLocation(location);
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (FRETypeMismatchException e) {
        e.printStackTrace();
    } catch (FREInvalidObjectException e) {
        e.printStackTrace();
    } catch (FREWrongThreadException e) {
        e.printStackTrace();
    }
    return null;
}
Example 31
Project: AndroidSurvey-master  File: LocationReceiver.java View source code
@Override
public void onReceive(Context context, Intent intent) {
    Location loc = (Location) intent.getParcelableExtra(LocationManager.KEY_LOCATION_CHANGED);
    if (loc != null) {
        onLocationReceived(context, loc);
        return;
    }
    if (intent.hasExtra(LocationManager.KEY_PROVIDER_ENABLED)) {
        boolean enabled = intent.getBooleanExtra(LocationManager.KEY_PROVIDER_ENABLED, false);
        onProviderEnabledChanged(enabled);
    }
}
Example 32
Project: Android_App_OpenSource-master  File: LbsScriptHook.java View source code
private void requestAddress() {
    Location location = ServiceManager.getLocationService().getLocation();
    try {
        if (location == null) {
            currentAddress = null;
            currentCity = null;
            return;
        } else {
            String s1;
            StringBuilder stringbuilder = (new StringBuilder()).append("http://maps.google.com/maps/api/geocode/json?latlng=");
            double d = location.getLatitude();
            StringBuilder stringbuilder1 = stringbuilder.append(d).append(",");
            double d1 = location.getLongitude();
            String s = stringbuilder1.append(d1).append("&sensor=true&language=zh-CN").toString();
            s1 = ServiceManager.getNetworkService().getSync(s);
            if (s1 == null) {
                currentAddress = null;
                currentCity = null;
                return;
            } else {
                JSONObject jsonobject = (new JSONObject(s1)).getJSONArray("results").getJSONObject(0);
                String s2 = jsonobject.getString("formatted_address");
                currentAddress = s2;
                String s3 = jsonobject.getJSONArray("address_components").getJSONObject(2).getString("long_name");
                currentCity = s3;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 33
Project: android_coursera_1-master  File: MockLocationProvider.java View source code
public void pushLocation(double lat, double lon) {
    Location mockLocation = new Location(mProviderName);
    mockLocation.setLatitude(lat);
    mockLocation.setLongitude(lon);
    mockLocation.setAltitude(0);
    mockLocation.setTime(System.currentTimeMillis());
    mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    mockLocation.setAccuracy(mockAccuracy);
    mLocationManager.setTestProviderLocation(mProviderName, mockLocation);
}
Example 34
Project: androrat-master  File: GPSListener.java View source code
public byte[] encode(Location loc) {
    packet = new GPSPacket(loc.getLatitude(), loc.getLongitude(), loc.getAltitude(), loc.getSpeed(), loc.getAccuracy());
    return packet.build();
/*
		ByteBuffer b = ByteBuffer.allocate(32);
		b.putDouble(loc.getLongitude());
		b.putDouble(loc.getLatitude());
		b.putDouble(loc.getAltitude());
		b.putFloat(loc.getAccuracy());
		b.putFloat(loc.getSpeed());
		return b.array();
		*/
}
Example 35
Project: androrm-master  File: LocationFieldTest.java View source code
public void testSave() {
    Location l = new Location(LocationManager.GPS_PROVIDER);
    l.setLatitude(1.0);
    l.setLongitude(2.0);
    BlankModel b = new BlankModel();
    b.setLocation(l);
    b.save(getContext());
    BlankModel b2 = Model.objects(getContext(), BlankModel.class).get(b.getId());
    Location l2 = b2.getLocation();
    assertEquals(1.0, l2.getLatitude());
    assertEquals(2.0, l2.getLongitude());
}
Example 36
Project: cgeo-master  File: PositionHistory.java View source code
/**
     * Adds the current position to the trail history to be able to show the trail on the map.
     */
public void rememberTrailPosition(final Location coordinates) {
    if (coordinates.getAccuracy() >= 50f) {
        return;
    }
    if (coordinates.getLatitude() == 0.0 && coordinates.getLongitude() == 0.0) {
        return;
    }
    if (history.isEmpty()) {
        history.add(coordinates);
        return;
    }
    final Location historyRecent = history.get(history.size() - 1);
    if (historyRecent.distanceTo(coordinates) <= MINIMUM_DISTANCE_METERS) {
        return;
    }
    history.add(coordinates);
    // avoid running out of memory
    final int itemsToRemove = getHistory().size() - MAX_POSITIONS;
    if (itemsToRemove > 0) {
        for (int i = 0; i < itemsToRemove; i++) {
            getHistory().remove(0);
        }
    }
}
Example 37
Project: Code4Reference-master  File: LocationFinder.java View source code
public void onLocationChanged(Location location) {
    if (location != null) {
        double lat = location.getLatitude();
        double lng = location.getLongitude();
        Editor editor = ctx.getSharedPreferences("c2dmPref", Context.MODE_PRIVATE).edit();
        editor.putString("lat", new Double(lat).toString());
        editor.putString("lng", new Double(lng).toString());
        editor.commit();
    }
}
Example 38
Project: Compass-View-master  File: DemoActivity.java View source code
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final ViewHolder viewHolder;
    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
        viewHolder = new ViewHolder();
        viewHolder.titleView = (TextView) convertView.findViewById(R.id.titleView);
        viewHolder.compassView = (CompassView) convertView.findViewById(R.id.compassView);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }
    final Location itemLocation = getItem(position);
    viewHolder.titleView.setText(itemLocation.getLatitude() + " - " + itemLocation.getLongitude());
    viewHolder.compassView.initializeCompass(compassSensorManager, userLocation, itemLocation, R.drawable.arrow);
    return convertView;
}
Example 39
Project: coursera-android-labs-master  File: MockLocationProvider.java View source code
public void pushLocation(double lat, double lon) {
    Location mockLocation = new Location(mProviderName);
    mockLocation.setLatitude(lat);
    mockLocation.setLongitude(lon);
    mockLocation.setAltitude(0);
    mockLocation.setTime(System.currentTimeMillis());
    mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    mockLocation.setAccuracy(sMockAccuracy);
    mLocationManager.setTestProviderLocation(mProviderName, mockLocation);
}
Example 40
Project: frisbee-master  File: ChapterComparator.java View source code
@Override
public int compare(Chapter chapter, Chapter chapter2) {
    if (chapter.equals(homeChapter)) {
        return -1;
    }
    if (chapter2.equals(homeChapter)) {
        return 1;
    }
    if (lastLocation == null || (chapter.getGeo() == null && chapter2.getGeo() == null)) {
        return chapter.compareTo(chapter2);
    }
    final boolean closeEnough;
    final boolean closeEnough2;
    final float[] results = new float[1];
    final float[] results2 = new float[1];
    if (chapter.getGeo() != null) {
        Location.distanceBetween(lastLocation.getLatitude(), lastLocation.getLongitude(), chapter.getGeo().getLat(), chapter.getGeo().getLng(), results);
        closeEnough = results[0] <= MAX_DISTANCE;
    } else {
        closeEnough = false;
    }
    if (chapter2.getGeo() != null) {
        Location.distanceBetween(lastLocation.getLatitude(), lastLocation.getLongitude(), chapter2.getGeo().getLat(), chapter2.getGeo().getLng(), results2);
        closeEnough2 = results2[0] <= MAX_DISTANCE;
    } else {
        closeEnough2 = false;
    }
    if (closeEnough && closeEnough2) {
        return integerCompare((int) results[0], (int) results2[0]);
    } else if (closeEnough) {
        return -1;
    } else if (closeEnough2) {
        return 1;
    } else {
        return chapter.compareTo(chapter2);
    }
}
Example 41
Project: GeoTagger-master  File: LocationHandler.java View source code
/*
	 * Return the current location of the device, if available
	 * If not, show prompt to enable GPS
	 */
public GeoLocation getCurrentLocation() {
    boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if (gpsEnabled) {
        Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        geo = new GeoLocation(loc.getLatitude(), loc.getLongitude());
    } else {
        alertHandler.showGpsDisabledAlert(context);
    }
    return geo;
}
Example 42
Project: gpslogger-master  File: Kml22AnnotateHandlerTest.java View source code
@Test
public void GetPlacemarkXml_BasicLocation_BasicPlacemarkNodeReturned() {
    Kml22AnnotateHandler kmlHandler = new Kml22AnnotateHandler(null, null, null);
    Location loc = MockLocations.builder("MOCK", 12.193, 19.111).withAltitude(9001d).withBearing(91.88f).withSpeed(188.44f).build();
    String actual = kmlHandler.getPlacemarkXml("This is the annotation", loc);
    String expected = "<Placemark><name>This is the annotation</name><Point><coordinates>19.111,12.193,9001.0</coordinates></Point></Placemark>\n";
    assertThat("Basic Placemark XML", actual, is(expected));
}
Example 43
Project: hellomap3d-android-master  File: CircleUtil.java View source code
/**
     * Calculates points for location circle, useful for "My Location" feature
     *
     * @param location from Android Location API
     * @param proj     map projection, usually EPSG3857
     * @return MapPosVector to construct Polygon object, and add it to DataSource and Layer
     */
public static MapPosVector createLocationCircle(Location location, Projection proj) {
    // number of points of circle
    int N = 50;
    int EARTH_RADIUS = 6378137;
    float radius = location.getAccuracy();
    double centerLat = location.getLatitude();
    double centerLon = location.getLongitude();
    MapPosVector points = new MapPosVector();
    for (int i = 0; i <= N; i++) {
        double angle = Math.PI * 2 * (i % N) / N;
        double dx = radius * Math.cos(angle);
        double dy = radius * Math.sin(angle);
        double lat = centerLat + (180 / Math.PI) * (dy / EARTH_RADIUS);
        double lon = centerLon + (180 / Math.PI) * (dx / EARTH_RADIUS) / Math.cos(centerLat * Math.PI / 180);
        points.add(proj.fromWgs84(new MapPos(lon, lat)));
    }
    return points;
}
Example 44
Project: hourlyweather-master  File: WidgetForecastFetcherTask.java View source code
@Override
protected void onPostExecute(HourlyForecast forecast) {
    loadingDialog.dismiss();
    if (location == null) {
        NotificationUtil.popErrorDialog(configActivity, "Location not avaliable", "Press ok to try and refresh your current position", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                new LocationResolver(configActivity).execute();
            }
        });
    } else if (forecast == null) {
        // error has occured, alert the user
        NotificationUtil.popNetworkErrorDialog(configActivity);
    } else {
        configActivity.forecastLoaded(forecast);
    }
}
Example 45
Project: i-board-master  File: AppLocationService.java View source code
public Location getLocation(String provider) {
    if (locationManager.isProviderEnabled(provider)) {
        locationManager.requestLocationUpdates(provider, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
        if (locationManager != null) {
            location = locationManager.getLastKnownLocation(provider);
            return location;
        }
    }
    return null;
}
Example 46
Project: InTheClear-master  File: MovementTracker.java View source code
public static double[] updateLocation() {
    try {
        String bestProvider = lm.getBestProvider(criteria, false);
        Location l = lm.getLastKnownLocation(bestProvider);
        return new double[] { l.getLatitude(), l.getLongitude() };
    } catch (NullPointerException e) {
        Log.d(ITCConstants.Log.ITC, e.toString());
        return null;
    }
}
Example 47
Project: JASONETTE-Android-master  File: JasonGeoAction.java View source code
public void onLocationChanged(Location location) {
    try {
        JSONObject ret = new JSONObject();
        String val = String.format("%f,%f", location.getLatitude(), location.getLongitude());
        ret.put("coord", val);
        ret.put("value", val);
        JasonHelper.next("success", action, ret, event, context);
    } catch (Exception e) {
        Log.d("Error", e.toString());
    }
}
Example 48
Project: kevoree-library-master  File: LocationUtils.java View source code
/**
	 * Get the most recent location from the GPS or Network provider.
	 * @param pLocationManager
	 * @return return the most recent location, or null if there's no known location
	 */
public static Location getLastKnownLocation(final LocationManager pLocationManager) {
    if (pLocationManager == null) {
        return null;
    }
    final Location gpsLocation = pLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    final Location networkLocation = pLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    if (gpsLocation == null) {
        return networkLocation;
    } else if (networkLocation == null) {
        return gpsLocation;
    } else {
        // both are non-null - use the most recent
        if (networkLocation.getTime() > gpsLocation.getTime() + GPS_WAIT_TIME) {
            return networkLocation;
        } else {
            return gpsLocation;
        }
    }
}
Example 49
Project: LightSDKAndroid-master  File: LocationUtil.java View source code
public void getLocation(Context context, final Result success) {
    manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    String provider = manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) ? LocationManager.NETWORK_PROVIDER : LocationManager.GPS_PROVIDER;
    manager.requestLocationUpdates(provider, 0, 0, new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            if (success != null) {
                success.onFinished(location.getLatitude(), location.getLongitude());
            }
            manager.removeUpdates(this);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Logger.d(provider);
        }

        @Override
        public void onProviderEnabled(String provider) {
            Logger.d(provider);
        }

        @Override
        public void onProviderDisabled(String provider) {
            Logger.d(provider);
        }
    });
}
Example 50
Project: MapLite-master  File: LocationUtils.java View source code
/**
	 * Get the most recent location from the GPS or Network provider.
	 *
	 * @return return the most recent location, or null if there's no known location
	 */
public static Location getLastKnownLocation(final LocationManager pLocationManager) {
    if (pLocationManager == null) {
        return null;
    }
    final Location gpsLocation = getLastKnownLocation(pLocationManager, LocationManager.GPS_PROVIDER);
    final Location networkLocation = getLastKnownLocation(pLocationManager, LocationManager.NETWORK_PROVIDER);
    if (gpsLocation == null) {
        return networkLocation;
    } else if (networkLocation == null) {
        return gpsLocation;
    } else {
        // both are non-null - use the most recent
        if (networkLocation.getTime() > gpsLocation.getTime() + GPS_WAIT_TIME) {
            return networkLocation;
        } else {
            return gpsLocation;
        }
    }
}
Example 51
Project: MiBandDecompiled-master  File: SosoLocationListener.java View source code
public void onLocationUpdate(d d1) {
    c.c("openSDK_LOG", (new StringBuilder()).append("location: onLocationUpdate = ").append(d1).toString());
    super.onLocationUpdate(d1);
    if (d1 != null) {
        Location location = new Location("passive");
        location.setLatitude(d1.b);
        location.setLongitude(d1.c);
        if (a != null) {
            a.onLocationUpdate(location);
            return;
        }
    }
}
Example 52
Project: mirror-master  File: GeoLocation.java View source code
/**
   * Makes a request to the geo location API and returns the current location or {@code null} on
   * error.
   */
public static Location getLocation() {
    String response = Network.get(GEO_IP_URL);
    if (response == null) {
        Log.e(TAG, "Empty response.");
        return null;
    }
    // Parse the latitude and longitude from the response JSON.
    try {
        JSONObject responseJson = new JSONObject(response);
        double latitude = responseJson.getDouble("lat");
        double longitude = responseJson.getDouble("lon");
        Location location = new Location("");
        location.setLatitude(latitude);
        location.setLongitude(longitude);
        return location;
    } catch (JSONException e) {
        Log.e(TAG, "Failed to parse geo location JSON.");
        return null;
    }
}
Example 53
Project: MozStumbler-master  File: LocationUtils.java View source code
/**
     * Get the most recent location from the GPS or Network provider.
     *
     * @return return the most recent location, or null if there's no known location
     */
public static Location getLastKnownLocation(final LocationManager pLocationManager) {
    if (pLocationManager == null) {
        return null;
    }
    final Location gpsLocation = getLastKnownLocation(pLocationManager, LocationManager.GPS_PROVIDER);
    final Location networkLocation = getLastKnownLocation(pLocationManager, LocationManager.NETWORK_PROVIDER);
    if (gpsLocation == null) {
        return networkLocation;
    } else if (networkLocation == null) {
        return gpsLocation;
    } else {
        // both are non-null - use the most recent
        if (networkLocation.getTime() > gpsLocation.getTime() + GPS_WAIT_TIME) {
            return networkLocation;
        } else {
            return gpsLocation;
        }
    }
}
Example 54
Project: mywebio-sdk-master  File: LocationExample.java View source code
private JSONObject getLocationFromProvider(String provider) throws JSONException {
    Location l = lm.getLastKnownLocation(provider);
    JSONObject jl = new JSONObject();
    if (l != null) {
        jl.put("provider", provider);
        jl.put("longitude", l.getLongitude());
        jl.put("latitude", l.getLatitude());
        jl.put("time", l.getTime());
        if (l.hasAccuracy())
            jl.put("accuracy", l.getAccuracy());
        if (l.hasAltitude())
            jl.put("altitude", l.getAltitude());
        if (l.hasBearing())
            jl.put("bearing", l.getBearing());
        if (l.hasSpeed())
            jl.put("speed", l.getSpeed());
    }
    return jl;
}
Example 55
Project: osmdroid-master  File: LocationUtils.java View source code
/**
	 * Get the most recent location from the GPS or Network provider.
	 *
	 * @return return the most recent location, or null if there's no known location
	 */
public static Location getLastKnownLocation(final LocationManager pLocationManager) {
    if (pLocationManager == null) {
        return null;
    }
    final Location gpsLocation = getLastKnownLocation(pLocationManager, LocationManager.GPS_PROVIDER);
    final Location networkLocation = getLastKnownLocation(pLocationManager, LocationManager.NETWORK_PROVIDER);
    if (gpsLocation == null) {
        return networkLocation;
    } else if (networkLocation == null) {
        return gpsLocation;
    } else {
        // both are non-null - use the most recent
        if (networkLocation.getTime() > gpsLocation.getTime() + Configuration.getInstance().getGpsWaitTime()) {
            return networkLocation;
        } else {
            return gpsLocation;
        }
    }
}
Example 56
Project: PanicButton-master  File: LocationFormatterTest.java View source code
@Test
public void shouldReturnGoogleMapUrlForTheGivenLocation() {
    double latitude = -183.123456;
    double longitude = 78.654321;
    Location location = LocationTestUtil.location(NETWORK_PROVIDER, latitude, longitude, currentTimeMillis(), 10.0f);
    String expectedMessage = "I\\'m at https://maps.google.com/maps?q=" + latitude + "," + longitude + " via network";
    LocationFormatter locationFormatter = new LocationFormatter(location);
    assertEquals(expectedMessage, locationFormatter.format(context));
}
Example 57
Project: popa-master  File: LocationListener.java View source code
@Override
public void onProviderDisabled(String s) {
    Log.e("Provider", "Provider Disable");
    AlertDialog.Builder builderSingle = new AlertDialog.Builder(mActivity);
    builderSingle.setIcon(android.R.drawable.stat_sys_warning);
    builderSingle.setTitle("Location Service Disable");
    builderSingle.show();
//ToDo View Leak in There fix asap
}
Example 58
Project: pps_android-master  File: GPSLocationService.java View source code
public static String getLocation(Context context) {
    // »ñȡλÖùÜÀí·þÎñ   
    LocationManager locationManager;
    String serviceName = Context.LOCATION_SERVICE;
    locationManager = (LocationManager) context.getSystemService(serviceName);
    // ²éÕÒµ½·þÎñÐÅÏ¢   
    Criteria criteria = new Criteria();
    // ¸ß¾«¶È   
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    // µÍ¹¦ºÄ   
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    // »ñÈ¡GPSÐÅÏ¢   
    String provider = locationManager.getBestProvider(criteria, true);
    // ͨ¹ýGPS»ñȡλÖà  
    Location location = locationManager.getLastKnownLocation(provider);
    if (location != null) {
        double lat = location.getLatitude();
        double longti = location.getLongitude();
        double ati = location.getAltitude();
        return String.valueOf("latitude = " + lat + "--longitude = " + longti + "--altitude = " + ati);
    }
    return "»ñÈ¡²»µ½GPSÐÅÏ¢";
}
Example 59
Project: ratebeerforandroid-master  File: PassiveLocationUpdateReceiver.java View source code
@Override
public void onReceive(Context context, Intent intent) {
    // We should have a location in our extras, which is the passively received user location
    if (!intent.hasExtra(LocationManager.KEY_LOCATION_CHANGED))
        return;
    // Store the new location
    Location location = (Location) intent.getExtras().get(LocationManager.KEY_LOCATION_CHANGED);
    applicationSettings.saveLastUserLocation(location);
}
Example 60
Project: rex-weather-master  File: LocationService.java View source code
@Override
public void call(final Subscriber<? super Location> subscriber) {
    final LocationListener locationListener = new LocationListener() {

        public void onLocationChanged(final Location location) {
            subscriber.onNext(location);
            subscriber.onCompleted();
            Looper.myLooper().quit();
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onProviderDisabled(String provider) {
        }
    };
    final Criteria locationCriteria = new Criteria();
    locationCriteria.setAccuracy(Criteria.ACCURACY_COARSE);
    locationCriteria.setPowerRequirement(Criteria.POWER_LOW);
    final String locationProvider = mLocationManager.getBestProvider(locationCriteria, true);
    Looper.prepare();
    mLocationManager.requestSingleUpdate(locationProvider, locationListener, Looper.myLooper());
    Looper.loop();
}
Example 61
Project: SimpleThermometerProject-master  File: LocationUtils.java View source code
public static Location getLastKnownLocation(Context context, String provider) {
    Location result = null;
    //retrieve an instance of the LocationManager
    final LocationManager locationManager = (LocationManager) context.getSystemService(Service.LOCATION_SERVICE);
    // Retrieve the location from the provider
    result = locationManager.getLastKnownLocation(provider);
    return result;
}
Example 62
Project: slimrepo-master  File: ParcelableTypeMappingInstaller.java View source code
@Override
public void install(FieldTypeMappingRegistrar registrar) {
    ParcelableTypeConverter.install(registrar, Bundle.class, Bundle.CREATOR);
    ParcelableTypeConverter.install(registrar, Bitmap.class, Bitmap.CREATOR);
    ParcelableTypeConverter.install(registrar, Address.class, Address.CREATOR);
    ParcelableTypeConverter.install(registrar, Location.class, Location.CREATOR);
    ParcelableTypeConverter.install(registrar, Intent.class, Intent.CREATOR);
    ParcelableTypeConverter.install(registrar, Gesture.class, Gesture.CREATOR);
    ParcelableTypeConverter.install(registrar, Uri.class, Uri.CREATOR);
}
Example 63
Project: Tagsnap-master  File: ReverseGeocodingService.java View source code
@Override
protected Void doInBackground(Location... locations) {
    Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
    Location loc = locations[0];
    List<Address> addresses = null;
    try {
        // get all the addresses fro the given latitude, and longitude
        addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
    } catch (IOException e) {
        mAddress = null;
    }
    // if we have at least one address, use it
    if (addresses != null && addresses.size() > 0) {
        mAddress = addresses.get(0);
    }
    return null;
}
Example 64
Project: transita-master  File: GeoListener.java View source code
void success(Location loc) {
    /*
		 * We only need to figure out what we do when we succeed!
		 */
    if (id != "global") {
        mAppView.loadUrl("javascript:Geolocation.success(" + id + ", " + loc.getLatitude() + ", " + loc.getLongitude() + ")");
    } else {
        mAppView.loadUrl("javascript:Geolocation.gotCurrentPosition(" + loc.getLatitude() + ", " + loc.getLongitude() + ")");
        this.stop();
    }
}
Example 65
Project: TruckMuncher-Android-master  File: VendorHomeServiceHelper.java View source code
void changeServingState(Context context, String truckId, boolean isServing, Location location) {
    ContentValues values = new ContentValues();
    values.put(PublicContract.Truck.LATITUDE, location.getLatitude());
    values.put(PublicContract.Truck.LONGITUDE, location.getLongitude());
    values.put(PublicContract.Truck.IS_SERVING, isServing);
    values.put(Contract.TruckState.IS_DIRTY, true);
    Uri uri = Contract.syncToNetwork(Contract.TRUCK_STATE_URI);
    WhereClause whereClause = new WhereClause.Builder().where(PublicContract.Truck.ID, EQUALS, truckId).build();
    AsyncQueryHandler queryHandler = new SimpleAsyncQueryHandler(context.getContentResolver());
    queryHandler.startUpdate(0, null, uri, values, whereClause.selection, whereClause.selectionArgs);
}
Example 66
Project: tuberun_android-master  File: StationsTubeFetcher.java View source code
@Override
protected ArrayList<Station> doInBackground(Location... at) {
    // android.os.Debug.waitForDebugger();
    ArrayList<Station> res = new ArrayList<Station>();
    DatabaseHelper myDbHelper = new DatabaseHelper(context);
    try {
        myDbHelper.openDataBase();
        res = myDbHelper.getTubeStationsNearby((long) (at[0].getLatitude() * 1000000), (long) (at[0].getLongitude() * 1000000));
        res = getNearbyStations(at[0], res, 8);
    } catch (Exception e) {
        Log.w("StationsTubeFetcher", e);
    } finally {
        myDbHelper.close();
    }
    return res;
}
Example 67
Project: umd-android-labs-master  File: MockLocationProvider.java View source code
public void pushLocation(double lat, double lon) {
    Location mockLocation = new Location(mProviderName);
    mockLocation.setLatitude(lat);
    mockLocation.setLongitude(lon);
    mockLocation.setAltitude(0);
    mockLocation.setTime(System.currentTimeMillis());
    mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    mockLocation.setAccuracy(mockAccuracy);
    mLocationManager.setTestProviderLocation(mProviderName, mockLocation);
}
Example 68
Project: viaja-facil-master  File: MyLocationListener.java View source code
@Override
public void onLocationChanged(Location location) {
    /*		int lat = (int) (location.getLatitude());
		int lng = (int) (location.getLongitude());
		System.out.println("Lat: " + lat + " Lon: " + lng);*/
    if (bestLocation == null || location.hasAccuracy() && ((location.getAccuracy() < bestLocation.getAccuracy() || !bestLocation.hasAccuracy()) || location.getAccuracy() < 80)) {
        bestLocation = location;
    }
}
Example 69
Project: wearscript-android-master  File: GPSDataProvider.java View source code
@Override
public void onLocationChanged(Location l) {
    long timestamp = System.nanoTime();
    DataPoint dataPoint = new DataPoint(GPSDataProvider.this, System.currentTimeMillis() / 1000., timestamp);
    dataPoint.addValue(Double.valueOf(l.getLatitude()));
    dataPoint.addValue(Double.valueOf(l.getLongitude()));
    dataPoint.addValue(Double.valueOf(l.getSpeed()));
    dataPoint.addValue(Double.valueOf(l.getBearing()));
    parent.queue(dataPoint);
}
Example 70
Project: XobotOS-master  File: ILocationListener.java View source code
@Override
public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException {
    switch(code) {
        case INTERFACE_TRANSACTION:
            {
                reply.writeString(DESCRIPTOR);
                return true;
            }
        case TRANSACTION_onLocationChanged:
            {
                data.enforceInterface(DESCRIPTOR);
                android.location.Location _arg0;
                if ((0 != data.readInt())) {
                    _arg0 = android.location.Location.CREATOR.createFromParcel(data);
                } else {
                    _arg0 = null;
                }
                this.onLocationChanged(_arg0);
                return true;
            }
        case TRANSACTION_onStatusChanged:
            {
                data.enforceInterface(DESCRIPTOR);
                java.lang.String _arg0;
                _arg0 = data.readString();
                int _arg1;
                _arg1 = data.readInt();
                android.os.Bundle _arg2;
                if ((0 != data.readInt())) {
                    _arg2 = android.os.Bundle.CREATOR.createFromParcel(data);
                } else {
                    _arg2 = null;
                }
                this.onStatusChanged(_arg0, _arg1, _arg2);
                return true;
            }
        case TRANSACTION_onProviderEnabled:
            {
                data.enforceInterface(DESCRIPTOR);
                java.lang.String _arg0;
                _arg0 = data.readString();
                this.onProviderEnabled(_arg0);
                return true;
            }
        case TRANSACTION_onProviderDisabled:
            {
                data.enforceInterface(DESCRIPTOR);
                java.lang.String _arg0;
                _arg0 = data.readString();
                this.onProviderDisabled(_arg0);
                return true;
            }
    }
    return super.onTransact(code, data, reply, flags);
}
Example 71
Project: WiFi-Automatic-master  File: Database.java View source code
/**
     * Gets a list of saved locations
     *
     * @return the list of locations, might be empty
     */
public List<Location> getLocations() {
    Cursor c = getReadableDatabase().query("locations", new String[] { "name", "lat", "lon" }, null, null, null, null, null);
    c.moveToFirst();
    List<Location> re = new ArrayList<>(c.getCount());
    while (!c.isAfterLast()) {
        if (BuildConfig.DEBUG)
            Logger.log("added location: " + c.getString(0) + " " + c.getDouble(1) + " " + c.getDouble(2));
        re.add(new Location(c.getString(0), new LatLng(c.getDouble(1), c.getDouble(2))));
        c.moveToNext();
    }
    c.close();
    return re;
}
Example 72
Project: levelup-sdk-android-master  File: AppLocationListRequestFactory.java View source code
@Nullable
private Map<String, String> buildQueryParams(@Nullable final android.location.Location location) {
    Map<String, String> queryParams = null;
    if (null != location) {
        queryParams = new HashMap<String, String>();
        queryParams.put(PARAM_LAT, Double.toString(location.getLatitude()));
        queryParams.put(PARAM_LNG, Double.toString(location.getLongitude()));
    }
    return queryParams;
}
Example 73
Project: Mapsforge-OsmDroid-GraphHopper-master  File: Helper.java View source code
public static android.location.Location getLastBestLocation(Context _context) {
    if (locManager == null)
        locManager = (LocationManager) _context.getSystemService(Context.LOCATION_SERVICE);
    int minDistance = (int) 500;
    long minTime = System.currentTimeMillis() - (900 * 1000);
    android.location.Location bestResult = null;
    float bestAccuracy = Float.MAX_VALUE;
    long bestTime = Long.MIN_VALUE;
    // Iterate through all the providers on the system, keeping
    // note of the most accurate result within the acceptable time limit.
    // If no result is found within maxTime, return the newest Location.
    List<String> matchingProviders = locManager.getAllProviders();
    for (String provider : matchingProviders) {
        android.location.Location location = locManager.getLastKnownLocation(provider);
        if (location != null) {
            //                log(TAG, " location: " + location.getLatitude() + "," + location.getLongitude() + "," + location.getAccuracy() + "," + location.getSpeed() + "m/s");
            float accuracy = location.getAccuracy();
            long time = location.getTime();
            //                if ((time > minTime && accuracy < bestAccuracy)) {
            if (accuracy < bestAccuracy) {
                bestResult = location;
                bestAccuracy = accuracy;
                bestTime = time;
            }
        }
    }
    return bestResult;
}
Example 74
Project: QuickSnap-master  File: CameraApplication.java View source code
public void requestLocationUpdate(boolean forceUpdate) {
    // Only request the location once an hour unless forceUpdate is set
    if (!forceUpdate && (System.currentTimeMillis() - mLocationLastUpdateTime < 1000 * 60 * 60)) {
        return;
    }
    mLocationLastUpdateTime = System.currentTimeMillis();
    MyLocation myLocation = new MyLocation(this);
    myLocation.requestCurrentLocation(new LocationResult() {

        @Override
        public void gotLocation(final android.location.Location location) {
            Thread thread = new Thread(new Runnable() {

                @Override
                public void run() {
                    updateWithNewLocation(location);
                }
            });
            thread.start();
        }
    });
}
Example 75
Project: StreetlightSeattleReporter-master  File: MyLocationListener.java View source code
/* Update application based on new location
	 * @see android.location.LocationListener#onLocationChanged(android.location.Location)
	 */
@Override
public void onLocationChanged(Location location) {
    locationManager.removeUpdates(this);
    String address = "Could not find location.";
    this.location = location;
    new MyAsyncTask().execute(address);
//		if (location != null) {
//			address = findStreetAddress(location);
//		}
//	    Intent broadcastIntent = new Intent();
//	    broadcastIntent.setAction(MainActivity.LOCATION_QUERY_STR);
//	    broadcastIntent.putExtra("address", address);
//	    context.sendBroadcast(broadcastIntent);
}
Example 76
Project: 24hAnalogWidget-master  File: WearFaceDemoActivity.java View source code
private void setDemoData() {
    final Calendar time = Calendar.getInstance(TimeZone.getTimeZone("America/Guatemala"));
    // A time that will put the hands at "10:10", is near the equinox,
    // and shows the month rollover.
    time.set(2014, 8, 30, 8, 10, 0);
    mClock.setTime(time);
    final Location location = new Location("demo");
    // Somewhere in Guatemala. This puts solar noon at actual noon.
    location.setLatitude(15.26);
    location.setLongitude(-92.13);
    mSunPositionOverlay.setLocation(location);
}
Example 77
Project: android-15-master  File: ExternalSharedPermsTest.java View source code
/** The use of location manager and bluetooth below are simply to simulate an app that
     *  tries to use them, so we can verify whether permissions are granted and accessible.
     * */
public void testRunLocationAndBluetooth() {
    LocationManager locationManager = (LocationManager) getInstrumentation().getContext().getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {

        public void onLocationChanged(Location location) {
        }

        public void onProviderDisabled(String provider) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    });
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if ((mBluetoothAdapter != null) && (!mBluetoothAdapter.isEnabled())) {
        mBluetoothAdapter.getName();
    }
}
Example 78
Project: android-app-common-tasks-master  File: GetCurrentLocationAct.java View source code
@Override
public void onClick(View v) {
    //                if (Common.isNetworkAvailable(mContext)) {
    //                    if (Common.getGpsStatus(mContext)) {
    Location location = Common.getCurrentLocation(mContext);
    if (location != null) {
        tvLatitude.setText("" + location.getLatitude());
        tvLongitude.setText("" + location.getLongitude());
    } else {
        Common.showGPSDisabledAlert("Please enable your location or connect to cellular network.", GetCurrentLocationAct.this);
    }
//                    } else {
//                        Common.showGPSDisabledAlert("Please enable your location.", mContext);
//                    }
//                } else {
//                    Toast.makeText(mContext, "Please Connect your device with internet.", Toast.LENGTH_LONG).show();
//                    Common.showNETWORDDisabledAlert(mContext);
//                }
}
Example 79
Project: android-examples-master  File: MainActivity.java View source code
/**
     * Sets location listening.
     */
void setupLocationListening() {
    LocationManager locationManager;
    LocationListener locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            TextView longitude = (TextView) findViewById(R.id.textView_lon);
            TextView latitude = (TextView) findViewById(R.id.textView_lat);
            longitude.setText("Longitude:" + location.getLongitude());
            latitude.setText("Latitude:" + location.getLatitude());
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {
        }

        @Override
        public void onProviderEnabled(String s) {
        }

        @Override
        public void onProviderDisabled(String s) {
        }
    };
    String mprovider;
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    mprovider = locationManager.getBestProvider(criteria, false);
    if (mprovider != null && !mprovider.equals("")) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Location location = locationManager.getLastKnownLocation(mprovider);
        locationManager.requestLocationUpdates(mprovider, 15000, 1, locationListener);
        if (location != null)
            locationListener.onLocationChanged(location);
        else
            Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
    }
}
Example 80
Project: android-question-answer-app-master  File: AddCommentDialogFragment.java View source code
@Override
public void onClick(DialogInterface dialog, int which) {
    EditText body = (EditText) viewComment.findViewById(R.id.add_comment_body);
    CheckBox commentLocation = (CheckBox) viewComment.findViewById(R.id.commentLocationBox);
    Location loc = null;
    if (commentLocation.isChecked()) {
        LocationManager lm = (LocationManager) getActivity().getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        } else {
            Toast.makeText(getActivity().getApplicationContext(), "Please enable GPS to use Location Service", Toast.LENGTH_SHORT).show();
        }
    }
    ((AddCommentDialogCallback) getActivity()).addCommentCallback(body.getText().toString(), loc);
}
Example 81
Project: android-sdk-sources-for-api-level-23-master  File: ExternalSharedPermsTest.java View source code
/** The use of location manager and bluetooth below are simply to simulate an app that
     *  tries to use them, so we can verify whether permissions are granted and accessible.
     * */
public void testRunLocationAndBluetooth() {
    LocationManager locationManager = (LocationManager) getInstrumentation().getContext().getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {

        public void onLocationChanged(Location location) {
        }

        public void onProviderDisabled(String provider) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    });
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if ((mBluetoothAdapter != null) && (!mBluetoothAdapter.isEnabled())) {
        mBluetoothAdapter.getName();
    }
}
Example 82
Project: Android-Templates-And-Utilities-master  File: ExampleFragment.java View source code
public void run() {
    // view was destroyed
    if (mRootView == null)
        return;
    Logcat.d("onGeolocationRespond() = " + location.getProvider() + " / " + location.getLatitude() + " / " + location.getLongitude() + " / " + new Date(location.getTime()).toString());
    mLocation = new Location(location);
// TODO
}
Example 83
Project: androidperformance-master  File: GPSTask.java View source code
@Override
public void gotLocation(final Location location) {
    GPS gps = new GPS();
    if (location != null) {
        gps.setAltitude("" + location.getAltitude());
        gps.setLatitude("" + location.getLatitude());
        gps.setLongitude("" + location.getLongitude());
        isRunning = false;
        responseListener.onCompleteGPS(gps);
    }
    isRunning = false;
    gps = new GPS("Not Found", "Not Found", "Not Found");
    responseListener.onCompleteGPS(gps);
}
Example 84
Project: android_frameworks_base-master  File: ExternalSharedPermsFLTest.java View source code
/** The use of location manager below is simply to simulate an app that
     *  tries to use it, so we can verify whether permissions are granted and accessible.
     * */
public void testRunFineLocation() {
    LocationManager locationManager = (LocationManager) getInstrumentation().getContext().getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {

        public void onLocationChanged(Location location) {
        }

        public void onProviderDisabled(String provider) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    });
}
Example 85
Project: android_packages_apps_Roadrunner-master  File: MathUtils.java View source code
/**
	 * calculate great circle distance in meters
	 * @param pos1 a Location object
	 * @param pos2 a Location object
	 * @return the distance between the two locations in meters 
	 */
public static double getDistanceGreatCircle(Location pos1, Location pos2) {
    double lat1 = pos1.getLatitude();
    double long1 = pos1.getLongitude();
    double lat2 = pos2.getLatitude();
    double long2 = pos2.getLongitude();
    double earthRadius = 3958.75;
    double dLat = Math.toRadians(lat2 - lat1);
    double dLng = Math.toRadians(long2 - long1);
    double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2) * Math.sin(dLng / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double dist = earthRadius * c;
    int meterConversion = 1609;
    return dist * meterConversion;
}
Example 86
Project: apps-master  File: MainActivity.java View source code
/**
     * Sets location listening.
     */
void setupLocationListening() {
    LocationManager locationManager;
    LocationListener locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            TextView longitude = (TextView) findViewById(R.id.textView_lon);
            TextView latitude = (TextView) findViewById(R.id.textView_lat);
            longitude.setText("Longitude:" + location.getLongitude());
            latitude.setText("Latitude:" + location.getLatitude());
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {
        }

        @Override
        public void onProviderEnabled(String s) {
        }

        @Override
        public void onProviderDisabled(String s) {
        }
    };
    String mprovider;
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    mprovider = locationManager.getBestProvider(criteria, false);
    if (mprovider != null && !mprovider.equals("")) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Location location = locationManager.getLastKnownLocation(mprovider);
        locationManager.requestLocationUpdates(mprovider, 15000, 1, locationListener);
        if (location != null)
            locationListener.onLocationChanged(location);
        else
            Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
    }
}
Example 87
Project: bblfr-android-master  File: MapUtils.java View source code
public static void moveToCurrentLocation(GoogleMap map, List<Marker> markers, Location lastLocation, float zoom) {
    map.setMyLocationEnabled(true);
    if (lastLocation == null && markers != null && !markers.isEmpty()) {
        moveToMarkerBounds(map, markers);
    } else if (lastLocation != null) {
        LatLng currentLocation = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude());
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, zoom));
    } else {
        Timber.w("Both lastLocation and markers are null");
    }
}
Example 88
Project: BeTrains-for-Android-master  File: FixedMyLocationOverlay.java View source code
@Override
protected void drawMyLocation(Canvas canvas, MapView mapView, Location lastFix, GeoPoint myLoc, long when) {
    if (!bugged) {
        try {
            super.drawMyLocation(canvas, mapView, lastFix, myLoc, when);
        } catch (Exception e) {
            bugged = true;
        }
    }
    if (bugged) {
        if (drawable == null) {
            accuracyPaint = new Paint();
            accuracyPaint.setAntiAlias(true);
            accuracyPaint.setStrokeWidth(2.0f);
            drawable = mapView.getContext().getResources().getDrawable(R.drawable.mylocation);
            width = drawable.getIntrinsicWidth();
            height = drawable.getIntrinsicHeight();
            center = new Point();
            left = new Point();
        }
        Projection projection = mapView.getProjection();
        double latitude = lastFix.getLatitude();
        double longitude = lastFix.getLongitude();
        float accuracy = lastFix.getAccuracy();
        float[] result = new float[1];
        Location.distanceBetween(latitude, longitude, latitude, longitude + 1, result);
        float longitudeLineDistance = result[0];
        GeoPoint leftGeo = new GeoPoint((int) (latitude * 1e6), (int) ((longitude - accuracy / longitudeLineDistance) * 1e6));
        projection.toPixels(leftGeo, left);
        projection.toPixels(myLoc, center);
        int radius = center.x - left.x;
        accuracyPaint.setColor(0xff6666ff);
        accuracyPaint.setStyle(Style.STROKE);
        canvas.drawCircle(center.x, center.y, radius, accuracyPaint);
        accuracyPaint.setColor(0x186666ff);
        accuracyPaint.setStyle(Style.FILL);
        canvas.drawCircle(center.x, center.y, radius, accuracyPaint);
        drawable.setBounds(center.x - width / 2, center.y - height / 2, center.x + width / 2, center.y + height / 2);
        drawable.draw(canvas);
    }
}
Example 89
Project: BetterBatteryStats-master  File: GeoUtils.java View source code
public static String getNearestAddress(Context ctx, Location loc) {
    if (!DataNetwork.hasDataConnection(ctx)) {
        return "";
    }
    Address address = getGeoData(ctx, loc);
    String strRet = "";
    if (address != null) {
        String addr0 = address.getAddressLine(0);
        String addr1 = address.getAddressLine(1);
        if (!addr0.equals("")) {
            strRet = addr0;
        }
        if (!addr1.equals("")) {
            if (!strRet.equals("")) {
                strRet = strRet + ", ";
            }
            strRet = strRet + addr1;
        }
    }
    return strRet;
}
Example 90
Project: bikey-master  File: SlopeMeter.java View source code
@Override
public void onLocationChanged(Location location) {
    if (mLastLocation == null) {
        mLastLocation = location;
    } else {
        LocationPair locationPair = new LocationPair(mLastLocation, location);
        if (locationPair.getDistance() >= MIN_DISTANCE) {
            mLocationPair = locationPair;
            mDebugInfo.lastLocationPair = mLocationPair;
            mLastLocation = location;
        }
    }
}
Example 91
Project: BothShare-master  File: LocationManagerUtil.java View source code
public Location getLocation(Context mContext) {
    Location location = null;
    double latitude = 0d;
    double longitude = 0d;
    try {
        LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        // getting GPS status
        Boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // getting network status
        Boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (!isGPSEnabled && !isNetworkEnabled) {
            location = null;
        } else {
            Boolean canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationRequestLisener());
                Log.d("Network", "Network Enabled");
                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, 0, 0, new LocationRequestLisener());
                    Log.d("GPS", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return location;
}
Example 92
Project: CodenameOne-master  File: CodenameOneBackgroundLocationActivity.java View source code
@Override
protected void onStart() {
    super.onStart();
    if (!Display.isInitialized()) {
        //Display.init(this);
        // This should never happen because Android will load the main activity first
        // automatically when we call startActivity()... and that will initialize the display
        Log.d("CN1", "Display is not initialized.  Cannot deliver background location update");
        finish();
        return;
    }
    Bundle b = getIntent().getExtras();
    if (b != null) {
        String locationClass = b.getString("backgroundLocation");
        Location location = b.getParcelable("Location");
        try {
            //the 2nd parameter is the class name we need to create
            LocationListener l = (LocationListener) Class.forName(locationClass).newInstance();
            l.locationUpdated(AndroidLocationManager.convert(location));
        } catch (Exception e) {
            Log.e("Codename One", "background location error", e);
        }
    }
    //finish this activity once the Location has been handled
    finish();
}
Example 93
Project: common-app-master  File: GetCurrentLocationAct.java View source code
@Override
public void onClick(View v) {
    //                if (Common.isNetworkAvailable(mContext)) {
    //                    if (Common.getGpsStatus(mContext)) {
    Location location = Common.getCurrentLocation(mContext);
    if (location != null) {
        tvLatitude.setText("" + location.getLatitude());
        tvLongitude.setText("" + location.getLongitude());
    } else {
        Common.showGPSDisabledAlert("Please enable your location or connect to cellular network.", GetCurrentLocationAct.this);
    }
//                    } else {
//                        Common.showGPSDisabledAlert("Please enable your location.", mContext);
//                    }
//                } else {
//                    Toast.makeText(mContext, "Please Connect your device with internet.", Toast.LENGTH_LONG).show();
//                    Common.showNETWORDDisabledAlert(mContext);
//                }
}
Example 94
Project: core-android-master  File: GPSLocatorDistance.java View source code
public void onLocationChanged(Location location) {
    float actualDistance = 0;
    synchronized (this) {
        if (this.location == null) {
            this.location = new Location(location);
            this.location.setLatitude(latitude);
            this.location.setLongitude(longitude);
        }
        actualDistance = this.location.distanceTo(location);
    }
    if (actualDistance < distance) {
        if (!entered) {
            rangeObserver.notification(true);
            entered = true;
        } else {
            if (Cfg.DEBUG) {
                Check.log(TAG + " Already entered");
            }
        }
    } else {
        if (entered) {
            rangeObserver.notification(false);
            entered = false;
        } else {
            if (Cfg.DEBUG) {
                Check.log(//$NON-NLS-1$
                TAG + //$NON-NLS-1$
                " Already exited");
            }
        }
    }
}
Example 95
Project: CZD_Android_Lib-master  File: LocationUtil.java View source code
public static String getAddress(Context context, Location loc) {
    String result = "";
    Geocoder gc = new Geocoder(context, Locale.getDefault());
    try {
        List<Address> addresses = gc.getFromLocation(loc.getLatitude(), loc.getLongitude(), 10);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            int maxLine = address.getMaxAddressLineIndex();
            if (maxLine >= 2) {
                result = address.getAddressLine(1) + address.getAddressLine(2);
            } else {
                result = address.getAddressLine(1);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}
Example 96
Project: evercam-discover-android-master  File: LocationReader.java View source code
private void launchListener() {
    listener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            if (currentLocation == null) {
                currentLocation = location;
            } else {
                locationManager.removeUpdates(this);
            }
            Log.d(TAG, location.getLongitude() + "   " + location.getLatitude());
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }
    };
    // locationManager.requestSingleUpdate(provider, listener, null);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
}
Example 97
Project: FineGeotag-master  File: ExifInterfaceEx.java View source code
public void setLocation(Location location) {
    // Latitude
    double lat = location.getLatitude();
    this.setAttribute(TAG_GPS_LATITUDE_REF, lat > 0 ? "N" : "S");
    this.setAttribute(TAG_GPS_LATITUDE, DMS(lat));
    // Longitude
    double lon = location.getLongitude();
    this.setAttribute(TAG_GPS_LONGITUDE_REF, lon > 0 ? "E" : "W");
    this.setAttribute(TAG_GPS_LONGITUDE, DMS(lon));
    // Date/time
    Date date = new Date(location.getTime());
    this.setAttribute(TAG_GPS_DATESTAMP, new SimpleDateFormat("y:M:d").format(date));
    this.setAttribute(TAG_GPS_TIMESTAMP, new SimpleDateFormat("H:m:s").format(date));
    // Altitude
    if (location.hasAltitude()) {
        double altitude = location.getAltitude();
        this.setAttribute(TAG_GPS_ALTITUDE_REF, altitude > 0 ? "0" : "1");
        this.setAttribute(TAG_GPS_ALTITUDE, String.valueOf(Math.abs(altitude)));
    }
    // Speed
    if (location.hasSpeed()) {
        // Km/h
        this.setAttribute("GPSSpeedRef", "K");
        this.setAttribute("GPSSpeed", String.valueOf(location.getSpeed() * 3600 / 1000));
    }
}
Example 98
Project: flipr-android-master  File: GeocodeTask.java View source code
@Override
protected String doInBackground(Location... params) {
    final Geocoder geocoder = new Geocoder(mContext);
    final Location location = params[0];
    try {
        List<Address> addresses;
        addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        if (addresses.size() > 0) {
            return AddressUtils.addressToName(addresses.get(0));
        }
    } catch (final IOException e) {
        Log.e(TAG, "error looking up location", e);
    }
    return mContext.getString(R.string.geocoder_lookup_unknown_location);
}
Example 99
Project: folio100_frameworks_base-master  File: ExternalSharedPermsFLTest.java View source code
/** The use of location manager below is simply to simulate an app that
     *  tries to use it, so we can verify whether permissions are granted and accessible.
     * */
public void testRunFineLocation() {
    LocationManager locationManager = (LocationManager) getInstrumentation().getContext().getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {

        public void onLocationChanged(Location location) {
        }

        public void onProviderDisabled(String provider) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    });
}
Example 100
Project: frameworks_base_disabled-master  File: ExternalSharedPermsFLTest.java View source code
/** The use of location manager below is simply to simulate an app that
     *  tries to use it, so we can verify whether permissions are granted and accessible.
     * */
public void testRunFineLocation() {
    LocationManager locationManager = (LocationManager) getInstrumentation().getContext().getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {

        public void onLocationChanged(Location location) {
        }

        public void onProviderDisabled(String provider) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    });
}
Example 101
Project: funf-core-android-master  File: LocationProbeTest.java View source code
public void testData() {
    Bundle params = new Bundle();
    params.putLong(Parameter.Builtin.DURATION.name, 30L);
    startProbe(params);
    Bundle data = getData(30 + FUDGE_FACTOR);
    Location location = (Location) data.get("LOCATION");
    assertNotNull(location);
    System.out.println("Accuracy: " + String.valueOf(location.getAccuracy()));
}