android.location.Criteria

Here are the examples of the java api android.location.Criteria taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

51 Examples 7

19 Source : LocationUtils.java
with MIT License
from yangjiantao

/**
 * 设置定位参数
 *
 * @return {@link Criteria}
 */
private static Criteria getCriteria() {
    Criteria criteria = new Criteria();
    // 设置定位精确度 Criteria.ACCURACY_COARSE比较粗略,Criteria.ACCURACY_FINE则比较精细
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    // 设置是否要求速度
    criteria.setSpeedRequired(false);
    // 设置是否允许运营商收费
    criteria.setCostAllowed(false);
    // 设置是否需要方位信息
    criteria.setBearingRequired(false);
    // 设置是否需要海拔信息
    criteria.setAlreplacedudeRequired(false);
    // 设置对电源的需求
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    return criteria;
}

19 Source : Singleton.java
with MIT License
from varunon9

public Location getCurrentLocation() {
    if (getLocation() == null) {
        // fallback to last known location
        Log.d(TAG, "Fallback to getLastKnownLocation using Criteria and provider");
        if (locationManager == null) {
            locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
        }
        Location location = null;
        try {
            Criteria criteria = new Criteria();
            location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
        } catch (SecurityException e) {
            // permission denied
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // setting fused location again
        getLastLocation();
        return location;
    } else {
        Log.d(TAG, "Using FusedLocationProviderClient to get last location");
        return getLocation();
    }
}

19 Source : ShareUtil.java
with Apache License 2.0
from SShineTeam

public Location getLocation(Activity activity) {
    LocationManager locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
    // 查找到服务信息
    Criteria criteria = new Criteria();
    // 高精度
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAlreplacedudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    // 低功耗
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    // 获取GPS信息
    String provider = locationManager.getBestProvider(criteria, false);
    // 通过GPS获取位置
    Location location = locationManager.getLastKnownLocation(provider);
    return location;
}

19 Source : ChatActivity.java
with Apache License 2.0
from rain9155

@SuppressLint("MissingPermission")
private void getLocation() {
    // 配置定位的一些配置信息
    Criteria criteria = new Criteria();
    // 低电耗
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    // 标准精度为粗糙
    criteria.setBearingAccuracy(Criteria.ACCURACY_COARSE);
    // 不需要海拔
    criteria.setAlreplacedudeRequired(false);
    // 不需要导向
    criteria.setBearingRequired(false);
    // 精度为低
    criteria.setAccuracy(Criteria.ACCURACY_LOW);
    // 不需要成本
    criteria.setCostAllowed(false);
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    // 得到最好的位置提供者,如GPS,netWork等
    String bestProvider = locationManager.getBestProvider(criteria, true);
    Log.d(TAG, "provider = " + bestProvider);
    mLocatingDialog.show(getSupportFragmentManager());
    ConnectManager.execute(() -> {
        // 里面存放着定位的信息,经纬度,海拔等
        Location location = null;
        if (!TextUtils.isEmpty(bestProvider)) {
            location = locationManager.getLastKnownLocation(bestProvider);
            Log.d(TAG, "location = " + location);
        } else {
            // 没有最好的定位方案则手动配置
            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
                location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
                location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            else if (locationManager.isProviderEnabled(LocationManager.PreplacedIVE_PROVIDER))
                location = locationManager.getLastKnownLocation(LocationManager.PreplacedIVE_PROVIDER);
        }
        Log.d(TAG, "location = " + location);
        final Location finalLocation = location;
        runOnUiThread(() -> {
            if (finalLocation != null) {
                showLocation(finalLocation);
            } else if (!TextUtils.isEmpty(bestProvider)) {
                locationManager.requestSingleUpdate(bestProvider, new LocationListener() {

                    @Override
                    public void onLocationChanged(Location location) {
                        // 当位置发生改变后就会回调该方法,经纬度相关信息存在Location里面
                        if (mLocatingDialog.isAdded()) {
                            showLocation(location);
                        }
                        Log.d(TAG, "onLocationChanged(), location改变, location = " + location);
                    }

                    @Override
                    public void onStatusChanged(String provider, int status, Bundle extras) {
                        // 3种状态:
                        // LocationProvider.OUT_OF_SERVICE = 0(无服务)
                        // LocationProvider.TEMPORARILY_UNAVAILABLE = 1(provider不可用)
                        // LocationProvider.AVAILABLE = 2(provider可用)
                        Log.d(TAG, "onStatusChanged(), provider状态改变, status = " + status);
                    }

                    @Override
                    public void onProviderEnabled(String provider) {
                        // 当provider可用时被触发
                        Log.d(TAG, "onProviderEnabled(), provider可用, provider = " + provider);
                    }

                    @Override
                    public void onProviderDisabled(String provider) {
                        // 当provider不可用时被触发
                        Log.d(TAG, "onProviderDisabled(), provider不可用, provider = " + provider);
                    }
                }, null);
            } else {
                showLocationFail();
            }
        });
    });
}

19 Source : LocationService.java
with GNU General Public License v3.0
from n37sn4k3

@SuppressLint("MissingPermission")
@RequiresPermission(allOf = { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION })
public void requestSingleUpdate(@Nullable Criteria criteria, boolean enabledOnly) {
    if (mLocationManager == null || mLocationListener == null || criteria == null) {
        LogUtil.w(TAG, "Cannot request single update with criteria best provider");
        return;
    }
    if (!getPackageManager().hreplacedystemFeature(PackageManager.FEATURE_LOCATION)) {
        LogUtil.w(TAG, "Cannot request single update with criteria best provider, location feature is not available");
        return;
    }
    String provider = mLocationManager.getBestProvider(criteria, enabledOnly);
    if (provider != null && (isProviderCompatible(provider))) {
        LogUtil.d(TAG, "Trying to request single update with criteria best provider...");
        try {
            mLocationManager.requestSingleUpdate(provider, mLocationListener, null);
        } catch (Exception e) {
            LogUtil.e(TAG, "Exception while trying to request single update with criteria best provider");
            LogUtil.e(TAG, e.getMessage());
            LogUtil.e(TAG, e.toString());
            e.printStackTrace();
        }
    } else {
        LogUtil.w(TAG, "Cannot request single update with criteria best provider, selected provider is not compatible");
    }
}

19 Source : FindStoreActivity.java
with Apache License 2.0
from mustafaynk

@Override
public boolean onMyLocationButtonClick() {
    // if(mMap.isMyLocationEnabled()) Toast.makeText(this, "Var", Toast.LENGTH_SHORT).show();
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the locatioin provider -> use
    // default
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, true);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        // ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        // public void onRequestPermissionsResult(int requestCode, String[] permissions,
        // int[] grantResults)
        // to handle the case where the user grants the permission. See the doreplacedentation
        // for ActivityCompat#requestPermissions for more details.
        return false;
    }
    Location location = locationManager.getLastKnownLocation(provider);
    // Initialize the location fields
    if (location != null) {
        Toast.makeText(this, "Provider " + provider + " seçildi", Toast.LENGTH_SHORT).show();
        System.out.println("Provider " + provider + " has been selected.");
        onLocationChanged(location);
    } else {
        Toast.makeText(this, "Location not available", Toast.LENGTH_SHORT).show();
    }
    return false;
}

19 Source : AndroidLocationEngineImplTest.java
with MIT License
from mapbox

@Test
public void requestLocationUpdatesWithNoPower() {
    LocationEngineRequest request = new LocationEngineRequest.Builder(10).setPriority(LocationEngineRequest.PRIORITY_NO_POWER).build();
    LocationEngineCallback<LocationEngineResult> callback = mock(LocationEngineCallback.clreplaced);
    Looper looper = mock(Looper.clreplaced);
    Criteria criteria = mock(Criteria.clreplaced);
    engine.requestLocationUpdates(request, callback, looper);
    verify(locationManagerMock, never()).getBestProvider(criteria, true);
}

19 Source : AndroidLocationEngineImpl.java
with MIT License
from mapbox

@VisibleForTesting
static Criteria getCriteria(int priority) {
    Criteria criteria = new Criteria();
    criteria.setAccuracy(priorityToAccuracy(priority));
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(priorityToPowerRequirement(priority));
    return criteria;
}

19 Source : je.java
with Apache License 2.0
from JackChan1999

public clreplaced je extends jf {

    public static final Integer a = Integer.valueOf(202);

    public static final Integer b = Integer.valueOf(5);

    public static final Integer c = Integer.valueOf(5);

    public static final Integer d = Integer.valueOf(0);

    public static final String e = null;

    public static final Boolean f = Boolean.valueOf(true);

    public static final Boolean g = Boolean.valueOf(true);

    public static final String h = null;

    public static final Boolean i = Boolean.valueOf(true);

    public static final Criteria j = null;

    public static final Location k = null;

    public static final Long l = Long.valueOf(10000);

    public static final Boolean m = Boolean.valueOf(true);

    public static final Long n = null;

    public static final Byte o = Byte.valueOf((byte) -1);

    public static final Boolean p = Boolean.valueOf(false);

    public static final String q = null;

    private static je r;

    public static synchronized je a() {
        je jeVar;
        synchronized (je.clreplaced) {
            if (r == null) {
                r = new je();
            }
            jeVar = r;
        }
        return jeVar;
    }

    public static synchronized void b() {
        synchronized (je.clreplaced) {
            if (r != null) {
                r.d();
            }
            r = null;
        }
    }

    private je() {
        c();
    }

    public void c() {
        a("AgentVersion", (Object) a);
        a("ReleaseMajorVersion", (Object) b);
        a("ReleaseMinorVersion", (Object) c);
        a("ReleasePatchVersion", (Object) d);
        a("ReleaseBetaVersion", (Object) "");
        a("VersionName", (Object) e);
        a("CaptureUncaughtExceptions", (Object) f);
        a("UseHttps", (Object) g);
        a("ReportUrl", (Object) h);
        a("ReportLocation", (Object) i);
        a("ExplicitLocation", (Object) k);
        a("ContinueSessionMillis", (Object) l);
        a("LogEvents", (Object) m);
        a("Age", (Object) n);
        a("Gender", (Object) o);
        a("UserId", (Object) "");
        a("ProtonEnabled", (Object) p);
        a("ProtonConfigUrl", (Object) q);
    }
}

19 Source : RxLocationTool.java
with Apache License 2.0
from hexingbo

/**
 * 设置定位参数
 *
 * @return {@link Criteria}
 */
private static Criteria getCriteria() {
    Criteria criteria = new Criteria();
    // 设置定位精确度 Criteria.ACCURACY_COARSE比较粗略,Criteria.ACCURACY_FINE则比较精细
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    // 设置是否要求速度
    criteria.setSpeedRequired(true);
    // 设置是否允许运营商收费
    criteria.setCostAllowed(true);
    // 设置是否需要方位信息
    criteria.setBearingRequired(true);
    // 设置是否需要海拔信息
    criteria.setAlreplacedudeRequired(true);
    // 设置对电源的需求
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    return criteria;
}

19 Source : Geolocation.java
with MIT License
from DoFabien

/**
 * Given a call and its options, find the best provider that satisfies those
 * required options.
 * @param call
 * @return
 */
private String getBestProviderForCall(PluginCall call) {
    Criteria locationCriteria = getCriteriaForCall(call);
    return locationManager.getBestProvider(locationCriteria, true);
}

19 Source : Geolocation.java
with MIT License
from DoFabien

/**
 * Given the call's options, return a Criteria object
 * that will indicate which location provider we need to use.
 * @param call
 * @return
 */
private Criteria getCriteriaForCall(PluginCall call) {
    boolean enableHighAccuracy = call.getBoolean("enableHighAccuracy", false);
    boolean alreplacedudeRequired = call.getBoolean("alreplacedudeRequired", false);
    boolean speedRequired = call.getBoolean("speedRequired", false);
    boolean bearingRequired = call.getBoolean("bearingRequired", false);
    int timeout = call.getInt("timeout", 30000);
    int maximumAge = call.getInt("maximumAge", 0);
    Criteria c = new Criteria();
    c.setAccuracy(enableHighAccuracy ? Criteria.ACCURACY_FINE : Criteria.ACCURACY_COARSE);
    c.setAlreplacedudeRequired(alreplacedudeRequired);
    c.setBearingRequired(bearingRequired);
    c.setSpeedRequired(speedRequired);
    return c;
}

19 Source : LocationFragment.java
with Apache License 2.0
from dbbahnhoflive

public clreplaced LocationFragment extends Fragment {

    public static final String FRAGMENT_TAG = "locator";

    private LocationManager locationManager;

    private final Criteria criteria;

    private final ArrayList<LocationListener> locationListeners = new ArrayList<>();

    private Location location;

    private LocationCollector locationCollector;

    public LocationFragment() {
        criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
    }

    @Override
    public void onDestroy() {
        locationManager = null;
        super.onDestroy();
    }

    @Override
    public void onStart() {
        super.onStart();
        acquireLocation(false);
    }

    public void addLocationListener(LocationListener locationListener) {
        if (location != null) {
            locationListener.onLocationChanged(location);
        }
        locationListeners.add(locationListener);
    }

    public void removeLocationListener(LocationListener locationListener) {
        locationListeners.remove(locationListener);
    }

    @SuppressWarnings("MissingPermission")
    public boolean acquireLocation(boolean forceUpdate) {
        if (locationManager != null) {
            if (Permission.LOCATION.isGranted()) {
                final List<String> providers = locationManager.getProviders(true);
                if (providers != null) {
                    if (forceUpdate || !tryLastKnownLocations(providers)) {
                        if (locationCollector != null) {
                            locationCollector.cancel();
                        }
                        locationCollector = new LocationCollector(providers);
                    } else {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private boolean tryLastKnownLocations(List<String> providers) {
        final ArrayList<Location> lastKnownLocations = new ArrayList<>(providers.size());
        for (String provider : providers) {
            @SuppressLint("MissingPermission")
            final Location lastKnownLocation = locationManager.getLastKnownLocation(provider);
            if (lastKnownLocation != null) {
                lastKnownLocations.add(lastKnownLocation);
            }
        }
        final Location bestSuitableLocation = findBestSuitableLocation(lastKnownLocations);
        if (bestSuitableLocation != null) {
            updateLocation(bestSuitableLocation);
            return true;
        }
        return false;
    }

    private Location findBestSuitableLocation(@NonNull List<Location> locations) {
        if (locations.isEmpty()) {
            return null;
        }
        final long now = System.currentTimeMillis();
        Collections.sort(locations, new Comparator<Location>() {

            @Override
            public int compare(Location o1, Location o2) {
                return (int) ((o2.getTime() - o1.getTime()) / 120 + o2.getAccuracy() - o1.getAccuracy());
            // 1 minute of currency is worth 500 meters of accuracy
            }
        });
        for (Location location : locations) {
            if (isAcceptable(location, now)) {
                return location;
            }
        }
        return locations.get(0);
    }

    private boolean isAcceptable(Location location, long now) {
        return location.getAccuracy() < 500 && now - location.getTime() < 60 * 1000;
    }

    private boolean isGreat(Location location, long now) {
        return location.getAccuracy() < 50 && now - location.getTime() < 30 * 1000;
    }

    private void updateLocation(Location location) {
        if (location != null) {
            this.location = location;
            notifiyLocationListeners(location);
        }
    }

    private void notifiyLocationListeners(Location location) {
        for (LocationListener listener : locationListeners) {
            listener.onLocationChanged(location);
        }
    }

    @Override
    public void onStop() {
        if (locationCollector != null) {
            locationCollector.cancel();
        }
        super.onStop();
    }

    public static LocationFragment get(FragmentManager fragmentManager) {
        final Fragment fragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG);
        if (fragment instanceof LocationFragment) {
            return (LocationFragment) fragment;
        }
        final LocationFragment locationFragment = new LocationFragment();
        fragmentManager.beginTransaction().add(locationFragment, FRAGMENT_TAG).commitAllowingStateLoss();
        return locationFragment;
    }

    private clreplaced LocationCollector extends BaseLocationListener {

        private final List<String> providers;

        private final List<Location> locations;

        @SuppressLint("MissingPermission")
        public LocationCollector(List<String> providers) {
            this.providers = providers;
            locations = new ArrayList<>(providers.size());
            for (String provider : providers) {
                locationManager.requestSingleUpdate(provider, this, Looper.getMainLooper());
            }
        }

        @Override
        public void onLocationChanged(Location location) {
            locations.add(location);
            if (isGreat(location, System.currentTimeMillis())) {
                // exit early because we have a great candidate
                providers.clear();
            }
            onProviderDone(location.getProvider());
        }

        @Override
        public void onProviderDisabled(String provider) {
            onProviderDone(provider);
        }

        private void onProviderDone(String provider) {
            if (!providers.remove(provider)) {
                providers.remove("preplacedive");
            }
            if (providers.isEmpty()) {
                onDone();
            }
        }

        private void onDone() {
            cancel();
            final Location bestSuitableLocation = findBestSuitableLocation(locations);
            if (bestSuitableLocation != null) {
                updateLocation(bestSuitableLocation);
            }
        }

        public void cancel() {
            locationCollector = null;
            locationManager.removeUpdates(this);
        }
    }
}

19 Source : MyLocationOverlay.java
with GNU General Public License v3.0
from cgeo

private synchronized boolean enableBestAvailableProvider() {
    disableMyLocation();
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    String bestAvailableProvider = this.locationManager.getBestProvider(criteria, true);
    if (bestAvailableProvider == null) {
        return false;
    }
    this.lastLocation = this.locationManager.getLastKnownLocation(bestAvailableProvider);
    this.locationManager.requestLocationUpdates(bestAvailableProvider, UPDATE_INTERVAL, UPDATE_DISTANCE, this);
    this.myLocationEnabled = true;
    return true;
}

19 Source : Utils.java
with GNU General Public License v3.0
from bidmachine

/*
    Location utils
     */
@Nullable
@SuppressLint("MissingPermission")
public static Location getLocation(Context context) {
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    if (locationManager != null) {
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, false);
        if (bestProvider != null) {
            try {
                Location location = locationManager.getLastKnownLocation(bestProvider);
                if (location == null) {
                    List<String> allProviders = locationManager.getAllProviders();
                    if (allProviders != null && allProviders.size() > 1) {
                        for (String provider : allProviders) {
                            if (provider != null && !provider.equals(bestProvider)) {
                                location = locationManager.getLastKnownLocation(provider);
                                if (location != null) {
                                    break;
                                }
                            }
                        }
                    }
                }
                return location;
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

19 Source : TrackerS.java
with Apache License 2.0
from aress31

private void setLocationListener() {
    if (ContextCompat.checkSelfPermission(this, "android.permission.ACCESS_COARSE_LOCATION") + ContextCompat.checkSelfPermission(this, "android.permission.ACCESS_FINE_LOCATION") != 0) {
        Log.wtf(TAG, TrackerS.clreplaced.getName() + "->setLocationListener:insufficient permission");
    } else {
        Criteria criteria = new Criteria();
        if (this.locationManager.getBestProvider(criteria, true) != null) {
            long MIN_DISTANCE_CHANGE_FOR_UPDATES = 20;
            long MIN_TIME_BETWEEN_UPDATES = 1000 * 60 * 30;
            this.locationManager.requestLocationUpdates(this.locationManager.getBestProvider(criteria, true), MIN_TIME_BETWEEN_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this.locationListener);
        } else {
            if (DEV_MODE) {
                Log.wtf("::trace", TrackerS.clreplaced.getName() + "->setLocationListener:location providers all disabled");
            }
        }
    }
}

19 Source : ThreatMapFragment.java
with MIT License
from aau-network-security

private void locationChecker() {
    final AppCompatActivity activity = (AppCompatActivity) getActivity();
    mLocationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    mLocationProvider = mLocationManager.getBestProvider(criteria, false);
    requestPermissionUpdates();
    populateMap();
    registerBroadcastReceiver();
}

18 Source : DefaultLocation.java
with Apache License 2.0
from weexteam

private WXLocationListener findLocation(String watchId, String sucCallback, String errorCallback, boolean enableHighAccuracy, boolean enableAddress) {
    // WXLogUtils.d(TAG, "into--[findLocation] mWatchId:" + watchId + "\nsuccessCallback:" + sucCallback + "\nerrorCallback:" + errorCallback + "\nenableHighAccuracy:" + enableHighAccuracy + "\nmEnableAddress:" + enableAddress);
    if (mLocationManager == null) {
        mLocationManager = (LocationManager) mWXSDKInstance.getContext().getSystemService(Context.LOCATION_SERVICE);
    }
    Criteria criteria = new Criteria();
    if (enableHighAccuracy) {
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    }
    // String provider = locationManager.getBestProvider(criteria, false);
    if (ActivityCompat.checkSelfPermission(mWXSDKInstance.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mWXSDKInstance.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        WXLocationListener WXLocationListener = new WXLocationListener(mLocationManager, mWXSDKInstance, watchId, sucCallback, errorCallback, enableAddress);
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, WXLocationListener);
        mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, WXLocationListener);
        return WXLocationListener;
    } else {
        Map<String, Object> options = new HashMap<>();
        options.put(ERROR_CODE, ErrorCode.NO_PERMISSION_ERROR);
        options.put(ERROR_MSG, ErrorMsg.NO_PERMISSION_ERROR);
        WXSDKManager.getInstance().callback(mWXSDKInstance.getInstanceId(), errorCallback, options);
    }
    return null;
}

18 Source : PLocation.java
with GNU General Public License v3.0
from victordiaz

@SuppressLint("MissingPermission")
@PhonkMethod(description = "Start the location. Returns lat, lon, alt, speed, bearing", example = "")
@PhonkMethodParam(params = { "function(lat, lon, alt, speed, bearing)" })
public void start() {
    if (!isAvailable()) {
        try {
            MLog.d(TAG, "try");
            throw new FeatureNotAvailableException();
        } catch (FeatureNotAvailableException e) {
            e.printStackTrace();
            MLog.d(TAG, "catch");
            getAppRunner().pConsole.error("Your device doesn't have a GPS :(");
            // getAppRunner().interp.observingDebugger.setDisconnected(true);
            return;
        }
    }
    if (running) {
        return;
    }
    MLog.d(TAG, "starting GPS");
    // criteria.setSpeedRequired(true);
    locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) == false) {
        MLog.d(TAG, "GPS not enabled");
        showSettingsAlert();
    } else {
        MLog.d(TAG, "GPS enabled");
    }
    running = true;
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    // criteria.setBearingAccuracy(Criteria.ACCURACY_FINE);
    criteria.setCostAllowed(true);
    criteria.setAlreplacedudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setPowerRequirement(Criteria.POWER_HIGH);
    criteria.setSpeedRequired(false);
    provider = locationManager.getBestProvider(criteria, false);
    locationListener = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            MLog.d(TAG, "the location status is: " + status);
            // TODO add listener to see when the GPS is on or not
            switch(status) {
                case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                    if (mLastLocation != null) {
                        isGPSFix = (SystemClock.elapsedRealtime() - mLastLocationMillis) < 3000;
                    }
                    if (isGPSFix) {
                    // A fix has been acquired.
                    // Do something.
                    } else {
                    // The fix has been lost.
                    // Do something.
                    }
                    // for (CustomSensorListener l : listeners) {
                    // ((GPSListener) l).onGPSStatus(isGPSFix);
                    // }
                    break;
                case GpsStatus.GPS_EVENT_FIRST_FIX:
                    // Do something.
                    isGPSFix = true;
                    break;
            }
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            getContext().startActivity(intent);
        }

        @Override
        public void onLocationChanged(Location location) {
            MLog.d(TAG, "updated ");
            ReturnObject r = new ReturnObject();
            r.put("lareplacedude", location.getLareplacedude());
            r.put("longitude", location.getLongitude());
            r.put("alreplacedude", location.getAlreplacedude());
            r.put("speed", location.getSpeed());
            r.put("speedUnit", "m/s");
            r.put("accuracy", location.getAccuracy());
            r.put("bearing", location.getBearing());
            r.put("provider", location.getProvider());
            r.put("time", location.getTime());
            mLocationCallback.event(r);
            if (location == null) {
                return;
            }
            mLastLocationMillis = SystemClock.elapsedRealtime();
            mLastLocation = location;
        }
    };
    locationManager.requestLocationUpdates(provider, 100, 0.1f, locationListener);
    locationManager.addGpsStatusListener(new GpsStatus.Listener() {

        @Override
        public void onGpsStatusChanged(int i) {
            int satellitesCount = 0;
            int satellitesInFix = 0;
            int timetofix = locationManager.getGpsStatus(null).getTimeToFirstFix();
            MLog.d(TAG, "Time to first fix = " + timetofix);
            ArrayList sats = new ArrayList();
            for (GpsSatellite sat : locationManager.getGpsStatus(null).getSatellites()) {
                if (sat.usedInFix()) {
                    satellitesInFix++;
                }
                satellitesCount++;
                HashMap<String, Object> sareplacedem = new HashMap<>();
                sareplacedem.put("azimuth", sat.getAzimuth());
                sareplacedem.put("elevation", sat.getAzimuth());
                sareplacedem.put("prn", sat.getPrn());
                sareplacedem.put("snr", sat.getSnr());
                sats.add(sareplacedem);
                ReturnObject ret = new ReturnObject();
                ret.put("satellites", sats);
                ret.put("satellitesInView", satellitesCount);
                ret.put("satellitesInFix", satellitesInFix);
                if (mSatellitesCallback != null)
                    mSatellitesCallback.event(ret);
            }
        // MLog.d(TAG, satellitesCount + " Used In Last Fix ("+satellitesInFix+")");
        }
    });
}

18 Source : LocationService.java
with Apache License 2.0
from schaa0

private String getBestProvider() {
    Criteria criteria = new Criteria();
    criteria.setCostAllowed(false);
    criteria.setAccuracy(Criteria.ACCURACY_LOW);
    return this.locationManager.getBestProvider(criteria, false);
}

18 Source : CriteriaSubject.java
with Apache License 2.0
from pkware

/**
 * Propositions for {@link Criteria} subjects.
 */
public clreplaced CriteriaSubject extends Subject {

    @Nullable
    private final Criteria actual;

    public CriteriaSubject(@Nonnull FailureMetadata failureMetadata, @Nullable Criteria actual) {
        super(failureMetadata, actual);
        this.actual = actual;
    }

    @Nonnull
    public static String accuracyRequirementToString(@CriteriaAccuracyRequirement int accuracy) {
        return buildNamedValueString(accuracy).value(ACCURACY_COARSE, "coarse").value(ACCURACY_FINE, "fine").get();
    }

    @Nonnull
    public static String accuracyToString(@CriteriaAccuracy int accuracy) {
        return buildNamedValueString(accuracy).value(ACCURACY_HIGH, "high").value(ACCURACY_MEDIUM, "medium").value(ACCURACY_LOW, "low").get();
    }

    @Nonnull
    public static String powerRequirementToString(@CriteriaPowerRequirement int requirement) {
        return buildNamedValueString(requirement).value(NO_REQUIREMENT, "none").value(POWER_LOW, "low").value(POWER_MEDIUM, "medium").value(POWER_HIGH, "high").get();
    }

    public void hasAccuracy(int accuracy) {
        int actualAccuracy = actual.getAccuracy();
        // noinspection ResourceType
        check("getAccuracy()").withMessage("Expected accuracy <%s> but was <%s>.", accuracyRequirementToString(accuracy), accuracyRequirementToString(actualAccuracy)).that(actualAccuracy).isEqualTo(accuracy);
    }

    public void hasBearingAccuracy(int accuracy) {
        int actualAccuracy = actual.getBearingAccuracy();
        // noinspection ResourceType
        check("getBearingAccuracy()").withMessage("Expected bearing accuracy <%s> but was <%s>.", accuracyToString(accuracy), accuracyToString(actualAccuracy)).that(actualAccuracy).isEqualTo(accuracy);
    }

    public void hasHorizontalAccuracy(int accuracy) {
        int actualAccuracy = actual.getHorizontalAccuracy();
        // noinspection ResourceType
        check("getHorizontalAccuracy()").withMessage("Expected horizontal accuracy <%s> but was <%s>.", accuracyToString(accuracy), accuracyToString(actualAccuracy)).that(actualAccuracy).isEqualTo(accuracy);
    }

    public void hasPowerRequirement(int requirement) {
        int actualRequirement = actual.getPowerRequirement();
        // noinspection ResourceType
        check("getPowerRequirement()").withMessage("Expected power requirement <%s> but was <%s>.", powerRequirementToString(requirement), powerRequirementToString(actualRequirement)).that(actualRequirement).isEqualTo(requirement);
    }

    public void hreplacedpeedAccuracy(int accuracy) {
        int actualAccuracy = actual.getSpeedAccuracy();
        // noinspection ResourceType
        check("getSpeedAccuracy()").withMessage("Expected speed accuracy <%s> but was <%s>.", accuracyToString(accuracy), accuracyToString(actualAccuracy)).that(actualAccuracy).isEqualTo(accuracy);
    }

    public void hasVerticalAccuracy(int accuracy) {
        int actualAccuracy = actual.getVerticalAccuracy();
        // noinspection ResourceType
        check("getVerticalAccuracy()").withMessage("Expected vertical accuracy <%s> but was <%s>.", accuracyToString(accuracy), accuracyToString(actualAccuracy)).that(actualAccuracy).isEqualTo(accuracy);
    }

    public void isAlreplacedudeRequired() {
        check("isAlreplacedudeRequired()").that(actual.isAlreplacedudeRequired()).isTrue();
    }

    public void isAlreplacedudeNotRequired() {
        check("isAlreplacedudeRequired()").that(actual.isAlreplacedudeRequired()).isFalse();
    }

    public void isBearingRequired() {
        check("isBearingRequired()").that(actual.isBearingRequired()).isTrue();
    }

    public void isBearingNotRequired() {
        check("isBearingRequired()").that(actual.isBearingRequired()).isFalse();
    }

    public void isCostAllowed() {
        check("isCostAllowed()").that(actual.isCostAllowed()).isTrue();
    }

    public void isCostNotAllowed() {
        check("isCostAllowed()").that(actual.isCostAllowed()).isFalse();
    }

    public void isSpeedRequired() {
        check("isSpeedRequired()").that(actual.isSpeedRequired()).isTrue();
    }

    public void isSpeedNotRequired() {
        check("isSpeedRequired()").that(actual.isSpeedRequired()).isFalse();
    }
}

18 Source : LocationService.java
with GNU General Public License v3.0
from n37sn4k3

@SuppressLint("MissingPermission")
@RequiresPermission(allOf = { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION })
public void requestLocationUpdates(@Nullable Criteria criteria, boolean enabledOnly, long minTime, float minDistance) {
    if (mLocationManager == null || mLocationListener == null || criteria == null) {
        LogUtil.w(TAG, "Cannot request location updates with criteria best provider, time and distance");
        return;
    }
    if (!getPackageManager().hreplacedystemFeature(PackageManager.FEATURE_LOCATION)) {
        LogUtil.w(TAG, "Cannot request location updates with criteria best provider, time and distance, location feature is not available");
        return;
    }
    String provider = mLocationManager.getBestProvider(criteria, enabledOnly);
    if (provider != null && (isProviderCompatible(provider))) {
        LogUtil.d(TAG, "Trying to request location updates with criteria best provider, time and distance...");
        try {
            mLocationManager.requestLocationUpdates(provider, minTime, minDistance, mLocationListener);
        } catch (Exception e) {
            LogUtil.e(TAG, "Exception while trying to request location updates with criteria best provider, time and distance");
            LogUtil.e(TAG, e.getMessage());
            LogUtil.e(TAG, e.toString());
            e.printStackTrace();
        }
    } else {
        LogUtil.w(TAG, "Cannot request location updates with criteria best provider, time and distance, selected provider is not compatible");
    }
}

18 Source : LocationService.java
with MIT License
from mizutori

public void startUpdatingLocation() {
    if (this.isLocationManagerUpdatingLocation == false) {
        isLocationManagerUpdatingLocation = true;
        runStartTimeInMillis = (long) (SystemClock.elapsedRealtimeNanos() / 1000000);
        locationList.clear();
        oldLocationList.clear();
        noAccuracyLocationList.clear();
        inaccurateLocationList.clear();
        kalmanNGLocationList.clear();
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        // Exception thrown when GPS or Network provider were not available on the user's device.
        try {
            Criteria criteria = new Criteria();
            // setAccuracyは内部では、https://stackoverflow.com/a/17874592/1709287の用にHorizontalAccuracyの設定に変換されている。
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            criteria.setPowerRequirement(Criteria.POWER_HIGH);
            criteria.setAlreplacedudeRequired(false);
            criteria.setSpeedRequired(true);
            criteria.setCostAllowed(true);
            criteria.setBearingRequired(false);
            // API level 9 and up
            criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
            criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);
            // criteria.setBearingAccuracy(Criteria.ACCURACY_HIGH);
            // criteria.setSpeedAccuracy(Criteria.ACCURACY_HIGH);
            Integer gpsFreqInMillis = 5000;
            // in meters
            Integer gpsFreqInDistance = 5;
            locationManager.addGpsStatusListener(this);
            locationManager.requestLocationUpdates(gpsFreqInMillis, gpsFreqInDistance, criteria, this, null);
            /* Battery Consumption Measurement */
            gpsCount = 0;
            batteryLevelArray.clear();
            batteryLevelScaledArray.clear();
        } catch (IllegalArgumentException e) {
            Log.e(LOG_TAG, e.getLocalizedMessage());
        } catch (SecurityException e) {
            Log.e(LOG_TAG, e.getLocalizedMessage());
        } catch (RuntimeException e) {
            Log.e(LOG_TAG, e.getLocalizedMessage());
        }
    }
}

18 Source : DistanceFilterLocationProvider.java
with Apache License 2.0
from mauron85

public clreplaced DistanceFilterLocationProvider extends AbstractLocationProvider implements LocationListener {

    private static final String TAG = DistanceFilterLocationProvider.clreplaced.getSimpleName();

    private static final String P_NAME = "com.tenforwardconsulting.cordova.bgloc";

    private static final String STATIONARY_REGION_ACTION = P_NAME + ".STATIONARY_REGION_ACTION";

    private static final String STATIONARY_ALARM_ACTION = P_NAME + ".STATIONARY_ALARM_ACTION";

    private static final String SINGLE_LOCATION_UPDATE_ACTION = P_NAME + ".SINGLE_LOCATION_UPDATE_ACTION";

    private static final String STATIONARY_LOCATION_MONITOR_ACTION = P_NAME + ".STATIONARY_LOCATION_MONITOR_ACTION";

    // 5 minutes.
    private static final long STATIONARY_TIMEOUT = 5 * 1000 * 60;

    // 3 minutes.
    private static final long STATIONARY_LOCATION_POLLING_INTERVAL_LAZY = 3 * 1000 * 60;

    // 1 minute.
    private static final long STATIONARY_LOCATION_POLLING_INTERVAL_AGGRESSIVE = 1 * 1000 * 60;

    private static final int MAX_STATIONARY_ACQUISITION_ATTEMPTS = 5;

    private static final int MAX_SPEED_ACQUISITION_ATTEMPTS = 3;

    private Boolean isMoving = false;

    private Boolean isAcquiringStationaryLocation = false;

    private Boolean isAcquiringSpeed = false;

    private Integer locationAcquisitionAttempts = 0;

    private Location lastLocation;

    private Location stationaryLocation;

    private float stationaryRadius;

    private PendingIntent stationaryAlarmPI;

    private PendingIntent stationaryLocationPollingPI;

    private long stationaryLocationPollingInterval;

    private PendingIntent stationaryRegionPI;

    private PendingIntent singleUpdatePI;

    private Integer scaledDistanceFilter;

    private Criteria criteria;

    private LocationManager locationManager;

    private AlarmManager alarmManager;

    private boolean isStarted = false;

    public DistanceFilterLocationProvider(Context context) {
        super(context);
        PROVIDER_ID = Config.DISTANCE_FILTER_PROVIDER;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        // Stop-detection PI
        stationaryAlarmPI = PendingIntent.getBroadcast(mContext, 0, new Intent(STATIONARY_ALARM_ACTION), 0);
        registerReceiver(stationaryAlarmReceiver, new IntentFilter(STATIONARY_ALARM_ACTION));
        // Stationary region PI
        stationaryRegionPI = PendingIntent.getBroadcast(mContext, 0, new Intent(STATIONARY_REGION_ACTION), PendingIntent.FLAG_CANCEL_CURRENT);
        registerReceiver(stationaryRegionReceiver, new IntentFilter(STATIONARY_REGION_ACTION));
        // Stationary location monitor PI
        stationaryLocationPollingPI = PendingIntent.getBroadcast(mContext, 0, new Intent(STATIONARY_LOCATION_MONITOR_ACTION), 0);
        registerReceiver(stationaryLocationMonitorReceiver, new IntentFilter(STATIONARY_LOCATION_MONITOR_ACTION));
        // One-shot PI (TODO currently unused)
        singleUpdatePI = PendingIntent.getBroadcast(mContext, 0, new Intent(SINGLE_LOCATION_UPDATE_ACTION), PendingIntent.FLAG_CANCEL_CURRENT);
        registerReceiver(singleUpdateReceiver, new IntentFilter(SINGLE_LOCATION_UPDATE_ACTION));
        // Location criteria
        criteria = new Criteria();
        criteria.setAlreplacedudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setSpeedRequired(true);
        criteria.setCostAllowed(true);
    }

    @Override
    public void onStart() {
        if (isStarted) {
            return;
        }
        logger.info("Start recording");
        scaledDistanceFilter = mConfig.getDistanceFilter();
        isStarted = true;
        setPace(false);
    }

    @Override
    public void onStop() {
        if (!isStarted) {
            return;
        }
        try {
            locationManager.removeUpdates(this);
            locationManager.removeProximityAlert(stationaryRegionPI);
        } catch (SecurityException e) {
        // noop
        } finally {
            isStarted = false;
        }
    }

    @Override
    public void onCommand(int commandId, int arg1) {
        switch(commandId) {
            case CMD_SWITCH_MODE:
                setPace(arg1 == BACKGROUND_MODE ? false : true);
                return;
        }
    }

    @Override
    public void onConfigure(Config config) {
        super.onConfigure(config);
        if (isStarted) {
            onStop();
            onStart();
        }
    }

    @Override
    public boolean isStarted() {
        return isStarted;
    }

    /**
     * @param value set true to engage "aggressive", battery-consuming tracking, false for stationary-region tracking
     */
    private void setPace(Boolean value) {
        if (!isStarted) {
            return;
        }
        logger.info("Setting pace: {}", value);
        Boolean wasMoving = isMoving;
        isMoving = value;
        isAcquiringStationaryLocation = false;
        isAcquiringSpeed = false;
        stationaryLocation = null;
        try {
            locationManager.removeUpdates(this);
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            criteria.setHorizontalAccuracy(translateDesiredAccuracy(mConfig.getDesiredAccuracy()));
            criteria.setPowerRequirement(Criteria.POWER_HIGH);
            if (isMoving) {
                // setPace can be called while moving, after distanceFilter has been recalculated.  We don't want to re-acquire velocity in this case.
                if (!wasMoving) {
                    isAcquiringSpeed = true;
                }
            } else {
                isAcquiringStationaryLocation = true;
            }
            // Temporarily turn on super-aggressive geolocation on all providers when acquiring velocity or stationary location.
            if (isAcquiringSpeed || isAcquiringStationaryLocation) {
                locationAcquisitionAttempts = 0;
                // Turn on each provider aggressively for a short period of time
                List<String> matchingProviders = locationManager.getAllProviders();
                for (String provider : matchingProviders) {
                    if (provider != LocationManager.PreplacedIVE_PROVIDER) {
                        locationManager.requestLocationUpdates(provider, 0, 0, this);
                    }
                }
            } else {
                locationManager.requestLocationUpdates(locationManager.getBestProvider(criteria, true), mConfig.getInterval(), scaledDistanceFilter, this);
            }
        } catch (SecurityException e) {
            logger.error("Security exception: {}", e.getMessage());
            this.handleSecurityException(e);
        }
    }

    /**
     * Translates a number representing desired accuracy of Geolocation system from set [0, 10, 100, 1000].
     * 0:  most aggressive, most accurate, worst battery drain
     * 1000:  least aggressive, least accurate, best for battery.
     */
    private Integer translateDesiredAccuracy(Integer accuracy) {
        if (accuracy >= 1000) {
            return Criteria.ACCURACY_LOW;
        }
        if (accuracy >= 100) {
            return Criteria.ACCURACY_MEDIUM;
        }
        if (accuracy >= 10) {
            return Criteria.ACCURACY_HIGH;
        }
        if (accuracy >= 0) {
            return Criteria.ACCURACY_HIGH;
        }
        return Criteria.ACCURACY_MEDIUM;
    }

    /**
     * Returns the most accurate and timely previously detected location.
     * Where the last result is beyond the specified maximum distance or
     * latency a one-off location update is returned via the {@link LocationListener}
     * specified in {@link setChangedLocationListener}.
     * @param minTime Minimum time required between location updates.
     * @return The most accurate and / or timely previously detected location.
     */
    public Location getLastBestLocation() {
        Location bestResult = null;
        String bestProvider = null;
        float bestAccuracy = Float.MAX_VALUE;
        long bestTime = Long.MIN_VALUE;
        long minTime = System.currentTimeMillis() - mConfig.getInterval();
        logger.info("Fetching last best location: radius={} minTime={}", mConfig.getStationaryRadius(), minTime);
        try {
            // 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 = locationManager.getAllProviders();
            for (String provider : matchingProviders) {
                Location location = locationManager.getLastKnownLocation(provider);
                if (location != null) {
                    logger.debug("Test provider={} lat={} lon={} acy={} v={}m/s time={}", provider, location.getLareplacedude(), location.getLongitude(), location.getAccuracy(), location.getSpeed(), location.getTime());
                    float accuracy = location.getAccuracy();
                    long time = location.getTime();
                    if ((time > minTime && accuracy < bestAccuracy)) {
                        bestProvider = provider;
                        bestResult = location;
                        bestAccuracy = accuracy;
                        bestTime = time;
                    }
                }
            }
            if (bestResult != null) {
                logger.debug("Best result found provider={} lat={} lon={} acy={} v={}m/s time={}", bestProvider, bestResult.getLareplacedude(), bestResult.getLongitude(), bestResult.getAccuracy(), bestResult.getSpeed(), bestResult.getTime());
            }
        } catch (SecurityException e) {
            logger.error("Security exception: {}", e.getMessage());
            this.handleSecurityException(e);
        }
        return bestResult;
    }

    public void onLocationChanged(Location location) {
        logger.debug("Location change: {} isMoving={}", location.toString(), isMoving);
        if (!isMoving && !isAcquiringStationaryLocation && stationaryLocation == null) {
            // Perhaps our GPS signal was interupted, re-acquire a stationaryLocation now.
            setPace(false);
        }
        showDebugToast("mv:" + isMoving + ",acy:" + location.getAccuracy() + ",v:" + location.getSpeed() + ",df:" + scaledDistanceFilter);
        if (isAcquiringStationaryLocation) {
            if (stationaryLocation == null || stationaryLocation.getAccuracy() > location.getAccuracy()) {
                stationaryLocation = location;
            }
            if (++locationAcquisitionAttempts == MAX_STATIONARY_ACQUISITION_ATTEMPTS) {
                isAcquiringStationaryLocation = false;
                startMonitoringStationaryRegion(stationaryLocation);
                handleStationary(stationaryLocation, stationaryRadius);
                return;
            } else {
                // Unacceptable stationary-location: bail-out and wait for another.
                playDebugTone(Tone.BEEP);
                return;
            }
        } else if (isAcquiringSpeed) {
            if (++locationAcquisitionAttempts == MAX_SPEED_ACQUISITION_ATTEMPTS) {
                // Got enough samples, replacedume we're confident in reported speed now.  Play "woohoo" sound.
                playDebugTone(Tone.DOODLY_DOO);
                isAcquiringSpeed = false;
                scaledDistanceFilter = calculateDistanceFilter(location.getSpeed());
                setPace(true);
            } else {
                playDebugTone(Tone.BEEP);
                return;
            }
        } else if (isMoving) {
            playDebugTone(Tone.BEEP);
            // Only reset stationaryAlarm when accurate speed is detected, prevents spurious locations from resetting when stopped.
            if ((location.getSpeed() >= 1) && (location.getAccuracy() <= mConfig.getStationaryRadius())) {
                resetStationaryAlarm();
            }
            // Calculate latest distanceFilter, if it changed by 5 m/s, we'll reconfigure our pace.
            Integer newDistanceFilter = calculateDistanceFilter(location.getSpeed());
            if (newDistanceFilter != scaledDistanceFilter.intValue()) {
                logger.info("Updating distanceFilter: new={} old={}", newDistanceFilter, scaledDistanceFilter);
                scaledDistanceFilter = newDistanceFilter;
                setPace(true);
            }
            if (lastLocation != null && location.distanceTo(lastLocation) < mConfig.getDistanceFilter()) {
                return;
            }
        } else if (stationaryLocation != null) {
            return;
        }
        // Go ahead and cache, push to server
        lastLocation = location;
        handleLocation(location);
    }

    public void resetStationaryAlarm() {
        alarmManager.cancel(stationaryAlarmPI);
        // Millisec * Second * Minute
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + STATIONARY_TIMEOUT, stationaryAlarmPI);
    }

    private Integer calculateDistanceFilter(Float speed) {
        Double newDistanceFilter = (double) mConfig.getDistanceFilter();
        if (speed < 100) {
            float roundedDistanceFilter = (round(speed / 5) * 5);
            newDistanceFilter = pow(roundedDistanceFilter, 2) + (double) mConfig.getDistanceFilter();
        }
        return (newDistanceFilter.intValue() < 1000) ? newDistanceFilter.intValue() : 1000;
    }

    private void startMonitoringStationaryRegion(Location location) {
        try {
            locationManager.removeUpdates(this);
            float stationaryRadius = mConfig.getStationaryRadius();
            float proximityRadius = (location.getAccuracy() < stationaryRadius) ? stationaryRadius : location.getAccuracy();
            stationaryLocation = location;
            logger.info("startMonitoringStationaryRegion: lat={} lon={} acy={}", location.getLareplacedude(), location.getLongitude(), proximityRadius);
            // Here be the execution of the stationary region monitor
            locationManager.addProximityAlert(location.getLareplacedude(), location.getLongitude(), proximityRadius, (long) -1, stationaryRegionPI);
            this.stationaryRadius = proximityRadius;
            startPollingStationaryLocation(STATIONARY_LOCATION_POLLING_INTERVAL_LAZY);
        } catch (SecurityException e) {
            logger.error("Security exception: {}", e.getMessage());
            this.handleSecurityException(e);
        }
    }

    /**
     * User has exit his stationary region!  Initiate aggressive geolocation!
     */
    public void onExitStationaryRegion(Location location) {
        // Filter-out spurious region-exits:  must have at least a little speed to move out of stationary-region
        playDebugTone(Tone.BEEP_BEEP_BEEP);
        logger.info("Exited stationary: lat={} long={} acy={}}'", location.getLareplacedude(), location.getLongitude(), location.getAccuracy());
        try {
            // Cancel the periodic stationary location monitor alarm.
            alarmManager.cancel(stationaryLocationPollingPI);
            // Kill the current region-monitor we just walked out of.
            locationManager.removeProximityAlert(stationaryRegionPI);
            // Engage aggressive tracking.
            this.setPace(true);
        } catch (SecurityException e) {
            logger.error("Security exception: {}", e.getMessage());
            this.handleSecurityException(e);
        }
    }

    public void startPollingStationaryLocation(long interval) {
        // proximity-alerts don't seem to work while suspended in latest Android 4.42 (works in 4.03).  Have to use AlarmManager to sample
        // location at regular intervals with a one-shot.
        stationaryLocationPollingInterval = interval;
        alarmManager.cancel(stationaryLocationPollingPI);
        long start = System.currentTimeMillis() + (60 * 1000);
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, start, interval, stationaryLocationPollingPI);
    }

    public void onPollStationaryLocation(Location location) {
        float stationaryRadius = mConfig.getStationaryRadius();
        if (isMoving) {
            return;
        }
        playDebugTone(Tone.BEEP);
        float distance = 0.0f;
        if (stationaryLocation != null) {
            distance = abs(location.distanceTo(stationaryLocation) - stationaryLocation.getAccuracy() - location.getAccuracy());
        }
        showDebugToast("Stationary exit in " + (stationaryRadius - distance) + "m");
        // TODO http://www.cse.buffalo.edu/~demirbas/publications/proximity.pdf
        // determine if we're almost out of stationary-distance and increase monitoring-rate.
        logger.info("Distance from stationary location: {}", distance);
        if (distance > stationaryRadius) {
            onExitStationaryRegion(location);
        } else if (distance > 0) {
            startPollingStationaryLocation(STATIONARY_LOCATION_POLLING_INTERVAL_AGGRESSIVE);
        } else if (stationaryLocationPollingInterval != STATIONARY_LOCATION_POLLING_INTERVAL_LAZY) {
            startPollingStationaryLocation(STATIONARY_LOCATION_POLLING_INTERVAL_LAZY);
        }
    }

    /**
     * Broadcast receiver for receiving a single-update from LocationManager.
     */
    private BroadcastReceiver singleUpdateReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String key = LocationManager.KEY_LOCATION_CHANGED;
            Location location = (Location) intent.getExtras().get(key);
            if (location != null) {
                logger.debug("Single location update: " + location.toString());
                onPollStationaryLocation(location);
            }
        }
    };

    /**
     * Broadcast receiver which detects a user has stopped for a long enough time to be determined as STOPPED
     */
    private BroadcastReceiver stationaryAlarmReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            logger.info("stationaryAlarm fired");
            setPace(false);
        }
    };

    /**
     * Broadcast receiver to handle stationaryMonitor alarm, fired at low frequency while monitoring stationary-region.
     * This is required because latest Android proximity-alerts don't seem to operate while suspended.  Regularly polling
     * the location seems to trigger the proximity-alerts while suspended.
     */
    private BroadcastReceiver stationaryLocationMonitorReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            logger.info("Stationary location monitor fired");
            playDebugTone(Tone.DIALTONE);
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
            criteria.setPowerRequirement(Criteria.POWER_HIGH);
            try {
                locationManager.requestSingleUpdate(criteria, singleUpdatePI);
            } catch (SecurityException e) {
                logger.error("Security exception: {}", e.getMessage());
            }
        }
    };

    /**
     * Broadcast receiver which detects a user has exit his circular stationary-region determined by the greater of stationaryLocation.getAccuracy() OR stationaryRadius
     */
    private BroadcastReceiver stationaryRegionReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String key = LocationManager.KEY_PROXIMITY_ENTERING;
            Boolean entering = intent.getBooleanExtra(key, false);
            if (entering) {
                logger.debug("Entering stationary region");
                if (isMoving) {
                    setPace(false);
                }
            } else {
                logger.debug("Exiting stationary region");
                // There MUST be a valid, recent location if this event-handler was called.
                Location location = getLastBestLocation();
                if (location != null) {
                    onExitStationaryRegion(location);
                }
            }
        }
    };

    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
        logger.debug("Provider {} was disabled", provider);
    }

    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
        logger.debug("Provider {} was enabled", provider);
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
        logger.debug("Provider {} status changed: {}", provider, status);
    }

    @Override
    public void onDestroy() {
        logger.info("Destroying DistanceFilterLocationProvider");
        this.onStop();
        alarmManager.cancel(stationaryAlarmPI);
        alarmManager.cancel(stationaryLocationPollingPI);
        unregisterReceiver(stationaryAlarmReceiver);
        unregisterReceiver(singleUpdateReceiver);
        unregisterReceiver(stationaryRegionReceiver);
        unregisterReceiver(stationaryLocationMonitorReceiver);
        super.onDestroy();
    }
}

18 Source : RawLocationProvider.java
with Apache License 2.0
from mauron85

@Override
public void onStart() {
    if (isStarted) {
        return;
    }
    Criteria criteria = new Criteria();
    criteria.setAlreplacedudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setSpeedRequired(true);
    criteria.setCostAllowed(true);
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setHorizontalAccuracy(translateDesiredAccuracy(mConfig.getDesiredAccuracy()));
    criteria.setPowerRequirement(Criteria.POWER_HIGH);
    try {
        locationManager.requestLocationUpdates(locationManager.getBestProvider(criteria, true), mConfig.getInterval(), mConfig.getDistanceFilter(), this);
        isStarted = true;
    } catch (SecurityException e) {
        logger.error("Security exception: {}", e.getMessage());
        this.handleSecurityException(e);
    }
}

18 Source : LocationManager.java
with Apache License 2.0
from mauron85

/**
 * Get current location without permission checking
 *
 * @param timeout
 * @param maximumAge
 * @param enableHighAccuracy
 * @return
 * @throws InterruptedException
 * @throws TimeoutException
 */
@SuppressLint("MissingPermission")
public Location getCurrentLocationNoCheck(int timeout, long maximumAge, boolean enableHighAccuracy) throws InterruptedException, TimeoutException {
    final long minLocationTime = System.currentTimeMillis() - maximumAge;
    final android.location.LocationManager locationManager = (android.location.LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
    Location lastKnownGPSLocation = locationManager.getLastKnownLocation(android.location.LocationManager.GPS_PROVIDER);
    if (lastKnownGPSLocation != null && lastKnownGPSLocation.getTime() >= minLocationTime) {
        return lastKnownGPSLocation;
    }
    Location lastKnownNetworkLocation = locationManager.getLastKnownLocation(android.location.LocationManager.NETWORK_PROVIDER);
    if (lastKnownNetworkLocation != null && lastKnownNetworkLocation.getTime() >= minLocationTime) {
        return lastKnownNetworkLocation;
    }
    Criteria criteria = new Criteria();
    criteria.setAccuracy(enableHighAccuracy ? Criteria.ACCURACY_FINE : Criteria.ACCURACY_COARSE);
    CurrentLocationListener locationListener = new CurrentLocationListener();
    locationManager.requestSingleUpdate(criteria, locationListener, Looper.getMainLooper());
    if (!locationListener.mCountDownLatch.await(timeout, TimeUnit.MILLISECONDS)) {
        locationManager.removeUpdates(locationListener);
        throw new TimeoutException();
    }
    if (locationListener.mLocation != null) {
        return locationListener.mLocation;
    }
    return null;
}

18 Source : g.java
with Apache License 2.0
from JackChan1999

public final void b() {
    try {
        Criteria criteria = new Criteria();
        criteria.setAccuracy(1);
        criteria.setAlreplacedudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(1);
        String bestProvider = this.d.getBestProvider(criteria, true);
        if (bestProvider != null) {
            this.e = this.d.getLastKnownLocation(bestProvider);
            if (this.e != null) {
                a(this.e);
            }
            this.d.requestLocationUpdates(bestProvider, SPConstant.DELAY_BUFFER_DURATION, replacedleBar.SHAREBTN_RIGHT_MARGIN, this.h);
        }
    } catch (SecurityException e) {
        z.d();
    } catch (Exception e2) {
        z.d();
    }
}

18 Source : GeoLocation.java
with GNU Lesser General Public License v3.0
from DanielBarnett714

/**
 * Get location double [ ].
 *
 * @return the double [ ]
 */
public Double[] getLocation() {
    Criteria criteria;
    String bestProvider;
    double lareplacedude, longitude;
    try {
        if (MainActivity.isLocationEnabled()) {
            criteria = new Criteria();
            bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();
            Location location = locationManager.getLastKnownLocation(bestProvider);
            if (location != null) {
                lareplacedude = location.getLareplacedude();
                longitude = location.getLongitude();
                Double[] coordinates = new Double[2];
                coordinates[0] = lareplacedude;
                coordinates[1] = longitude;
                return coordinates;
            } else {
                try {
                    updateLocation();
                    Handler h = new Handler(Looper.getMainLooper());
                    h.post(new Runnable() {

                        public void run() {
                            Toast.makeText(context, R.string.accessing_location, Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (RuntimeException e) {
                }
                return null;
            }
        } else {
            return null;
        }
    } catch (SecurityException e) {
        Handler h = new Handler(Looper.getMainLooper());
        h.post(new Runnable() {

            public void run() {
                Toast.makeText(context, R.string.location_not_enabled, Toast.LENGTH_SHORT).show();
            }
        });
        return null;
    }
}

18 Source : GeoLocation.java
with GNU Lesser General Public License v3.0
from DanielBarnett714

public void updateLocation() {
    Criteria criteria = new Criteria();
    String bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();
    try {
        locationManager.requestLocationUpdates(bestProvider, 60000, 15, this);
        Handler h = new Handler(Looper.getMainLooper());
        h.post(new Runnable() {

            public void run() {
                Toast.makeText(context, R.string.accessing_location, Toast.LENGTH_SHORT).show();
            }
        });
    } catch (SecurityException e) {
    }
}

18 Source : DeviceLocation.java
with MIT License
from appoly

public void startUpdatingLocation() {
    if (this.isLocationManagerUpdatingLocation == false) {
        isLocationManagerUpdatingLocation = true;
        runStartTimeInMillis = (long) (SystemClock.elapsedRealtimeNanos() / 1000000);
        locationList.clear();
        oldLocationList.clear();
        noAccuracyLocationList.clear();
        inaccurateLocationList.clear();
        kalmanNGLocationList.clear();
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // Exception thrown when GPS or Network provider were not available on the user's device.
        try {
            Criteria criteria = new Criteria();
            // setAccuracyは内部では、https://stackoverflow.com/a/17874592/1709287の用にHorizontalAccuracyの設定に変換されている。
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            criteria.setPowerRequirement(Criteria.POWER_HIGH);
            criteria.setAlreplacedudeRequired(false);
            criteria.setSpeedRequired(true);
            criteria.setCostAllowed(true);
            criteria.setBearingRequired(false);
            // API level 9 and up
            criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
            criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);
            // criteria.setBearingAccuracy(Criteria.ACCURACY_HIGH);
            // criteria.setSpeedAccuracy(Criteria.ACCURACY_HIGH);
            Integer gpsFreqInMillis = 5000;
            // in meters
            Integer gpsFreqInDistance = 1;
            // locationManager.addGpsStatusListener(this);
            locationManager.requestLocationUpdates(gpsFreqInMillis, gpsFreqInDistance, criteria, this, null);
            /* Battery Consumption Measurement */
            gpsCount = 0;
        } catch (IllegalArgumentException e) {
            Log.e(TAG, e.getLocalizedMessage());
        } catch (SecurityException e) {
            Log.e(TAG, e.getLocalizedMessage());
        } catch (RuntimeException e) {
            Log.e(TAG, e.getLocalizedMessage());
        }
    }
}

18 Source : DefaultLocation.java
with Apache License 2.0
from apache

private WXLocationListener findLocation(String watchId, String sucCallback, String errorCallback, boolean enableHighAccuracy, boolean enableAddress) {
    WXLogUtils.d(TAG, "into--[findLocation] mWatchId:" + watchId + "\nsuccessCallback:" + sucCallback + "\nerrorCallback:" + errorCallback + "\nenableHighAccuracy:" + enableHighAccuracy + "\nmEnableAddress:" + enableAddress);
    if (mLocationManager == null) {
        mLocationManager = (LocationManager) mWXSDKInstance.getContext().getSystemService(Context.LOCATION_SERVICE);
    }
    Criteria criteria = new Criteria();
    if (enableHighAccuracy) {
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    }
    // String provider = locationManager.getBestProvider(criteria, false);
    if (ActivityCompat.checkSelfPermission(mWXSDKInstance.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mWXSDKInstance.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        WXLocationListener WXLocationListener = new WXLocationListener(mLocationManager, mWXSDKInstance, watchId, sucCallback, errorCallback, enableAddress);
        if (mLocationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)) {
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, WXLocationListener);
        }
        if (mLocationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER)) {
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, WXLocationListener);
        }
        return WXLocationListener;
    } else {
        Map<String, Object> options = new HashMap<>();
        options.put(ERROR_CODE, ErrorCode.NO_PERMISSION_ERROR);
        options.put(ERROR_MSG, ErrorMsg.NO_PERMISSION_ERROR);
        if (mWXSDKInstance != null) {
            new SimpleJSCallback(mWXSDKInstance.getInstanceId(), errorCallback).invoke(options);
        }
    }
    return null;
}

17 Source : TestActivity.java
with MIT License
from tranquvis

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    startTime = System.currentTimeMillis();
    try {
        locationManager.requestSingleUpdate(criteria, this, null);
    } catch (SecurityException e) {
        Log.e(TAG, "permission not granted");
    }
}

17 Source : LocationProviderAndroid.java
with BSD 3-Clause "New" or "Revised" License
from ridi

/**
 * Registers this object with the location service.
 */
private void registerForLocationUpdates(boolean enableHighAccuracy) {
    createLocationManagerIfNeeded();
    if (usePreplacediveOneShotLocation())
        return;
    replacedert !mIsRunning;
    mIsRunning = true;
    // We're running on the main thread. The C++ side is responsible to
    // bounce notifications to the Geolocation thread as they arrive in the mainLooper.
    try {
        Criteria criteria = new Criteria();
        if (enableHighAccuracy)
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
        mLocationManager.requestLocationUpdates(0, 0, criteria, this, ThreadUtils.getUiThreadLooper());
    } catch (SecurityException e) {
        Log.e(TAG, "Caught security exception while registering for location updates " + "from the system. The application does not have sufficient " + "geolocation permissions.");
        unregisterFromLocationUpdates();
        // Propagate an error to JavaScript, this can happen in case of WebView
        // when the embedding app does not have sufficient permissions.
        LocationProviderAdapter.newErrorAvailable("application does not have sufficient geolocation permissions.");
    } catch (IllegalArgumentException e) {
        Log.e(TAG, "Caught IllegalArgumentException registering for location updates.");
        unregisterFromLocationUpdates();
        replacedert false;
    }
}

17 Source : MyLocationActivity.java
with Apache License 2.0
from mohammadima3oud

private void goToMyLocation() {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        enableMyLocation();
    } else {
        googleMap.setMyLocationEnabled(true);
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
        if (location != null) {
            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLareplacedude(), location.getLongitude()), 13));
        }
    }
}

17 Source : GPSLocationProvider.java
with MIT License
from maddevsio

@RequiresPermission(ACCESS_FINE_LOCATION)
public void startLocationUpdates(Settings m_settings, HandlerThread thread) {
    m_locationManager.removeGpsStatusListener(gpsListener);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        m_locationManager.registerGnssStatusCallback(executorService, gnssStatus);
    } else {
        m_locationManager.addGpsStatusListener(gpsListener);
    }
    m_locationManager.removeUpdates(this);
    if (m_settings.onlyGpsSensor) {
        m_locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, m_settings.gpsMinTime, m_settings.gpsMinDistance, this);
    } else {
        thread.start();
        Criteria criteria = new Criteria();
        criteria.setSpeedRequired(true);
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setSpeedAccuracy(Criteria.ACCURACY_HIGH);
        criteria.setPowerRequirement(Criteria.POWER_HIGH);
        m_locationManager.requestLocationUpdates(m_settings.gpsMinTime, m_settings.gpsMinDistance, criteria, this, thread.getLooper());
    }
}

17 Source : MyLocation.java
with Apache License 2.0
from LuoPeiQin

public String getLocationInfo() {
    if (locationManager == null) {
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    }
    Criteria criteria = new Criteria();
    // 设置为最大精度
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    // 不要求海拔信息
    criteria.setAlreplacedudeRequired(false);
    // 是否允许付费
    criteria.setCostAllowed(true);
    // 对电量的要求
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    // 不要求Bearing信息
    criteria.setBearingRequired(false);
    String bestProvider = locationManager.getBestProvider(criteria, true);
    Log.i(TAG, "bestProvider=" + bestProvider);
    // 1秒,2米
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, mLocationListener);
    LocationProvider locationProvider = locationManager.getProvider(LocationManager.NETWORK_PROVIDER);
    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    if (null == location) {
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    }
    if (null == location) {
        location = locationManager.getLastKnownLocation(bestProvider);
    }
    updateWithNewLocation(location);
    // locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, mLocationListener);
    return returnData;
}

17 Source : GpsTraceService.java
with MIT License
from ittianyu

@Override
public void onCreate() {
    super.onCreate();
    // locate
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // check permission
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    // get best provider
    Criteria criteria = new Criteria();
    criteria.setCostAllowed(true);
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    String bestProvider = locationManager.getBestProvider(criteria, true);
    System.out.println("best provider:" + bestProvider);
    // start listening
    listener = new MyLocationListener();
    locationManager.requestLocationUpdates(bestProvider, 0, 0, listener);
}

17 Source : LocationProviderAndroid.java
with Apache License 2.0
from GoogleChrome

/**
 * Registers this object with the location service.
 */
private void registerForLocationUpdates(boolean enableHighAccuracy) {
    createLocationManagerIfNeeded();
    if (usePreplacediveOneShotLocation())
        return;
    replacedert !mIsRunning;
    mIsRunning = true;
    try {
        Criteria criteria = new Criteria();
        if (enableHighAccuracy)
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
        mLocationManager.requestLocationUpdates(0, 0, criteria, this, Looper.getMainLooper());
    } catch (SecurityException e) {
        Log.e(TAG, "Caught security exception while registering for location updates " + "from the system. The application does not have sufficient " + "geolocation permissions.");
        unregisterFromLocationUpdates();
        // Propagate an error to JavaScript, this can happen in case of WebView
        // when the embedding app does not have sufficient permissions.
        notifyLocationErrorWithMessage("Application does not have sufficient geolocation permissions.");
    } catch (IllegalArgumentException e) {
        Log.e(TAG, "Caught IllegalArgumentException registering for location updates.");
        unregisterFromLocationUpdates();
    }
}

17 Source : MainActivity.java
with Apache License 2.0
from eborghi10

@Override
protected void init(NodeMainExecutor nodeMainExecutor) {
    Log.d(TAG, "init()");
    final LocationPublisherNode locationPublisherNode = new LocationPublisherNode();
    ImuPublisherNode imuPublisherNode = new ImuPublisherNode();
    MainActivity.this.locationFrameIdListener = locationPublisherNode.getFrameIdListener();
    MainActivity.this.imuFrameIdListener = imuPublisherNode.getFrameIdListener();
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAlreplacedudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setSpeedRequired(false);
    criteria.setCostAllowed(true);
    final String provider = LocationManager.GPS_PROVIDER;
    String svcName = Context.LOCATION_SERVICE;
    final LocationManager locationManager = (LocationManager) getSystemService(svcName);
    final int t = 500;
    final float distance = 0.1f;
    MainActivity.this.runOnUiThread(new Runnable() {

        @Override
        public void run() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                boolean permissionFineLocation = checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
                boolean permissionCoarseLocation = checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
                Log.d(TAG, "PERMISSION 1: " + String.valueOf(permissionFineLocation));
                Log.d(TAG, "PERMISSION 2: " + String.valueOf(permissionCoarseLocation));
                if (permissionFineLocation && permissionCoarseLocation) {
                    if (locationManager != null) {
                        Log.d(TAG, "Requesting location");
                        locationManager.requestLocationUpdates(provider, t, distance, locationPublisherNode.getLocationListener());
                    }
                } else {
                    // Request permissions
                    requestPermissions(new String[] { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION }, PackageManager.GET_PERMISSIONS);
                }
            } else {
                locationManager.requestLocationUpdates(provider, t, distance, locationPublisherNode.getLocationListener());
            }
        }
    });
    SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    try {
        Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(imuPublisherNode.getAccelerometerListener(), accelerometer, SensorManager.SENSOR_DELAY_FASTEST);
    } catch (NullPointerException e) {
        Log.e(TAG, e.toString());
        return;
    }
    SensorManager sensorManager1 = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    try {
        Sensor gyroscope = sensorManager1.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
        sensorManager1.registerListener(imuPublisherNode.getGyroscopeListener(), gyroscope, SensorManager.SENSOR_DELAY_FASTEST);
    } catch (NullPointerException e) {
        Log.e(TAG, e.toString());
        return;
    }
    SensorManager sensorManager2 = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    try {
        Sensor orientation = sensorManager2.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        sensorManager2.registerListener(imuPublisherNode.getOrientationListener(), orientation, SensorManager.SENSOR_DELAY_FASTEST);
    } catch (NullPointerException e) {
        Log.e(TAG, e.toString());
        return;
    }
    // At this point, the user has already been prompted to either enter the URI
    // of a master to use or to start a master locally.
    // The user can easily use the selected ROS Hostname in the master chooser
    // activity.
    NodeConfiguration nodeConfiguration = NodeConfiguration.newPublic(InetAddressFactory.newNonLoopback().getHostAddress());
    nodeConfiguration.setMasterUri(getMasterUri());
    nodeMainExecutor.execute(locationPublisherNode, nodeConfiguration);
    nodeMainExecutor.execute(imuPublisherNode, nodeConfiguration);
    onClick(null);
}

17 Source : GPSLocationManager.java
with Apache License 2.0
from dbbahnhoflive

private Location getBestLastKnownLocation(Context context) {
    Criteria criteria = new Criteria();
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
    } else if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    }
    String provider = locationManager.getBestProvider(criteria, true);
    return locationManager.getLastKnownLocation(provider);
}

17 Source : LocationProvider.java
with GNU General Public License v3.0
from boygaggoo

/**
 * Sets location updates for better performance.
 */
public synchronized void requestFineUpdates() {
    synchronized (this) {
        mFineRequestsNum++;
        if (mIsFineMode)
            return;
        mIsFineMode = true;
    }
    int fineLocationPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION);
    int coarseLocationPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION);
    if (fineLocationPermission == PackageManager.PERMISSION_GRANTED || coarseLocationPermission == PackageManager.PERMISSION_GRANTED) {
        Criteria c = new Criteria();
        c.setAccuracy(Criteria.ACCURACY_FINE);
        c.setPowerRequirement(Criteria.POWER_HIGH);
        c.setAlreplacedudeRequired(false);
        c.setBearingRequired(false);
        c.setCostAllowed(false);
        c.setSpeedRequired(false);
        mLocationManager.requestLocationUpdates(FINE_MIN_LOCATION_TIME, FINE_MIN_LOCATION_DISTANCE, c, this, mLooper);
        Log.d(TAG, "switch to fine mode");
    } else {
        Log.w(TAG, "no permissions to start fine mode");
    }
}

17 Source : LocationProvider.java
with GNU General Public License v3.0
from boygaggoo

/**
 * Sets location updates for power saving.
 */
public void requestCoarseUpdates() {
    synchronized (this) {
        if (!mIsFineMode)
            return;
        mIsFineMode = false;
        mFineRequestsNum = 0;
    }
    int fineLocationPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION);
    int coarseLocationPermission = ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION);
    if (fineLocationPermission == PackageManager.PERMISSION_GRANTED || coarseLocationPermission == PackageManager.PERMISSION_GRANTED) {
        Criteria c = new Criteria();
        c.setAccuracy(Criteria.ACCURACY_COARSE);
        c.setPowerRequirement(Criteria.POWER_LOW);
        c.setAlreplacedudeRequired(false);
        c.setBearingRequired(false);
        c.setCostAllowed(false);
        c.setSpeedRequired(false);
        mLocationManager.requestLocationUpdates(COARSE_MIN_LOCATION_TIME, COARSE_MIN_LOCATION_DISTANCE, c, this, mLooper);
        Log.d(TAG, "switch to coarse mode");
    } else {
        Log.w(TAG, "no permissions to start coarse mode");
    }
}

17 Source : Utils.java
with GNU General Public License v3.0
from bidmachine

static Location getLocation(Context context) {
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    if (locationManager != null) {
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, false);
        if (bestProvider != null) {
            try {
                Location location = locationManager.getLastKnownLocation(bestProvider);
                if (location == null) {
                    List<String> allProviders = locationManager.getAllProviders();
                    if (allProviders != null && allProviders.size() > 1) {
                        for (String provider : allProviders) {
                            if (provider != null && !provider.equals(bestProvider)) {
                                location = locationManager.getLastKnownLocation(provider);
                                if (location != null) {
                                    break;
                                }
                            }
                        }
                    }
                }
                return location;
            } catch (SecurityException | IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

17 Source : MainActivity.java
with GNU General Public License v3.0
from beegee-tokyo

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportFragmentManager().addOnBackStackChangedListener(this);
    if (savedInstanceState == null)
        getSupportFragmentManager().beginTransaction().add(R.id.fragment, new DevicesFragment(), "devices").commit();
    else
        onBackStackChanged();
    // Get pointer to shared preferences
    mPrefs = getSharedPreferences(sharedPrefName, 0);
    // if (mPrefs.contains("userName")) {
    // userName = mPrefs.getString("userName", "me");
    // }
    appContext = this;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setreplacedle(R.string.location_permission_replacedle);
            builder.setMessage(R.string.location_permission_message);
            builder.setPositiveButton(android.R.string.ok, (dialog, which) -> requestPermissions(new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, 0));
            builder.show();
            return;
        }
    }
    ArrayList<String> arrPerm = new ArrayList<>();
    // On newer Android versions it is required to get the permission of the user to
    // access the storage of the device.
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
        arrPerm.add(Manifest.permission.INTERNET);
    }
    // On newer Android versions it is required to get the permission of the user to
    // access the storage of the device.
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        arrPerm.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        arrPerm.add(Manifest.permission.ACCESS_COARSE_LOCATION);
    }
    if (!arrPerm.isEmpty()) {
        String[] permissions = new String[arrPerm.size()];
        permissions = arrPerm.toArray(permissions);
        ActivityCompat.requestPermissions(this, permissions, 0);
    }
    // Enable access to internet
    // ThreadPolicy to get permission to access internet
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    // TODO select the best provider
    locationManagerGPS = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManagerNetwork = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManagerPreplacedive = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria bestProviderCriteria = new Criteria();
    bestProviderCriteria.setHorizontalAccuracy(ACCURACY_HIGH);
    bestProviderCriteria.setAccuracy(ACCURACY_FINE);
    String bestProvider = locationManagerGPS.getBestProvider(bestProviderCriteria, true);
    Log.d(TAG, "Best provider is " + bestProvider);
    boolean locationGPSEnabled = false;
    boolean locationNetEnabled = false;
    boolean locationOtherEnabled = false;
    // TODO use the best provider
    try {
        locationGPSEnabled = Objects.requireNonNull(locationManagerGPS).isProviderEnabled(LocationManager.GPS_PROVIDER);
        locationManagerGPS.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
    } catch (Exception ignored) {
    }
    try {
        locationNetEnabled = Objects.requireNonNull(locationManagerNetwork).isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        locationManagerNetwork.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
    } catch (Exception ignored) {
    }
    try {
        locationOtherEnabled = Objects.requireNonNull(locationManagerPreplacedive).isProviderEnabled(LocationManager.PreplacedIVE_PROVIDER);
        locationManagerPreplacedive.requestLocationUpdates(LocationManager.PreplacedIVE_PROVIDER, 1000, 0, this);
    } catch (Exception ignored) {
    }
    if ((!locationGPSEnabled) && (!locationNetEnabled) && (!locationOtherEnabled)) {
        Toast.makeText(getApplicationContext(), getString(R.string.info_no_gps), Toast.LENGTH_SHORT).show();
        Log.e(TAG, getString(R.string.info_no_gps));
    }
}

16 Source : TrackService.java
with GNU General Public License v2.0
from videgro

private void askLocationManagerForLocationUpdates() {
    final String tag = "askLocationManagerForLocationUpdates - ";
    // Define the criteria how to select the location provider -> use
    // default
    Criteria criteria = new Criteria();
    final String provider = locationManager.getBestProvider(criteria, true);
    Log.i(TAG, "Provider " + provider + " has been selected.");
    replacedytics.logEvent(this, TAG, "SelectedProvider", provider);
    if (provider != null) {
        try {
            Location location = locationManager.getLastKnownLocation(provider);
            if (location != null) {
                onLocationChanged(location);
            }
            /*
				 * Minimum time: 1000 ms Minimum distance: 8 meters
				 *
				 */
            locationManager.requestLocationUpdates(provider, 1000, 8, this);
            replacedytics.logEvent(this, TAG, tag, "");
        } catch (SecurityException e) {
            Log.e(TAG, tag + "SecurityException", e);
            replacedytics.logEvent(this, TAG, tag, e.getMessage());
        }
    } else {
        Log.w(TAG, tag + "No Provider available.");
    }
}

16 Source : LocationUtils.java
with MIT License
from tranquvis

/**
 * listen on location changed and save the new location to LocationUtils.lastLocation
 *
 * @param context app context
 * @throws SecurityException
 */
private static void RequestNewLocation(Context context) throws SecurityException {
    lastLocation = null;
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    LocationListener locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            lastLocation = location;
            Log.i(TAG, location.toString());
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {
            Log.i(TAG, "status changed: " + s);
        }

        @Override
        public void onProviderEnabled(String s) {
            Log.i(TAG, "provider enabled: " + s);
        }

        @Override
        public void onProviderDisabled(String s) {
            Log.e(TAG, "provider disabled: " + s);
        }
    };
    locationManager.requestSingleUpdate(criteria, locationListener, Looper.getMainLooper());
}

16 Source : MainActivity.java
with GNU General Public License v3.0
from rrrlasse

public clreplaced MainActivity extends FragmentActivity implements LocationListener, IFragmentToActivity {

    public File dir;

    public File file_full;

    public File file_simple;

    // to compute average_speed = speed_sum / speed_samples
    double speed_sum = 0;

    int speed_samples = 0;

    double metab = 4.33;

    public String str(double d) {
        d = d > 9999999 ? 9999999 : (d < -9999999 ? -9999999 : d);
        double a = Math.abs(d);
        // String s = String.format(Locale.ROOT, a >= 100 ? "%.0f" : (a >= 10 ? "%.1f" : "%.2f"), d);
        String s = String.format(Locale.ROOT, a >= 10 ? "%.0f" : "%.1f", d);
        s = s.equals("-0") ? "0" : (s.equals("-0.0") ? "0.0" : (s.equals("-0.00") ? "0.00" : s));
        return s;
    }

    @Override
    public void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    @Override
    public void communicateToFragment2() {
    }

    @Override
    public void onBackPressed() {
        if (mPager.getCurrenreplacedem() == 0) {
            // If the user is currently looking at the first step, allow the system to handle the
            // Back button. This calls finish() on this activity and pops the back stack.
            super.onBackPressed();
        } else {
            // Otherwise, select the previous step.
            mPager.setCurrenreplacedem(mPager.getCurrenreplacedem() - 1);
        }
    }

    private clreplaced ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {

        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment gereplacedem(int position) {
            ScreenSlidePageFragment sf = ScreenSlidePageFragment.create(position);
            return sf;
        }

        @Override
        public int getCount() {
            return NUM_PAGES;
        }
    }

    private static final int NUM_PAGES = 3;

    /**
     * The pager widget, which handles animation and allows swiping horizontally to access previous
     * and next wizard steps.
     */
    private ViewPager mPager;

    /**
     * The pager adapter, which provides the pages to the view pager widget.
     */
    private PagerAdapter mPagerAdapter;

    long last_gui_refresh = 0;

    long last_stat_refresh = 0;

    int last_samples = 0;

    Vector<Vector<Double>> smooth_avg = new Vector<Vector<Double>>();

    TextView sensorView1, speed, watts, textView_speed, textView_avgspeed, textView_value, textView_description;

    Handler bluetoothIn;

    public boolean bluetoothConnected = false;

    NumberPicker np;

    // used to identify handler message
    final int handlerState = 0;

    private BluetoothAdapter btAdapter = null;

    private BluetoothSocket btSocket = null;

    private ConnectedThread mConnectedThread;

    // SPP UUID service - this should work for most devices
    private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    // String for MAC address
    private static String address;

    Parser parser = new Parser();

    Display display = new Display();

    long android_start_time;

    double powermeter_sum_time = 0;

    OutputStream fo_full;

    Writer w_full;

    OutputStream fo_simple;

    Writer w_simple;

    LocationManager locationManager;

    Criteria criteria = new Criteria();

    String bestProvider;

    // Set the global variable `w` to an output stream
    void create_log_file() {
        // Create log file
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String currentDateandTime = sdf.format(new Date());
        String path;
        if (Build.VERSION.SDK_INT >= 19) {
            file_full = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOreplacedENTS) + "/Powermeter/Full/" + currentDateandTime + ".txt");
            file_simple = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOreplacedENTS) + "/Powermeter/Simple/" + currentDateandTime + ".txt");
        } else {
            file_full = new File(Environment.getExternalStorageDirectory() + "/Doreplacedents" + "/Powermeter/Full/" + currentDateandTime + ".txt");
            file_simple = new File(Environment.getExternalStorageDirectory() + "/Doreplacedents" + "/Powermeter/Simple/ " + currentDateandTime + ".txt");
        }
        try {
            file_full.createNewFile();
            file_simple.createNewFile();
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Could not create log file. Try and insert an SD Card.", Toast.LENGTH_SHORT).show();
        }
        try {
            fo_full = new FileOutputStream(file_full);
            w_full = new OutputStreamWriter(fo_full);
            fo_simple = new FileOutputStream(file_simple);
            w_simple = new OutputStreamWriter(fo_simple);
            w_full.write("# time (ms), watt, cadence (RPM), torque (Nm), pedal position, speed (km/h)\r\n");
            w_full.write("\r\n");
            w_simple.write("# See trip summary at the bottom of this file.\r\n");
            w_simple.write("#\r\n");
            w_simple.write("# time, watt, cadence (RPM), 30s watt avg, speed (km/h), avg speed, metab kcal, pedal smoothness, pedal kg\r\n");
        } catch (Exception e) {
        }
    }

    double speed() {
        Location location = locationManager.getLastKnownLocation(bestProvider);
        double d;
        try {
            d = location.getSpeed();
        } catch (Exception e) {
            d = -1;
        }
        return d * 3.6;
    }

    @Override
    public void onLocationChanged(Location location) {
        int t = 34;
    }

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

    @Override
    public void onProviderEnabled(String s) {
    }

    @Override
    public void onProviderDisabled(String s) {
    }

    String all = "";

    void Sleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (Exception e) {
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        parser.bike_number = getPreferences(Context.MODE_PRIVATE).getInt("bike_number", 0);
        // Instantiate a ViewPager and a PagerAdapter.
        mPager = (ViewPager) findViewById(R.id.pager);
        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);
        watts = (TextView) findViewById(R.id.watts);
        speed = (TextView) findViewById(R.id.speed);
        np = (NumberPicker) findViewById(R.id.numberPicker);
        np.setMaxValue(30);
        np.setMinValue(1);
        np.setValue(getPreferences(Context.MODE_PRIVATE).getInt("seconds_average", 4));
        android_start_time = System.currentTimeMillis();
        if (Build.VERSION.SDK_INT >= 19) {
            dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOreplacedENTS) + "/Powermeter/Full");
            dir.mkdirs();
            dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOreplacedENTS) + "/Powermeter/Simple");
            dir.mkdirs();
        } else {
            dir = new File(Environment.getExternalStorageDirectory() + "/Doreplacedents" + "/Powermeter/Full");
            dir.mkdirs();
            dir = new File(Environment.getExternalStorageDirectory() + "/Doreplacedents" + "/Powermeter/Simple");
            dir.mkdirs();
        }
        speed_samples = 0;
        speed_sum = 0;
        bluetoothIn = new Handler() {

            public void handleMessage(Message msg) {
                String str = "";
                if (msg.what != handlerState) {
                    str = "";
                } else {
                    str = (String) msg.obj;
                }
                {
                    // all = all.concat(str);
                    String info = "";
                    parser.parse(str);
                    for (int i = 0; i + 1 < parser.points.size(); i++) {
                        Point p = parser.points.get(i);
                        powermeter_sum_time += p.duration;
                        if (w_full != null) {
                            try {
                                w_full.write((int) (powermeter_sum_time * 1000) + "\t" + str(p.watt) + "\t" + str(p.cadence) + "\t" + str(p.torque) + "\t" + str(p.position) + "\t" + str(speed()) + "\r\n");
                            } catch (Exception e) {
                            }
                        }
                        display.feed(p);
                    }
                    if (parser.points.size() > 1) {
                        parser.points.subList(0, parser.points.size() - 1).clear();
                    }
                    // Refresh the GUI only if:
                    // 1 second elapsed sincelast refresh, and
                    // power meter is transmitting data, and
                    // calibration for selected bike is OK
                    long elapsed = System.currentTimeMillis() - last_gui_refresh;
                    if (elapsed > 1000 && display.points.size() > 0 && parser.calibrate_initialized[parser.bike_number] == 1) {
                        // drawView.invalidate();
                        last_gui_refresh = System.currentTimeMillis();
                        int s = np.getValue();
                        // abs to avoid String.format giving "-0.0"
                        double w = Math.abs(display.watt(s));
                        watts.setText(str(w));
                        double sp = speed();
                        speed_samples++;
                        speed_sum += sp;
                        double avg_speed = speed_sum / speed_samples;
                        speed.setText(str(sp));
                        power_bar(w, 50);
                        // FIXME: To test this for null is a bad way to find out if main screen is visible
                        TextView textView_watt_trip = (TextView) findViewById(R.id.textView_watt_trip);
                        {
                            if (parser.battery != 0 && parser.battery < 3.5) {
                                // Bluetooth becomes unstable around 3.3 V
                                ImageView imageView_battery = (ImageView) findViewById(R.id.imageView_battery);
                                imageView_battery.setVisibility(View.VISIBLE);
                            }
                            double w2 = display.watt(30);
                            double kcal = display.total_joule / 4184.;
                            // replaceduming 22.5% human body efficiency (studies show it's 20 - 25)
                            double kcal_metab = kcal * metab;
                            long millis = (long) (powermeter_sum_time * 1000);
                            DateFormat df = new SimpleDateFormat("H:mm:ss");
                            df.setTimeZone(TimeZone.getTimeZone("GMT+0"));
                            String triptime = df.format(new Date(millis));
                            if (textView_watt_trip != null && display.points.size() > 0) {
                                TextView textView_30s = (TextView) findViewById(R.id.textView_30s);
                                TextView textView_rpm = (TextView) findViewById(R.id.textView_rpm);
                                textView_avgspeed = (TextView) findViewById(R.id.textView_avgspeed);
                                TextView textView_metabolic = (TextView) findViewById(R.id.textView_metabolic);
                                TextView textView_trip = (TextView) findViewById(R.id.textView_trip);
                                TextView textView_smoothness = (TextView) findViewById(R.id.textView_smoothness);
                                TextView textView_kg = (TextView) findViewById(R.id.textView_kg);
                                textView_metabolic.setText(str(kcal_metab));
                                textView_trip.setText(triptime);
                                textView_watt_trip.setText(str(display.total_joule / ((millis / 1000) == 0 ? 1 : (millis / 1000))));
                                textView_smoothness.setText(Integer.toString((int) display.smoothness()) + "%");
                                textView_kg.setText(str(display.kg()));
                                textView_30s.setText(str(w2));
                                textView_avgspeed.setText(str(avg_speed));
                                // again int cast to avoid "-0" of String.format
                                textView_rpm.setText(Integer.toString((int) display.cadance()));
                            }
                            if (w_simple != null) {
                                try {
                                    w_simple.write(// triptime
                                    triptime + "\t" + // current watt
                                    str(w) + "\t" + // cadence
                                    Integer.toString((int) display.cadance()) + "\t" + // 30 sec avg wattage
                                    str(w2) + "\t" + // speed, km/h
                                    str(speed()) + "\t" + // avg trip speed
                                    str(avg_speed) + "\t" + // metab kcal
                                    str(kcal_metab) + "\t" + Integer.toString((int) display.smoothness()) + // pedal smoothness
                                    "%" + "\t" + // pedal force
                                    str(display.kg()) + "\r\n");
                                } catch (Exception e) {
                                }
                            }
                        }
                        textView_value = (TextView) findViewById(R.id.textView_value);
                        if (textView_value != null && display.points.size() > 0) {
                            double kg = display.kg();
                            String d = "";
                            String v = "";
                            d += "Pedal pressure: \n";
                            v += String.format(Locale.ROOT, "%.2f", kg) + " kg\n";
                            d += "Powermeter temp.: \n";
                            v += str(parser.temperature) + " C\n";
                            d += "Data errors: \n";
                            v += parser.data_errors + "\n";
                            d += "Vcc/Battery: \n";
                            v += str(parser.vcc) + " / " + str(parser.battery) + " V\n";
                            d += "adc spikes (h/b): \n";
                            v += parser.spikes_high + "/" + parser.spikes_bump + "\n";
                            d += "gauge voltage: \n";
                            v += (display.points.size() > 0 ? display.points.get(display.points.size() - 1).voltage : 0) + "\n";
                            double gauge_rate = 0;
                            if (display.points.size() >= 50) {
                                float sum_d = 0;
                                for (int x = 0; x < 50; x++) {
                                    sum_d += display.points.get(display.points.size() - 1 - x).duration;
                                }
                                gauge_rate = 50 / sum_d;
                            }
                            d += "BTooth/gauge rate: ";
                            v += (parser.samples - last_samples) * 1000 / elapsed + " / " + (int) (gauge_rate) + " samples/sec\n";
                            d += "\n";
                            v += "\n";
                            d += "\nCalibration values:\n";
                            v += "(bike1 / bike2)\n";
                            boolean b1 = parser.calibrate_initialized[0] == 1;
                            boolean b2 = parser.calibrate_initialized[1] == 1;
                            d += "Status: \n";
                            v += (b1 ? "OK" : "Missing") + " / " + (b2 ? "OK" : "Missing") + "\n";
                            d += "Arm forwards: \n";
                            v += str(!b1 ? 0 : parser.calibrate_forward[0]) + " / " + str(!b2 ? 0 : parser.calibrate_forward[1]) + "\n";
                            d += "Arm backwards: \n";
                            v += str(!b1 ? 0 : parser.calibrate_backwards[0]) + " / " + str(!b2 ? 0 : parser.calibrate_backwards[1]) + "\n";
                            d += "Delta dvdf: \n";
                            v += str(!b1 ? 0 : parser.calibrate_dvdf[0]) + " / " + str(!b2 ? 0 : parser.calibrate_dvdf[1]) + "\n";
                            d += "Zero velocity: \n";
                            v += str(!b1 ? 0 : parser.calibrate_velocity[0]) + " / " + str(!b2 ? 0 : parser.calibrate_velocity[1]) + "\n";
                            d += "Arm length (mm): \n";
                            v += String.format(Locale.ROOT, "%.1f", !b1 ? 0 : parser.calibrate_arm[0] * 1000) + " / " + String.format(Locale.ROOT, "%.1f", !b2 ? 0 : parser.calibrate_arm[1] * 1000) + "\n";
                            textView_description = (TextView) findViewById(R.id.textView_description);
                            textView_description.setText(d);
                            textView_value.setText(v);
                            TextView textView_sample = (TextView) findViewById(R.id.textView_sample);
                            textView_sample.setText("Last sample (timer, gauge, gyro, accel):\n" + parser.sample.replaceAll("\t", " \t "));
                        }
                        last_samples = parser.samples;
                    }
                    if (System.currentTimeMillis() - last_stat_refresh > 30000) {
                        mConnectedThread.write("s");
                        last_stat_refresh = System.currentTimeMillis();
                    }
                    int bike = parser.bike_number;
                    if (parser.calibration_type == Constants.CalibrationStatus.WEIGHT_DONE) {
                        Toast.makeText(getApplicationContext(), "Weight calibration OK (gauge = " + (int) parser.calibrate_weight + ")", Toast.LENGTH_LONG).show();
                        parser.calibration_type = Constants.CalibrationStatus.NONE;
                        eprom_write((float) parser.calibrate_arm[bike], EEPROM.ARM[bike]);
                    }
                    if (parser.calibration_type == Constants.CalibrationStatus.FORWARDS_DONE) {
                        Toast.makeText(getApplicationContext(), "Forwards/zero calibration OK (gauge = " + (int) parser.calibrate_forward[bike] + ")", Toast.LENGTH_LONG).show();
                        parser.calibration_type = Constants.CalibrationStatus.NONE;
                        eprom_write((float) parser.calibrate_forward[bike], EEPROM.FORWARDS[bike]);
                        eprom_write((float) parser.calibrate_velocity[bike], EEPROM.VELOCITY[bike]);
                    }
                    if (parser.calibration_type == Constants.CalibrationStatus.BACKWARDS_DONE) {
                        parser.calibration_type = Constants.CalibrationStatus.NONE;
                        Toast.makeText(getApplicationContext(), "Backwards calibration OK (gauge = " + (int) parser.calibrate_backwards[bike] + ")", Toast.LENGTH_LONG).show();
                        mConnectedThread.write("C");
                        eprom_write((float) parser.calibrate_backwards[bike], EEPROM.BACKWARDS[bike]);
                        eprom_write((float) parser.calibrate_dvdf[bike], EEPROM.DVDF[bike]);
                        // will be 1
                        eprom_write((float) parser.calibrate_initialized[bike], EEPROM.INITIALIZED[bike]);
                        mConnectedThread.write("c");
                    }
                }
            }
        };
        // get Bluetooth adapter
        btAdapter = BluetoothAdapter.getDefaultAdapter();
    // checkBTState();
    }

    void power_bar(double watts, double snap_to) {
        // Draw the green power bar
        int w = (int) watts;
        int s = (int) snap_to;
        android.widget.FrameLayout a = (android.widget.FrameLayout) findViewById(R.id.a);
        android.widget.FrameLayout b = (android.widget.FrameLayout) findViewById(R.id.b);
        android.widget.LinearLayout bar = (android.widget.LinearLayout) findViewById(R.id.bar);
        ViewGroup.LayoutParams pa = a.getLayoutParams();
        ViewGroup.LayoutParams pb = b.getLayoutParams();
        int bh = bar.getHeight();
        int n100 = (w + (s / 2)) / s * s;
        double diff = n100 - w;
        if (diff > 0) {
            pa.height = 0;
            pb.height = (int) (diff / (s / 2) * (bh * 2 / 3));
        } else {
            pb.height = 0;
            pa.height = (int) ((-diff) / (s / 2) * (bh * 2 / 3));
        }
        a.setLayoutParams(pa);
        b.setLayoutParams(pb);
    }

    void eprom_write(float value, long address) {
        byte[] dvdf_bytes = ByteBuffer.allocate(8).putFloat(value).array();
        // ew addr count byte
        String s = "ew " + address + " 4";
        for (int i = 0; i < 4; i++) {
            s = s + " ";
            int b = dvdf_bytes[i] < 0 ? 256 + dvdf_bytes[i] : dvdf_bytes[i];
            s = s + b;
        }
        s = s + "\n";
        mConnectedThread.write(s);
        Sleep(100);
    }

    void eprom_read(long address) {
        mConnectedThread.write("er " + address + " 4\n");
        Sleep(100);
    }

    void eprom_read(long address, int bytes) {
        mConnectedThread.write("er " + address + " " + bytes + "\n");
        Sleep(100);
    }

    private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
        return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
    // creates secure outgoing connecetion with BT device using UUID
    }

    @Override
    public void onResume() {
        super.onResume();
        // Get MAC address from DeviceListActivity via intent
        Intent intent = getIntent();
        // Get the MAC address from the DeviceListActivty via EXTRA
        address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
        if (Constants.ENABLE_BLUETOOTH) {
            // create device and set the MAC address
            BluetoothDevice device = btAdapter.getRemoteDevice(address);
            IntentFilter filter = new IntentFilter();
            filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
            filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
            try {
                btSocket = createBluetoothSocket(device);
            } catch (IOException e) {
                Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
            }
            // Establish the Bluetooth socket connection.
            try {
                btSocket.connect();
            } catch (IOException e) {
                try {
                    btSocket.close();
                } catch (IOException e2) {
                // insert code to deal with this
                }
            }
            mConnectedThread = new ConnectedThread(btSocket);
            mConnectedThread.start();
        }
        // I send a character when resuming.beginning transmission to check device is connected
        // If it is not an exception will be thrown in the write method and finish() will be called
        // Activate GPS
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, this);
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        bestProvider = locationManager.getBestProvider(criteria, true);
        if (Constants.ENABLE_BLUETOOTH) {
            mConnectedThread.write("c");
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        try {
            locationManager.removeUpdates(this);
            getPreferences(Context.MODE_PRIVATE).edit().putInt("seconds_average", np.getValue()).commit();
            if (Constants.ENABLE_BLUETOOTH) {
                mConnectedThread.write("C");
            }
            if (w_simple != null) {
                w_simple.write("# kcal = " + str(display.total_joule / 4184.) + "\r\n");
                w_simple.write("# metabolic kcal = " + str(display.total_joule / 4184. * metab) + "\r\n");
                w_simple.write("# average trip wattage = " + str(display.total_joule / ((System.currentTimeMillis() - android_start_time) / 1000)) + "\r\n");
                w_simple.flush();
                w_simple.close();
                w_full.flush();
                w_full.close();
            }
            if (Constants.ENABLE_BLUETOOTH) {
                // Don't leave Bluetooth sockets open when leaving activity
                btSocket.close();
            }
        } catch (IOException e2) {
        // insert code to deal with this
        }
    }

    // Checks that the Android device Bluetooth is available and prompts to be turned on if off
    private void checkBTState() {
        if (btAdapter == null) {
            Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
        } else {
            if (btAdapter.isEnabled()) {
            } else {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 1);
            }
        }
    }

    // create new clreplaced for connect thread
    private clreplaced ConnectedThread extends Thread {

        private final InputStream mmInStream;

        private final OutputStream mmOutStream;

        // creation of the connect thread
        public ConnectedThread(BluetoothSocket socket) {
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            try {
                // Create I/O streams for connection
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
            }
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            if (Constants.ENABLE_BLUETOOTH) {
                byte[] buffer = new byte[256];
                int bytes;
                try {
                    mmInStream.read(buffer);
                    bluetoothConnected = true;
                } catch (Exception e) {
                }
                if (bluetoothConnected) {
                    create_log_file();
                    mConnectedThread.write("C");
                    eprom_read(0, 48);
                    mConnectedThread.write("c");
                }
                // Keep looping to listen for received messages
                while (true) {
                    try {
                        // Send dummy message to refresh the GUI
                        bluetoothIn.obtainMessage(handlerState, 0, -1, "").sendToTarget();
                        Sleep(200);
                        if (bluetoothConnected) {
                            // read bytes from input buffer
                            bytes = mmInStream.read(buffer);
                            String readMessage = new String(buffer, 0, bytes);
                            // Send the obtained bytes to the UI Activity via handler
                            bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
                        }
                    } catch (IOException e) {
                    }
                }
            }
        }

        // write method
        public void write(String input) {
            if (Constants.ENABLE_BLUETOOTH) {
                // converts entered String into bytes
                byte[] msgBuffer = input.getBytes();
                try {
                    // write bytes over BT connection via outstream
                    mmOutStream.write(msgBuffer);
                } catch (IOException e) {
                // Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
                // finish();
                }
            }
        }

        void Sleep(long ms) {
            try {
                Thread.sleep(ms);
            } catch (Exception e) {
            }
        }
    }
}

15 Source : DeviceListActivity.java
with GNU General Public License v3.0
from rrrlasse

public clreplaced DeviceListActivity extends Activity implements LocationListener {

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onLocationChanged(android.location.Location location) {
    }

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

    @Override
    public void onProviderEnabled(String provider) {
    }

    // Debugging for LOGCAT
    private static final String TAG = "DeviceListActivity";

    private static final boolean D = true;

    // declare button for launching website and textview for connection status
    Button tlbutton;

    TextView textView1;

    private TimerTask timerTask;

    // EXTRA string to send on to mainactivity
    public static String EXTRA_DEVICE_ADDRESS = "device_address";

    // Member fields
    private BluetoothAdapter mBtAdapter;

    private ArrayAdapter<String> mPairedDevicesArrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.device_list);
    }

    @Override
    public void onResume() {
        super.onResume();
        // ***************
        checkBTState();
        // Activate GPS
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, this);
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        bestProvider = locationManager.getBestProvider(criteria, true);
        textView1 = (TextView) findViewById(R.id.connecting);
        textView1.setTextSize(40);
        textView1.setText(" ");
        // Initialize array adapter for paired devices
        mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
        // Find and set up the ListView for paired devices
        ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
        pairedListView.setAdapter(mPairedDevicesArrayAdapter);
        pairedListView.setOnItemClickListener(mDeviceClickListener);
        // Get the local Bluetooth adapter
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        if (Constants.ENABLE_BLUETOOTH) {
            // Get a set of currently paired devices and append to 'pairedDevices'
            Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
            // Add previosuly paired devices to the array
            if (pairedDevices.size() > 0) {
                // make replacedle viewable
                findViewById(R.id.replacedle_paired_devices).setVisibility(View.VISIBLE);
                for (BluetoothDevice device : pairedDevices) {
                    mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                }
            } else {
                String noDevices = getResources().getText(R.string.none_paired).toString();
                mPairedDevicesArrayAdapter.add(noDevices);
            }
        }
        if (!Constants.ENABLE_BLUETOOTH) {
            Intent i = new Intent(DeviceListActivity.this, MainActivity.clreplaced);
            startActivity(i);
        }
        timerTask = new TimerTask() {

            @Override
            public void run() {
                TextView tv = (TextView) findViewById(R.id.precision);
                if (tv != null) {
                    Location location = locationManager.getLastKnownLocation(bestProvider);
                    if (location == null) {
                        setText(tv, "GPS precision: Finding satelites...");
                    } else {
                        float f = location.getAccuracy();
                        setText(tv, "GPS precision: " + Integer.toString((int) f) + " m");
                    }
                }
            }
        };
        timer = new Timer();
        timer.scheduleAtFixedRate(timerTask, 0, 2000);
    }

    public void onPause() {
        locationManager.removeUpdates(this);
        super.onPause();
    }

    // Set up on-click listener for the list (nicked this - unsure)
    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {

        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
            timer.cancel();
            textView1.setText("Connecting...");
            // Get the device MAC address, which is the last 17 chars in the View
            String info = ((TextView) v).getText().toString();
            String address = info.substring(info.length() - 17);
            // Make an intent to start next activity while taking an extra which is the MAC address.
            Intent i = new Intent(DeviceListActivity.this, MainActivity.clreplaced);
            i.putExtra(EXTRA_DEVICE_ADDRESS, address);
            startActivity(i);
        }
    };

    private void checkBTState() {
        // Check device has Bluetooth and that it is turned on
        // CHECK THIS OUT THAT IT WORKS!!!
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBtAdapter == null) {
            Toast.makeText(getBaseContext(), "Device does not support Bluetooth", Toast.LENGTH_SHORT).show();
        } else {
            if (mBtAdapter.isEnabled()) {
                Log.d(TAG, "...Bluetooth ON...");
            } else {
                // Prompt user to turn on Bluetooth
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 1);
            }
        }
    }

    LocationManager locationManager;

    Criteria criteria = new Criteria();

    String bestProvider;

    private Timer timer = new Timer();

    private void setText(final TextView text, final String value) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                text.setText(value);
            }
        });
    }
}

14 Source : Util.java
with Apache License 2.0
from JackChan1999

public static String getLocation(Context context) {
    if (context == null) {
        return "";
    }
    try {
        LocationManager locationManager = (LocationManager) context.getSystemService(HOME_RECOMMEND_PARAMETERS.LOCATION);
        Criteria criteria = new Criteria();
        criteria.setCostAllowed(false);
        criteria.setAccuracy(2);
        String bestProvider = locationManager.getBestProvider(criteria, true);
        if (bestProvider != null) {
            Location lastKnownLocation = locationManager.getLastKnownLocation(bestProvider);
            if (lastKnownLocation == null) {
                return "";
            }
            double lareplacedude = lastKnownLocation.getLareplacedude();
            g = lareplacedude + "*" + lastKnownLocation.getLongitude();
            return g;
        }
    } catch (Throwable e) {
        f.b("getLocation", "getLocation>>>", e);
    }
    return "";
}

14 Source : LocationSensor.java
with GNU General Public License v2.0
from Cloudslab

@DesignerComponent(category = ComponentCategory.SENSORS, description = "Non-visible component providing location information, including longitude, lareplacedude, alreplacedude (if supported by the device), speed (if supported by the device), and address.  This can also perform \"geocoding\", converting a given address (not necessarily the current one) to a lareplacedude (with the <code>LareplacedudeFromAddress</code> method) and a longitude (with the <code>LongitudeFromAddress</code> method).</p>\n<p>In order to function, the component must have its <code>Enabled</code> property set to True, and the device must have location sensing enabled through wireless networks or GPS satellites (if outdoors).</p>\nLocation information might not be immediately available when an app starts.  You'll have to wait a short time for a location provider to be found and used, or wait for the OnLocationChanged event", iconName = "images/locationSensor.png", nonVisible = true, version = 3)
@SimpleObject
@UsesPermissions(permissionNames = "android.permission.ACCESS_FINE_LOCATION,android.permission.ACCESS_COARSE_LOCATION,android.permission.ACCESS_MOCK_LOCATION,android.permission.ACCESS_LOCATION_EXTRA_COMMANDS")
public clreplaced LocationSensor extends AndroidNonvisibleComponent implements Component, OnStopListener, OnResumeListener, Deleteable {

    public static final int UNKNOWN_VALUE = 0;

    private List<String> allProviders;

    private double alreplacedude;

    private final Handler androidUIHandler;

    private int distanceInterval;

    private boolean enabled;

    private Geocoder geocoder;

    private final Handler handler;

    private boolean hasAlreplacedude;

    private boolean hasLocationData;

    private Location lastLocation;

    private double lareplacedude;

    private final Set<LocationSensorListener> listeners;

    private boolean listening;

    private final Criteria locationCriteria;

    private final LocationManager locationManager;

    private LocationProvider locationProvider;

    private double longitude;

    private MyLocationListener myLocationListener;

    private boolean providerLocked;

    private String providerName;

    private float speed;

    private int timeInterval;

    public interface LocationSensorListener extends LocationListener {

        void onDistanceIntervalChanged(int i);

        void onTimeIntervalChanged(int i);

        void setSource(LocationSensor locationSensor);
    }

    private clreplaced MyLocationListener implements LocationListener {

        private MyLocationListener() {
        }

        public void onLocationChanged(Location location) {
            LocationSensor.this.lastLocation = location;
            LocationSensor.this.longitude = location.getLongitude();
            LocationSensor.this.lareplacedude = location.getLareplacedude();
            LocationSensor.this.speed = location.getSpeed();
            if (location.hasAlreplacedude()) {
                LocationSensor.this.hasAlreplacedude = true;
                LocationSensor.this.alreplacedude = location.getAlreplacedude();
            }
            if (LocationSensor.this.longitude != 0.0d || LocationSensor.this.lareplacedude != 0.0d) {
                LocationSensor.this.hasLocationData = true;
                final double argLareplacedude = LocationSensor.this.lareplacedude;
                final double argLongitude = LocationSensor.this.longitude;
                final double argAlreplacedude = LocationSensor.this.alreplacedude;
                final float argSpeed = LocationSensor.this.speed;
                final Location location2 = location;
                LocationSensor.this.androidUIHandler.post(new Runnable() {

                    public void run() {
                        LocationSensor.this.LocationChanged(argLareplacedude, argLongitude, argAlreplacedude, argSpeed);
                        for (LocationSensorListener listener : LocationSensor.this.listeners) {
                            listener.onLocationChanged(location2);
                        }
                    }
                });
            }
        }

        public void onProviderDisabled(String provider) {
            LocationSensor.this.StatusChanged(provider, "Disabled");
            LocationSensor.this.stopListening();
            if (LocationSensor.this.enabled) {
                LocationSensor.this.RefreshProvider();
            }
        }

        public void onProviderEnabled(String provider) {
            LocationSensor.this.StatusChanged(provider, "Enabled");
            LocationSensor.this.RefreshProvider();
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
            switch(status) {
                case 0:
                    LocationSensor.this.StatusChanged(provider, "OUT_OF_SERVICE");
                    if (provider.equals(LocationSensor.this.providerName)) {
                        LocationSensor.this.stopListening();
                        LocationSensor.this.RefreshProvider();
                        return;
                    }
                    return;
                case 1:
                    LocationSensor.this.StatusChanged(provider, "TEMPORARILY_UNAVAILABLE");
                    return;
                case 2:
                    LocationSensor.this.StatusChanged(provider, "AVAILABLE");
                    if (!provider.equals(LocationSensor.this.providerName) && !LocationSensor.this.allProviders.contains(provider)) {
                        LocationSensor.this.RefreshProvider();
                        return;
                    }
                    return;
                default:
                    return;
            }
        }
    }

    public LocationSensor(ComponentContainer container) {
        this(container, true);
    }

    public LocationSensor(ComponentContainer container, boolean enabled) {
        super(container.$form());
        this.listeners = new HashSet();
        this.providerLocked = false;
        this.listening = false;
        this.longitude = 0.0d;
        this.lareplacedude = 0.0d;
        this.alreplacedude = 0.0d;
        this.speed = 0.0f;
        this.hasLocationData = false;
        this.hasAlreplacedude = false;
        this.androidUIHandler = new Handler();
        this.enabled = true;
        this.enabled = enabled;
        this.handler = new Handler();
        this.form.registerForOnResume(this);
        this.form.registerForOnStop(this);
        this.timeInterval = 60000;
        this.distanceInterval = 5;
        Context context = container.$context();
        this.geocoder = new Geocoder(context);
        this.locationManager = (LocationManager) context.getSystemService("location");
        this.locationCriteria = new Criteria();
        this.myLocationListener = new MyLocationListener();
        this.allProviders = new ArrayList();
        Enabled(enabled);
    }

    @SimpleEvent
    public void LocationChanged(double lareplacedude, double longitude, double alreplacedude, float speed) {
        EventDispatcher.dispatchEvent(this, "LocationChanged", Double.valueOf(lareplacedude), Double.valueOf(longitude), Double.valueOf(alreplacedude), Float.valueOf(speed));
    }

    @SimpleEvent
    public void StatusChanged(String provider, String status) {
        if (this.enabled) {
            EventDispatcher.dispatchEvent(this, "StatusChanged", provider, status);
        }
    }

    @SimpleProperty(category = PropertyCategory.BEHAVIOR)
    public String ProviderName() {
        if (this.providerName == null) {
            return "NO PROVIDER";
        }
        return this.providerName;
    }

    @SimpleProperty
    public void ProviderName(String providerName) {
        this.providerName = providerName;
        if (empty(providerName) || !startProvider(providerName)) {
            RefreshProvider();
        }
    }

    @SimpleProperty(category = PropertyCategory.BEHAVIOR)
    public boolean ProviderLocked() {
        return this.providerLocked;
    }

    @SimpleProperty
    public void ProviderLocked(boolean lock) {
        this.providerLocked = lock;
    }

    @DesignerProperty(defaultValue = "60000", editorType = "sensor_time_interval")
    @SimpleProperty
    public void TimeInterval(int interval) {
        if (interval >= 0 && interval <= 1000000) {
            this.timeInterval = interval;
            if (this.enabled) {
                RefreshProvider();
            }
            for (LocationSensorListener listener : this.listeners) {
                listener.onTimeIntervalChanged(this.timeInterval);
            }
        }
    }

    @SimpleProperty(category = PropertyCategory.BEHAVIOR, description = "Determines the minimum time interval, in milliseconds, that the sensor will try to use for sending out location updates. However, location updates will only be received when the location of the phone actually changes, and use of the specified time interval is not guaranteed. For example, if 1000 is used as the time interval, location updates will never be fired sooner than 1000ms, but they may be fired anytime after.")
    public int TimeInterval() {
        return this.timeInterval;
    }

    @DesignerProperty(defaultValue = "5", editorType = "sensor_dist_interval")
    @SimpleProperty
    public void DistanceInterval(int interval) {
        if (interval >= 0 && interval <= 1000) {
            this.distanceInterval = interval;
            if (this.enabled) {
                RefreshProvider();
            }
            for (LocationSensorListener listener : this.listeners) {
                listener.onDistanceIntervalChanged(this.distanceInterval);
            }
        }
    }

    @SimpleProperty(category = PropertyCategory.BEHAVIOR, description = "Determines the minimum distance interval, in meters, that the sensor will try to use for sending out location updates. For example, if this is set to 5, then the sensor will fire a LocationChanged event only after 5 meters have been traversed. However, the sensor does not guarantee that an update will be received at exactly the distance interval. It may take more than 5 meters to fire an event, for instance.")
    public int DistanceInterval() {
        return this.distanceInterval;
    }

    @SimpleProperty(category = PropertyCategory.BEHAVIOR)
    public boolean HasLongitudeLareplacedude() {
        return this.hasLocationData && this.enabled;
    }

    @SimpleProperty(category = PropertyCategory.BEHAVIOR)
    public boolean HasAlreplacedude() {
        return this.hasAlreplacedude && this.enabled;
    }

    @SimpleProperty(category = PropertyCategory.BEHAVIOR)
    public boolean HasAccuracy() {
        return Accuracy() != 0.0d && this.enabled;
    }

    @SimpleProperty(category = PropertyCategory.BEHAVIOR)
    public double Longitude() {
        return this.longitude;
    }

    @SimpleProperty(category = PropertyCategory.BEHAVIOR)
    public double Lareplacedude() {
        return this.lareplacedude;
    }

    @SimpleProperty(category = PropertyCategory.BEHAVIOR)
    public double Alreplacedude() {
        return this.alreplacedude;
    }

    @SimpleProperty(category = PropertyCategory.BEHAVIOR)
    public double Accuracy() {
        if (this.lastLocation != null && this.lastLocation.hasAccuracy()) {
            return (double) this.lastLocation.getAccuracy();
        }
        if (this.locationProvider != null) {
            return (double) this.locationProvider.getAccuracy();
        }
        return 0.0d;
    }

    @SimpleProperty(category = PropertyCategory.BEHAVIOR)
    public boolean Enabled() {
        return this.enabled;
    }

    @DesignerProperty(defaultValue = "True", editorType = "boolean")
    @SimpleProperty
    public void Enabled(boolean enabled) {
        this.enabled = enabled;
        if (enabled) {
            RefreshProvider();
        } else {
            stopListening();
        }
    }

    @SimpleProperty(category = PropertyCategory.BEHAVIOR)
    public String CurrentAddress() {
        if ((this.hasLocationData && this.lareplacedude <= 90.0d && this.lareplacedude >= -90.0d && this.longitude <= 180.0d) || this.longitude >= -180.0d) {
            try {
                List<Address> addresses = this.geocoder.getFromLocation(this.lareplacedude, this.longitude, 1);
                if (addresses != null && addresses.size() == 1) {
                    Address address = (Address) addresses.get(0);
                    if (address != null) {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
                            sb.append(address.getAddressLine(i));
                            sb.append("\n");
                        }
                        return sb.toString();
                    }
                }
            } catch (Exception e) {
                if ((e instanceof IllegalArgumentException) || (e instanceof IOException) || (e instanceof IndexOutOfBoundsException)) {
                    Log.e("LocationSensor", "Exception thrown by getting current address " + e.getMessage());
                } else {
                    Log.e("LocationSensor", "Unexpected exception thrown by getting current address " + e.getMessage());
                }
            }
        }
        return "No address available";
    }

    @SimpleFunction(description = "Derives lareplacedude of given address")
    public double LareplacedudeFromAddress(String locationName) {
        try {
            List<Address> addressObjs = this.geocoder.getFromLocationName(locationName, 1);
            Log.i("LocationSensor", "lareplacedude addressObjs size is " + addressObjs.size() + " for " + locationName);
            if (addressObjs != null && addressObjs.size() != 0) {
                return ((Address) addressObjs.get(0)).getLareplacedude();
            }
            throw new IOException("");
        } catch (IOException e) {
            this.form.dispatchErrorOccurredEvent(this, "LareplacedudeFromAddress", 101, locationName);
            return 0.0d;
        }
    }

    @SimpleFunction(description = "Derives longitude of given address")
    public double LongitudeFromAddress(String locationName) {
        try {
            List<Address> addressObjs = this.geocoder.getFromLocationName(locationName, 1);
            Log.i("LocationSensor", "longitude addressObjs size is " + addressObjs.size() + " for " + locationName);
            if (addressObjs != null && addressObjs.size() != 0) {
                return ((Address) addressObjs.get(0)).getLongitude();
            }
            throw new IOException("");
        } catch (IOException e) {
            this.form.dispatchErrorOccurredEvent(this, "LongitudeFromAddress", 102, locationName);
            return 0.0d;
        }
    }

    @SimpleProperty(category = PropertyCategory.BEHAVIOR)
    public List<String> AvailableProviders() {
        return this.allProviders;
    }

    public void RefreshProvider() {
        stopListening();
        if (!this.providerLocked || empty(this.providerName)) {
            this.allProviders = this.locationManager.getProviders(true);
            String bProviderName = this.locationManager.getBestProvider(this.locationCriteria, true);
            if (!(bProviderName == null || bProviderName.equals(this.allProviders.get(0)))) {
                this.allProviders.add(0, bProviderName);
            }
            for (String providerN : this.allProviders) {
                this.listening = startProvider(providerN);
                if (this.listening) {
                    if (!this.providerLocked) {
                        this.providerName = providerN;
                        return;
                    }
                    return;
                }
            }
            return;
        }
        this.listening = startProvider(this.providerName);
    }

    private boolean startProvider(String providerName) {
        this.providerName = providerName;
        LocationProvider tLocationProvider = this.locationManager.getProvider(providerName);
        if (tLocationProvider == null) {
            Log.d("LocationSensor", "getProvider(" + providerName + ") returned null");
            return false;
        }
        stopListening();
        this.locationProvider = tLocationProvider;
        this.locationManager.requestLocationUpdates(providerName, (long) this.timeInterval, (float) this.distanceInterval, this.myLocationListener);
        this.listening = true;
        return true;
    }

    private void stopListening() {
        if (this.listening) {
            this.locationManager.removeUpdates(this.myLocationListener);
            this.locationProvider = null;
            this.listening = false;
        }
    }

    public void onResume() {
        if (this.enabled) {
            RefreshProvider();
        }
    }

    public void onStop() {
        stopListening();
    }

    public void onDelete() {
        stopListening();
    }

    public void addListener(LocationSensorListener listener) {
        listener.setSource(this);
        this.listeners.add(listener);
    }

    public void removeListener(LocationSensorListener listener) {
        this.listeners.remove(listener);
        listener.setSource(null);
    }

    private boolean empty(String s) {
        return s == null || s.length() == 0;
    }
}

See More Examples