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.layer.atlas.messenger.AtlasMessagesScreen.java

@Override
protected void onResume() {
    super.onResume();

    updateValues();//from w ww.ja va  2s.  co  m
    messagesList.jumpToLastMessage();

    // restore location tracking
    int requestLocationTimeout = 1 * 1000; // every second
    int distance = 100;
    Location loc = null;
    if (locationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
        loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (debug)
            Log.w(TAG, "onResume() location from gps: " + loc);
    }
    if (loc == null && locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
        loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (debug)
            Log.w(TAG, "onResume() location from network: " + loc);
    }
    if (loc != null && loc.getTime() < System.currentTimeMillis() + LOCATION_EXPIRATION_TIME) {
        locationTracker.onLocationChanged(loc);
    }
    if (locationManager.getProvider(LocationManager.GPS_PROVIDER) != null) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, requestLocationTimeout, distance,
                locationTracker);
    }
    if (locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, requestLocationTimeout,
                distance, locationTracker);
    }

    app.getLayerClient().registerEventListener(messagesList);
    app.getLayerClient().registerTypingIndicator(typingIndicator.clear());

    // when something changed
    app.getLayerClient().registerEventListener(new LayerChangeEventListener.MainThread() {
        public void onEventMainThread(LayerChangeEvent event) {
            updateValues();
        }
    });
}

From source file:com.landenlabs.all_devtool.GpsFragment.java

@Override
public void onLocationChanged(Location location) {

    boolean isDupLoc = false;

    try {/*www  .  j  ava2 s.com*/
        Location gpsLoc = m_locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (gpsLoc != null) {
            showGPS(gpsLoc);
            isDupLoc = isDupLoc || (location.distanceTo(gpsLoc) == 0);
        }
    } catch (Exception ex) {
        Toast.makeText(this.getActivity(), "GPS " + ex.getMessage(), Toast.LENGTH_LONG).show();
    }

    try {
        if (ActivityCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(getContext(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            Location netLoc = m_locMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (netLoc != null) {
                showGPS(netLoc);
                isDupLoc = isDupLoc || (location.distanceTo(netLoc) == 0);
            }
        }
    } catch (Exception ex) {
        Toast.makeText(this.getActivity(), "GPS needs location permission\n" + ex.getMessage(),
                Toast.LENGTH_LONG).show();
    }

    try {
        Location passiveLoc = m_locMgr.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        if (null != passiveLoc) {
            showGPS(passiveLoc);
            isDupLoc = isDupLoc || (location.distanceTo(passiveLoc) == 0);
        }
    } catch (Exception ex) {
        Toast.makeText(this.getActivity(), "Passive " + ex.getMessage(), Toast.LENGTH_LONG).show();
    }

    if (!isDupLoc)
        showGPS(location);
}

From source file:org.sipdroid.sipua.ui.Receiver.java

public static void pos(boolean enable) {

    if (!PreferenceManager.getDefaultSharedPreferences(mContext)
            .getBoolean(org.sipdroid.sipua.ui.Settings.PREF_POS, org.sipdroid.sipua.ui.Settings.DEFAULT_POS)
            || PreferenceManager.getDefaultSharedPreferences(mContext)
                    .getString(org.sipdroid.sipua.ui.Settings.PREF_POSURL,
                            org.sipdroid.sipua.ui.Settings.DEFAULT_POSURL)
                    .length() < 1) {//  w w  w .j  ava 2s  .  com
        if (lm != null && am != null) {
            pos_gps(false);
            pos_net(false);
            lm = null;
            am = null;
        }
        return;
    }

    if (lm == null)
        lm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
    if (am == null)
        am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    pos_gps(false);
    if (enable) {
        if (call_state == UserAgent.UA_STATE_IDLE && Sipdroid.on(mContext)
                && PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(
                        org.sipdroid.sipua.ui.Settings.PREF_POS, org.sipdroid.sipua.ui.Settings.DEFAULT_POS)
                && PreferenceManager.getDefaultSharedPreferences(mContext)
                        .getString(org.sipdroid.sipua.ui.Settings.PREF_POSURL,
                                org.sipdroid.sipua.ui.Settings.DEFAULT_POSURL)
                        .length() > 0) {
            Location last = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (System.currentTimeMillis() - loctrydate > GPS_UPDATES
                    && (last == null || System.currentTimeMillis() - last.getTime() > GPS_UPDATES)) {
                loctrydate = System.currentTimeMillis();
                pos_gps(true);
                pos_net(false);
            } else if (last != null)
                Receiver.url("lat=" + last.getLatitude() + "&lon=" + last.getLongitude() + "&rad="
                        + last.getAccuracy());
            pos_net(true);
        } else
            pos_net(false);
    }
}

From source file:com.geotrackin.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 a  v a2 s .c om*/
 */
private void StartGpsManager() {
    tracer.debug("GpsLoggingService.StartGpsManager");

    GetPreferences();

    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")) {
        tracer.info("Requesting GPS location updates");
        // gps satellite based
        gpsLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, gpsLocationListener);

        gpsLocationManager.addGpsStatusListener(gpsLocationListener);
        gpsLocationManager.addNmeaListener(gpsLocationListener);

        Session.setUsingGps(true);
        startAbsoluteTimer();

    }

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

        startAbsoluteTimer();

    }

    if (!Session.isTowerEnabled() && !Session.isGpsEnabled()) {
        tracer.info("No provider available");
        Session.setUsingGps(false);
        SetStatus(R.string.gpsprovider_unavailable);
        SetFatalMessage(R.string.gpsprovider_unavailable);
        StopLogging();
        return;
    }

    if (mainServiceClient != null) {
        mainServiceClient.OnWaitingForLocation(true);
        Session.setWaitingForLocation(true);
    }

    SetStatus(R.string.started);
}

From source file:com.ushahidi.android.app.ui.phone.ListMapActivity.java

/** Location stuff **/
// Fetches the current location of the device.
protected void setDeviceLocation() {
    mLocationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    // Get last known location from either GPS or Network provider
    Location loc = null;/*www  .  j  av a 2 s .  c om*/
    boolean netAvail = (mLocationMgr.getProvider(LocationManager.NETWORK_PROVIDER) != null);
    boolean gpsAvail = (mLocationMgr.getProvider(LocationManager.GPS_PROVIDER) != null);
    if (gpsAvail) {
        loc = mLocationMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    } else if (netAvail) {
        loc = mLocationMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }

    // Just use last location if it's less than 10 minutes old
    if (loc != null && ((new Date()).getTime() - loc.getTime() < 10 * 60 * 1000)) {
        onLocationChanged(loc);
    } else {
        if (gpsAvail) {
            mLocationMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        }
        if (netAvail) {
            mLocationMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        }
    }
}

From source file:com.andybotting.tubechaser.activity.StationDetail.java

/**
 * Upload stats//from   w  w w  . j  a  va2 s  . c  om
 */
private void uploadStats() {
    if (LOGV)
        Log.v(TAG, "Sending Station/Line statistics");

    // gather all of the device info
    try {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String device_uuid = tm.getDeviceId();
        String device_id = "00000000000000000000000000000000";
        if (device_uuid != null) {
            device_id = GenericUtil.MD5(device_uuid);
        }

        LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Location location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        // post the data
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://tubechaser.andybotting.com/stats/depart/send");
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();

        pairs.add(new BasicNameValuePair("device_id", device_id));
        pairs.add(new BasicNameValuePair("station_id", String.valueOf(mStation.getId())));
        pairs.add(new BasicNameValuePair("line_id", String.valueOf(mLine.getId())));

        if (location != null) {
            pairs.add(new BasicNameValuePair("latitude", String.valueOf(location.getLatitude())));
            pairs.add(new BasicNameValuePair("longitude", String.valueOf(location.getLongitude())));
            pairs.add(new BasicNameValuePair("accuracy", String.valueOf(location.getAccuracy())));
        }

        try {
            post.setEntity(new UrlEncodedFormEntity(pairs));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        try {
            HttpResponse response = client.execute(post);
            response.getStatusLine().getStatusCode();
        } catch (Exception e) {
            e.printStackTrace();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.adflake.AdFlakeManager.java

/**
 * Gets the current location.//ww  w  .java 2 s .  co m
 * 
 * @note If location is not enabled, this method will return null
 * @return the current location or null if location access is not enabled or
 *         granted by the user.
 */
public Location getCurrentLocation() {
    if (_contextReference == null) {
        return null;
    }

    Context context = _contextReference.get();
    if (context == null) {
        return null;
    }

    Location location = null;

    if (context.checkCallingOrSelfPermission(
            android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    } else if (context.checkCallingOrSelfPermission(
            android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }
    return location;
}

From source file:com.andybotting.tramhunter.activity.StopDetailsActivity.java

/**
 * Upload statistics to our web server//from  w w w . j  av a 2s .  co  m
 */
private void uploadStats() {
    if (LOGV)
        Log.i(TAG, "Sending stop request statistics");

    // gather all of the device info
    try {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String device_uuid = tm.getDeviceId();
        String device_id = "00000000000000000000000000000000";
        if (device_uuid != null) {
            device_id = GenericUtil.MD5(device_uuid);
        }

        LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Location location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        // post the data
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://tramhunter.andybotting.com/stats/stop/send");
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("device_id", device_id));
        pairs.add(new BasicNameValuePair("guid", ttService.getGUID()));
        pairs.add(new BasicNameValuePair("ttid", String.valueOf(mStop.getTramTrackerID())));

        if (location != null) {
            pairs.add(new BasicNameValuePair("latitude", String.valueOf(location.getLatitude())));
            pairs.add(new BasicNameValuePair("longitude", String.valueOf(location.getLongitude())));
            pairs.add(new BasicNameValuePair("accuracy", String.valueOf(location.getAccuracy())));
        }

        try {
            post.setEntity(new UrlEncodedFormEntity(pairs));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        try {
            HttpResponse response = client.execute(post);
            response.getStatusLine().getStatusCode();
        } catch (Exception e) {
            e.printStackTrace();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:net.jongrakko.zipsuri.activity.PostUploadActivity.java

@Override
public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
    if (isChecked) {
        switch (buttonView.getId()) {
        case R.id.radioButtonAddressGPS:
            mEditTextAddress.setOnClickListener(null);
            this.mGoogleMap.setOnMapClickListener(this);
            this.mGoogleMap.setOnMyLocationButtonClickListener(this);

            if (ContextCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                mGoogleMap.setMyLocationEnabled(true);
                LocationProvider lprovider;
                LocationManager lm = (LocationManager) getActivity()
                        .getSystemService(getActivity().LOCATION_SERVICE);
                lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
                lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
                String provider;//from   ww  w. j  a  v a2  s .c  o  m
                Criteria criteria = new Criteria();
                criteria.setAccuracy(Criteria.ACCURACY_FINE);
                criteria.setPowerRequirement(Criteria.POWER_HIGH);
                provider = lm.getBestProvider(criteria, true);

                if (provider == null || provider.equals("passive")) { // ? ?    ??
                    new AlertDialog.Builder(getActivity()).setTitle(" ??")
                            .setNeutralButton("??", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    buttonView.toggle();
                                    startActivityForResult(
                                            new Intent(
                                                    android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
                                            0);
                                }
                            }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                                @Override
                                public void onCancel(DialogInterface dialog) {
                                    dialog.dismiss();
                                }
                            }).show();
                } else { //  ? ?   
                    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, this);
                    Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (l != null) {
                        Log.e("hello??", "okok");
                    }
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermissions(new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                            MY_LOCATION_REQUEST_CODE);
                }
            }
            break;
        case R.id.radioButtonAddressSelf:
            this.mGoogleMap.setOnMapClickListener(null);
            mEditTextAddress.setOnClickListener(this);
            this.mGoogleMap.setOnMyLocationButtonClickListener(null);
            mGoogleMap.setMyLocationEnabled(false);
            mEditTextAddress.setOnClickListener(this);
            startActivityForResult(new Intent(getContext(), SearchAddressActivity.class), SEARCH_ADDRESS);
            break;
        }
    }
}

From source file:org.sipdroid.sipua.ui.Receiver.java

static void pos_net(boolean enable) {
    if (net_sender == null) {
        Intent loopintent = new Intent(mContext, LoopLocation.class);
        net_sender = PendingIntent.getBroadcast(mContext, 0, loopintent, 0);
    }/*from  ww  w.  j  av a2s .  c o m*/
    if (net_enabled != enable) {
        if (enable) {
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, NET_UPDATES, 3000, net_sender);
        } else {
            lm.removeUpdates(net_sender);
        }
        net_enabled = enable;
    }
}