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.platform.middlewares.plugins.GeoLocationPlugin.java

private JSONObject getAuthorizationError(Context app) {
    String error = null;//w ww. j av a 2s.  c om

    LocationManager lm = (LocationManager) app.getSystemService(Context.LOCATION_SERVICE);
    boolean gps_enabled = false;
    boolean network_enabled = false;

    try {
        gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ignored) {
    }

    try {
        network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ignored) {
    }
    if (!gps_enabled && !network_enabled) {
        error = "Location services are disabled";
    }
    int permissionCheck = ContextCompat.checkSelfPermission(app, Manifest.permission.ACCESS_FINE_LOCATION);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        error = "Location services are not authorized";
    }

    if (error != null) {
        JSONObject obj = new JSONObject();
        try {
            obj.put("error", error);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    } else {
        return null;
    }

}

From source file:com.ibm.mf.geofence.MFGeofencingManager.java

/**
 * Add the specified geofences to the monitored geofences.
 * @param geofences the geofences to add.
 *///from  w  ww. j  a v  a2s .c  om
void monitorGeofences(List<PersistentGeofence> geofences) {
    if (!geofences.isEmpty()) {
        log.debug("monitorGeofences(" + geofences + ")");
        List<Geofence> list = new ArrayList<>(geofences.size());
        List<Geofence> noTriggerList = new ArrayList<>(geofences.size());
        Location last = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        for (PersistentGeofence geofence : geofences) {
            Geofence fence = new Geofence.Builder().setRequestId(geofence.getCode())
                    .setCircularRegion(geofence.getLatitude(), geofence.getLongitude(),
                            (float) geofence.getRadius())
                    .setExpirationDuration(Geofence.NEVER_EXPIRE).setNotificationResponsiveness(10_000)
                    .setLoiteringDelay(300000)
                    .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                    .build();

            Location location = new Location(LocationManager.NETWORK_PROVIDER);
            location.setLatitude(geofence.getLatitude());
            location.setLongitude(geofence.getLongitude());
            if ((mMode != MODE_REBOOT) || (last == null)
                    || (location.distanceTo(last) > geofence.getRadius())) {
                list.add(fence);
            } else {
                // if already in geofence, do not trigger upon registration.
                noTriggerList.add(fence);
            }
        }
        registerFencesForMonitoring(list, GeofencingRequest.INITIAL_TRIGGER_ENTER);
        registerFencesForMonitoring(noTriggerList, 0);
    }
}

From source file:info.snowhow.plugin.RecorderService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i(LOG_TAG, "Received start id " + startId + ": " + intent);
    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        showNoGPSAlert();/* ww  w .  ja  v  a2 s.  co m*/
    }
    runningID = startId;
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.

    if (intent == null) {
        tf = sharedPref.getString("runningTrackFile", "");
        Log.w(LOG_TAG, "Intent is null, trying to continue to write to file " + tf + " lm " + locationManager);
        minimumPrecision = sharedPref.getFloat("runningPrecision", 0);
        distanceChange = sharedPref.getLong("runningDistanceChange", MINIMUM_DISTANCE_CHANGE_FOR_UPDATES);
        updateTime = sharedPref.getLong("runningUpdateTime", MINIMUM_TIME_BETWEEN_UPDATES);
        updateTimeFast = sharedPref.getLong("runningUpdateTimeFast", MINIMUM_TIME_BETWEEN_UPDATES_FAST);
        speedLimit = sharedPref.getLong("runningSpeedLimit", SPEED_LIMIT);
        adaptiveRecording = sharedPref.getBoolean("adaptiveRecording", false);
        int count = sharedPref.getInt("count", 0);
        if (count > 0) {
            firstPoint = false;
        }
        if (tf == null || tf == "") {
            Log.e(LOG_TAG, "No trackfile found ... exit clean here");
            cleanUp();
            return START_NOT_STICKY;
        }
    } else {
        tf = intent.getStringExtra("fileName");
        Log.d(LOG_TAG, "FILENAME for recording is " + tf);
        minimumPrecision = intent.getFloatExtra("precision", 0);
        distanceChange = intent.getLongExtra("distance_change", MINIMUM_DISTANCE_CHANGE_FOR_UPDATES);
        updateTime = intent.getLongExtra("update_time", MINIMUM_TIME_BETWEEN_UPDATES);
        updateTimeFast = intent.getLongExtra("update_time_fast", MINIMUM_TIME_BETWEEN_UPDATES_FAST);
        speedLimit = intent.getLongExtra("speed_limit", SPEED_LIMIT);
        adaptiveRecording = intent.getBooleanExtra("adaptiveRecording", false);
        editor.putString("runningTrackFile", tf);
        editor.putFloat("runningPrecision", minimumPrecision);
        editor.putLong("runningDistanceChange", distanceChange);
        editor.putLong("runningUpdateTime", updateTime);
        editor.putLong("runningUpdateTimeFast", updateTimeFast);
        editor.putLong("runningSpeedLimit", speedLimit);
        editor.putBoolean("adaptiveRecording", adaptiveRecording);
        editor.commit();
    }

    Intent cordovaMainIntent;
    try {
        PackageManager packageManager = this.getPackageManager();
        cordovaMainIntent = packageManager.getLaunchIntentForPackage(this.getPackageName());
        Log.d(LOG_TAG, "got cordovaMainIntent " + cordovaMainIntent);
        if (cordovaMainIntent == null) {
            throw new PackageManager.NameNotFoundException();
        }
    } catch (PackageManager.NameNotFoundException e) {
        cordovaMainIntent = new Intent();
    }
    PendingIntent pend = PendingIntent.getActivity(this, 0, cordovaMainIntent, 0);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ifString), 0);
    NotificationCompat.Action stop = new NotificationCompat.Action.Builder(android.R.drawable.ic_delete,
            "Stop recording", pendingIntent).build();
    note = new NotificationCompat.Builder(this).setContentTitle(applicationName + " GPS tracking")
            .setSmallIcon(android.R.drawable.ic_menu_mylocation).setOngoing(true).setContentIntent(pend)
            .setContentText("No location yet.");
    note.addAction(stop);

    nm = (NotificationManager) getSystemService(Activity.NOTIFICATION_SERVICE);
    nm.notify(0, note.build());

    recording = true;
    Log.d(LOG_TAG, "recording in handleIntent");
    try { // create directory first, if it does not exist
        File trackFile = new File(tf).getParentFile();
        if (!trackFile.exists()) {
            trackFile.mkdirs();
            Log.d(LOG_TAG, "done creating path for trackfile: " + trackFile);
        }
        Log.d(LOG_TAG, "going to create RandomAccessFile " + tf);
        myWriter = new RandomAccessFile(tf, "rw");
        if (intent != null) { // start new file
            // myWriter.setLength(0);    // delete all contents from file
            String trackName = intent.getStringExtra("trackName");
            String trackHead = initTrack(trackName).toString();
            myWriter.write(trackHead.getBytes());
            // we want to write JSON manually for streamed writing
            myWriter.seek(myWriter.length() - 1);
            myWriter.write(",\"coordinates\":[]}".getBytes());
        }
    } catch (IOException e) {
        Log.d(LOG_TAG, "io error. cannot write to file " + tf);
    }
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, updateTime, distanceChange, mgpsll);
    if (locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER)) {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, updateTime, distanceChange,
                mnetll);
    }
    return START_STICKY;
}

From source file:br.com.rescue_bots_android.bluetooth.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main_blue);

    ActivityHelper.initialize(this);

    routeController = new RouteController(this);
    coordinates = new ArrayList<Path>();

    trackerController = new TrackerController(this);

    Intent intent = getIntent();//from ww  w .  j a v a  2  s  . co  m
    Bundle b = intent.getExtras();
    mDevice = b.getParcelable(Homescreen.DEVICE_EXTRA);
    mDeviceUUID = UUID.fromString(b.getString(Homescreen.DEVICE_UUID));
    mMaxChars = b.getInt(Homescreen.BUFFER_SIZE);

    Log.d(TAG, "Ready");

    mBtnDisconnect = (Button) findViewById(R.id.btnDisconnect);
    mBtnSend = (Button) findViewById(R.id.btnSend);
    mBtnClear = (Button) findViewById(R.id.btnClear);
    mTxtReceive = (TextView) findViewById(R.id.txtReceive);
    mEditSend = (EditText) findViewById(R.id.editSend);
    scrollView = (ScrollView) findViewById(R.id.viewScroll);
    chkScroll = (CheckBox) findViewById(R.id.chkScroll);
    chkReceiveText = (CheckBox) findViewById(R.id.chkReceiveText);
    checkBoxJoystickEnable = (CheckBox) findViewById(R.id.checkBoxJoystickEnable);
    mBtnClearInput = (Button) findViewById(R.id.btnClearInput);
    mBtnConfig = (Button) findViewById(R.id.buttonConfig2);
    //imageButtonClaw (Button)findViewById(R.id.imageButtonClaw);
    editTextAngle = (TextView) findViewById(R.id.editTextAngle);
    joystickView = (JoystickView) findViewById(R.id.viewJoystick);
    //Event listener that always returns the variation of the angle in degrees, motion power in percentage and direction of movement
    ibClaw = (ImageButton) findViewById(R.id.imageButtonClaw);
    clawControll = new ClawControll(ibClaw);

    joystickView.setOnJoystickMoveListener(new OnJoystickMoveListener() {

        @Override
        public void onValueChanged(int angle, int power, int direction) {
            // TODO Auto-generated method stub
            mTxtReceive.append(" " + String.valueOf(angle) + "");
            mTxtReceive.append(" " + String.valueOf(power) + "%");
            switch (direction) {
            case JoystickView.FRONT:
                mTxtReceive.append("FRONT");
                sendSerial("a");
                break;
            case JoystickView.FRONT_RIGHT:
                mTxtReceive.append("FRONT_RIGHT");
                sendSerial("c");
                break;
            case JoystickView.RIGHT:
                mTxtReceive.append("RIGHT");
                sendSerial("c");
                break;
            case JoystickView.RIGHT_BOTTOM:
                mTxtReceive.append("RIGHT_BOTTOM");
                sendSerial("f");
                break;
            case JoystickView.BOTTOM:
                mTxtReceive.append("BOTTOM");
                sendSerial("d");
                break;
            case JoystickView.BOTTOM_LEFT:
                mTxtReceive.append("BOTTOM_LEFT");
                sendSerial("e");
                break;
            case JoystickView.LEFT:
                mTxtReceive.append("LEFT");
                sendSerial("b");
                break;
            case JoystickView.LEFT_FRONT:
                mTxtReceive.append("LEFT_FRONT");
                sendSerial("b");
                break;
            default:
                mTxtReceive.append("CENTER");
                sendSerial("g");
            }
        }
    }, JoystickView.DEFAULT_LOOP_INTERVAL);

    mTxtReceive.setMovementMethod(new ScrollingMovementMethod());

    mBtnDisconnect.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            mIsUserInitiatedDisconnect = true;
            new DisConnectBT().execute();
        }
    });

    mBtnSend.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            try {
                mBTSocket.getOutputStream().write(mEditSend.getText().toString().getBytes());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

    mBtnClear.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            mEditSend.setText("");
        }
    });

    mBtnClearInput.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            //mTxtReceive.setText("");
            if (mBtnClearInput.getText().toString().equalsIgnoreCase(LocationManager.GPS_PROVIDER)) {
                mBtnClearInput.setText(LocationManager.NETWORK_PROVIDER);
                gps.setProvider(LocationManager.NETWORK_PROVIDER);
            } else {
                mBtnClearInput.setText(LocationManager.GPS_PROVIDER);
                gps.setProvider(LocationManager.GPS_PROVIDER);
            }
        }
    });
    mBtnConfig.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent i = new Intent(MainActivity.this, ConfigActivity.class);
            startActivity(i);
        }
    });

    ibClaw.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if (clawControll != null) {
                clawControll.changeState();
            }
        }
    });
    checkBoxJoystickEnable.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if (checkBoxJoystickEnable.isChecked()) {
                joystickEnabled = true;
                joystickView.setEnabled(true);
                ibClaw.setEnabled(true);
            } else {
                joystickEnabled = false;
                joystickView.setEnabled(false);
                ibClaw.setEnabled(false);
            }
        }
    });
    joystickView.setEnabled(true);
    ibClaw.setEnabled(true);

    initGPSListener();

    // initialize your android device sensor capabilities
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    image = (ImageView) findViewById(R.id.compassImg);

}

From source file:com.guidewithme.ArticleInfoListFragment.java

private Location getLocation() {
    Location loc = null;//from   www  .j  a v  a 2s .c  om

    if ((loc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)) == null)
        loc = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

    return loc;
}

From source file:net.imatruck.betterweather.BetterWeatherExtension.java

/**
 * Starts the update process, will verify the reason before continuing
 *
 * @param reason Update reason, provided by DashClock or this app
 *///from   w w w  .  j  a v  a  2s .com
@Override
protected void onUpdateData(int reason) {

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

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

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

        return;
    }

    LOGD(TAG, "Updating data");

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

    getCurrentPreferences();

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

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

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

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

    requestLocationUpdate(lm, provider);
}

From source file:com.example.android.location.BaselineActivity.java

private void setup() {

    Location gpsLocation = null;/*from   www.  jav  a2 s .  c  om*/
    Location networkLocation = null;
    mLocationManager.removeUpdates(listener);
    mLatLng.setText(R.string.unknown);
    mAddress.setText(R.string.unknown);
    // Get fine location updates only.
    if (mUseFine) {
        mFineProviderButton.setBackgroundResource(R.drawable.button_active);
        mBothProviderButton.setBackgroundResource(R.drawable.button_inactive);
        // Request updates from just the fine (gps) provider.
        gpsLocation = requestUpdatesFromProvider(LocationManager.GPS_PROVIDER, R.string.not_support_gps);
        // Update the UI immediately if a location is obtained.
        if (gpsLocation != null)
            updateUILocation(gpsLocation);
    } else if (mUseBoth) {
        // Get coarse and fine location updates.
        mFineProviderButton.setBackgroundResource(R.drawable.button_inactive);
        mBothProviderButton.setBackgroundResource(R.drawable.button_active);
        // Request updates from both fine (gps) and coarse (network) providers.
        gpsLocation = requestUpdatesFromProvider(LocationManager.GPS_PROVIDER, R.string.not_support_gps);
        networkLocation = requestUpdatesFromProvider(LocationManager.NETWORK_PROVIDER,
                R.string.not_support_network);

        // If both providers return last known locations, compare the two and use the better
        // one to update the UI.  If only one provider returns a location, use it.
        if (gpsLocation != null && networkLocation != null) {
            updateUILocation(getBetterLocation(gpsLocation, networkLocation));
        } else if (gpsLocation != null) {
            updateUILocation(gpsLocation);
        } else if (networkLocation != null) {
            updateUILocation(networkLocation);
        }
    }

}

From source file:org.nasa.openspace.gc.geolocation.LocationActivity.java

private void setup() {
    Location gpsLocation = null;/*from   w w  w. j av  a  2s  .  co m*/
    Location networkLocation = null;
    mLocationManager.removeUpdates(listener);
    mLatLng.setText(R.string.unknown);
    mAddress.setText(R.string.unknown);
    // Get fine location updates only.
    if (mUseFine) {
        //mFineProviderButton.setBackgroundResource(R.drawable.button_active);
        //mBothProviderButton.setBackgroundResource(R.drawable.button_inactive);
        // Request updates from just the fine (gps) provider.
        gpsLocation = requestUpdatesFromProvider(LocationManager.GPS_PROVIDER, R.string.not_support_gps);
        // Update the UI immediately if a location is obtained.
        if (gpsLocation != null)
            updateUILocation(gpsLocation);
    } else if (mUseBoth) {
        // Get coarse and fine location updates.
        //mFineProviderButton.setBackgroundResource(R.drawable.button_inactive);
        //mBothProviderButton.setBackgroundResource(R.drawable.button_active);
        // Request updates from both fine (gps) and coarse (network) providers.
        gpsLocation = requestUpdatesFromProvider(LocationManager.GPS_PROVIDER, R.string.not_support_gps);
        networkLocation = requestUpdatesFromProvider(LocationManager.NETWORK_PROVIDER,
                R.string.not_support_network);

        // If both providers return last known locations, compare the two and use the better
        // one to update the UI.  If only one provider returns a location, use it.
        if (gpsLocation != null && networkLocation != null) {
            updateUILocation(getBetterLocation(gpsLocation, networkLocation));
        } else if (gpsLocation != null) {
            updateUILocation(gpsLocation);
        } else if (networkLocation != null) {
            updateUILocation(networkLocation);
        }
    }
}

From source file:com.remdo.app.MainActivity.java

private Boolean isGPSorNetworkEnabled() {
    Boolean enabled = false;/* w w w. j  a v  a  2 s.  co m*/

    //Accedemos a los servicios de localizacin del sistema
    LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);

    //Obtenemos el estado del GPS y de la red
    Boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    Boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if (isGPSEnabled || isNetworkEnabled)
        enabled = true;

    return enabled;
}

From source file:cd.education.data.collector.android.activities.GeoPointMapActivity.java

@Override
protected void onResume() {
    super.onResume();
    if (mRefreshLocation) {
        mLocationStatus.setVisibility(View.VISIBLE);
        if (mGPSOn) {
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        }//from  w  w  w  . jav a  2s.c  om
        if (mNetworkOn) {
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        }
    }
}