Example usage for android.location LocationManager NETWORK_PROVIDER

List of usage examples for android.location LocationManager NETWORK_PROVIDER

Introduction

In this page you can find the example usage for android.location LocationManager NETWORK_PROVIDER.

Prototype

String NETWORK_PROVIDER

To view the source code for android.location LocationManager NETWORK_PROVIDER.

Click Source Link

Document

Name of the network location provider.

Usage

From source file:com.barak.pix.NewPostActivity.java

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {

    case 11:/*from w  ww . j a  v a 2  s. c  om*/
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            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 documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10,
                    locationListener);

        } else {

            Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access location data.",
                    Toast.LENGTH_LONG).show();

        }
        break;

    }
}

From source file:com.alibaba.weex.extend.module.location.DefaultLocation.java

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);
    }//from w  w  w  .j a va 2 s . c  o m
    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;
}

From source file:com.nextgis.firereporter.GetFiresService.java

protected void GetNasaData(boolean bShowProgress) {
    Location currentLocation = null;
    String sLat = null, sLon = null;

    if (mLocManager != null) {
        currentLocation = mLocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (currentLocation == null) {
            currentLocation = mLocManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }//from  w w w  .  ja  va  2  s  .com

        if (currentLocation == null) {
            SendError(getString(R.string.noLocation));
            return;
        } else {
            sLat = Double.toString(currentLocation.getLatitude());
            sLon = Double.toString(currentLocation.getLongitude());
        }
    }

    SharedPreferences prefs = getSharedPreferences(MainActivity.PREFERENCES, MODE_PRIVATE | MODE_MULTI_PROCESS);
    String sURL = prefs.getString(SettingsActivity.KEY_PREF_SRV_NASA,
            getResources().getString(R.string.stDefaultServer));
    String sLogin = prefs.getString(SettingsActivity.KEY_PREF_SRV_NASA_USER, "fire_usr");
    String sPass = prefs.getString(SettingsActivity.KEY_PREF_SRV_NASA_PASS, "J59DY");
    int nDayInterval = prefs.getInt(SettingsActivity.KEY_PREF_SEARCH_DAY_INTERVAL + "_int", 5);
    int fetchRows = prefs.getInt(SettingsActivity.KEY_PREF_ROW_COUNT + "_int", 15);
    int searchRadius = prefs.getInt(SettingsActivity.KEY_PREF_FIRE_SEARCH_RADIUS + "_int", 5) * 1000;//meters
    boolean searchByDate = prefs.getBoolean(SettingsActivity.KEY_PREF_SEARCH_CURR_DAY, false);

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date date = new Date();
    long diff = 86400000L * nDayInterval;//1000 * 60 * 60 * 24 * 5;// 5 days  
    date.setTime(date.getTime() - diff);
    String dt = dateFormat.format(date);

    String sFullURL = sURL + "?function=get_rows_nasa&user=" + sLogin + "&pass=" + sPass + "&limit=" + fetchRows
            + "&radius=" + searchRadius;//
    if (searchByDate) {
        sFullURL += "&date=" + dt;
    }
    if (sLat.length() > 0 && sLon.length() > 0) {
        sFullURL += "&lat=" + sLat + "&lon=" + sLon;
    }

    //String sRemoteData = "http://gis-lab.info/data/zp-gis/soft/fires.php?function=get_rows_nasa&user=fire_usr&pass=J59DY&limit=5";
    //if(!oNasa.getStatus().equals(AsyncTask.Status.RUNNING) && !oNasa.getStatus().equals(AsyncTask.Status.PENDING))
    new HttpGetter(this, 2, getResources().getString(R.string.stDownLoading), mFillDataHandler, bShowProgress)
            .execute(sFullURL);
}

From source file:uk.org.rivernile.edinburghbustracker.android.fragments.general.BusStopDetailsFragment.java

/**
 * {@inheritDoc}//from w w w .jav  a 2  s.  c  o m
 */
@Override
public void onProviderEnabled(final String provider) {
    if (LocationManager.GPS_PROVIDER.equals(provider) || LocationManager.NETWORK_PROVIDER.equals(provider)) {
        locMan.requestLocationUpdates(provider, REQUEST_PERIOD, MIN_DISTANCE, this);
    }
}

From source file:com.qi.airstat.BluetoothLeService.java

/**
 * Connects to the GATT server hosted on the Bluetooth LE device.
 *
 * @param address The device address of the destination device.
 *
 * @return Return true if the connection is initiated successfully. The connection result
 *         is reported asynchronously through the
 *         {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
 *         callback./*from   w ww .j  a  v a2s . com*/
 */
public boolean connect(final String address) {
    if (mBluetoothAdapter == null || address == null) {
        Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
        BluetoothState.isBLEConnected(false);
        return false;
    }

    // Previously connected device.  Try to reconnect.
    if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) {
        Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
        if (mBluetoothGatt.connect()) {
            mConnectionState = STATE_CONNECTING;
            return true;
        } else {
            BluetoothState.isBLEConnected(false);
            return false;
        }
    }

    final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    if (device == null) {
        Log.w(TAG, "Device not found.  Unable to connect.");
        BluetoothState.isBLEConnected(false);
        return false;
    }
    // We want to directly connect to the device, so we are setting the autoConnect
    // parameter to false.
    mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
    Log.d(TAG, "Trying to create a new connection.");
    mBluetoothDeviceAddress = address;
    mConnectionState = STATE_CONNECTING;
    Constants.MAC_POLAR = mBluetoothDeviceAddress;

    try {
        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        latitude = location.getLatitude();
        longitude = location.getLongitude();
    } catch (SecurityException exception) {
        exception.printStackTrace();
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("userID", Constants.UID);
        jsonObject.put("conCreationTime", new SimpleDateFormat("yyMMddHHmmss").format(new java.util.Date()));
        jsonObject.put("flagValidCon", 1);
        jsonObject.put("devMAC", "x'" + Constants.MAC_POLAR.replaceAll(":", "") + "'");
        jsonObject.put("devType", Constants.DEVICE_TYPE_POLAR);
        jsonObject.put("devPortability", 0x01);
        jsonObject.put("latitude", "x'" + latitude);
        jsonObject.put("longitude", "x'" + longitude);
    } catch (JSONException exception) {
        exception.printStackTrace();
    }

    HttpService httpService = new HttpService();
    String res = httpService.executeConn(null, "POST", "http://teamc-iot.calit2.net/IOT/public/deviceReg",
            jsonObject);

    try {
        JSONObject resJson;
        resJson = new JSONObject(res);
        Log.d("BLEService", "DevReg sent, response was " + res);

        if (resJson.getInt("status") == 0) {
            return true;
        } else {
            mConnectionState = STATE_DISCONNECTED;
            Constants.MAC_POLAR = null;
            BluetoothState.isBLEConnected(false);
            return false;
        }
    } catch (JSONException exception) {
        exception.printStackTrace();
        return false;
    }
}

From source file:com.waz.zclient.pages.main.conversation.LocationFragment.java

private boolean isLocationServicesEnabled() {
    if (!PermissionUtils.hasSelfPermissions(getContext(), LOCATION_PERMISSIONS)) {
        return false;
    }//from  w ww  .  j ava 2s .c o m
    // We are creating a local locationManager here, as it's not sure we already have one
    LocationManager locationManager = (LocationManager) getActivity()
            .getSystemService(Context.LOCATION_SERVICE);
    if (locationManager == null) {
        return false;
    }
    boolean gpsEnabled;
    boolean netEnabled;

    try {
        gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception e) {
        gpsEnabled = false;
    }

    try {
        netEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception e) {
        netEnabled = false;
    }
    return netEnabled || gpsEnabled;
}

From source file:li.barter.fragments.BooksAroundMeFragment.java

/**
 * Reads the latest fetched locations from shared preferences
 *//*from  ww  w  .ja  v a 2s . c  om*/
private void readLastFetchedInfoFromPref() {

    // Don't read from pref if already has fetched
    if (mLastFetchedLocation == null) {
        mLastFetchedLocation = new Location(LocationManager.PASSIVE_PROVIDER);
        Logger.d(TAG, mLastFetchedLocation.getLatitude() + "");
        if (mLastFetchedLocation == null) {
            mLastFetchedLocation = new Location(LocationManager.NETWORK_PROVIDER);
            Logger.d(TAG, mLastFetchedLocation.getLatitude() + "");
        }
        mLastFetchedLocation.setLatitude(SharedPreferenceHelper.getDouble(R.string.pref_last_fetched_latitude));
        mLastFetchedLocation
                .setLongitude(SharedPreferenceHelper.getDouble(R.string.pref_last_fetched_longitude));
    }

}

From source file:com.appsimobile.appsii.module.weather.WeatherLoadingService.java

@Nullable
@RequiresPermission(anyOf = { ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION })
private Location requestLocationInfoBlocking() throws InterruptedException {

    List<String> providers = mLocationManager.getAllProviders();

    if (!providers.contains(LocationManager.NETWORK_PROVIDER))
        return null;
    if (!mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
        return null;

    SimpleLocationListener listener = new SimpleLocationListener(mLocationManager);

    mLocationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, listener, Looper.getMainLooper());

    Location result = listener.waitForResult();
    if (result == null) {
        result = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }//from w ww  .j  a  v  a 2  s  .c o m
    if (BuildConfig.DEBUG)
        Log.d("WeatherLoadingService", "location: " + result);
    return result;
}

From source file:com.umaps.gpslogger.GpsLoggingService.java

/**
 * Starts the location manager. There are two location managers - GPS and
 * Cell Tower. This code determines which manager to request updates from
 * based on user preference and whichever is enabled. If GPS is enabled on
 * the phone, that is used. But if the user has also specified that they
 * prefer cell towers, then cell towers are used. If neither is enabled,
 * then nothing is requested./*from   w  w w . j  av a 2s.c o m*/
 */
private void StartGpsManager() {

    GetPreferences();

    //If the user has been still for more than the minimum seconds
    if (userHasBeenStillForTooLong()) {
        Log.i(TAG, "No movement detected in the past interval, will not log");
        SetAlarmForNextPoint();
        return;
    }

    if (gpsLocationListener == null) {
        gpsLocationListener = new GeneralLocationListener(this, "GPS");
    }

    if (towerLocationListener == null) {
        towerLocationListener = new GeneralLocationListener(this, "CELL");
    }

    gpsLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    towerLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    CheckTowerAndGpsStatus();

    if (Session.isGpsEnabled() && AppSettings.getChosenListeners().contains("gps")) {
        Log.i(TAG, "Requesting GPS location updates");
        // gps satellite based
        gpsLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, gpsLocationListener);
        gpsLocationManager.addGpsStatusListener(gpsLocationListener);

        Session.setUsingGps(true);
        startAbsoluteTimer();
    }

    if (Session.isTowerEnabled()
            && (AppSettings.getChosenListeners().contains("network") || !Session.isGpsEnabled())) {
        Log.i(TAG, "Requesting cell and wifi location updates");
        Session.setUsingGps(false);
        // Cell tower and wifi based
        towerLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0,
                towerLocationListener);

        startAbsoluteTimer();
    }

    if (!Session.isTowerEnabled() && !Session.isGpsEnabled()) {
        Log.e(TAG, "No provider available!");
        Session.setUsingGps(false);
        Log.e(TAG, getString(R.string.gpsprovider_unavailable));
        StopLogging();
        SetLocationServiceUnavailable();
        return;
    }

    EventBus.getDefault().post(new ServiceEvents.WaitingForLocation(true));
    Session.setWaitingForLocation(true);
}

From source file:org.y20k.trackbook.MainActivityMapFragment.java

private void startPreliminaryTracking() {
    if (mLocationSystemSetting && !mLocalTrackerRunning) {
        // create location listeners
        List locationProviders = mLocationManager.getAllProviders();
        if (locationProviders.contains(LocationManager.GPS_PROVIDER)) {
            mGPSListener = createLocationListener();
            mLocalTrackerRunning = true;
        }/*from  w  w  w. jav a  2  s  .  c  o  m*/
        if (locationProviders.contains(LocationManager.NETWORK_PROVIDER)) {
            mNetworkListener = createLocationListener();
            mLocalTrackerRunning = true;
        }
        // register listeners
        LocationHelper.registerLocationListeners(mLocationManager, mGPSListener, mNetworkListener);
        LogHelper.v(LOG_TAG, "Starting preliminary tracking.");
    }
}