Example usage for android.content Context LOCATION_SERVICE

List of usage examples for android.content Context LOCATION_SERVICE

Introduction

In this page you can find the example usage for android.content Context LOCATION_SERVICE.

Prototype

String LOCATION_SERVICE

To view the source code for android.content Context LOCATION_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.location.LocationManager for controlling location updates.

Usage

From source file:com.company.millenium.iwannask.MainActivity.java

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

    //GPS/*from   w w w  .  ja v a2  s . c  o  m*/
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            if (ActivityCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // Check Permissions Now
                final int REQUEST_LOCATION = 2;

                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
                    // Display UI and wait for user interaction
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION);
                }
            } else {
                locationManager.removeUpdates(this);
            }
        }

        public void onStatusChanged(String string, int integer, Bundle bundle) {

        }

        public void onProviderEnabled(String string) {

        }

        public void onProviderDisabled(String string) {

        }
    };

    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // Check Permissions Now
        final int REQUEST_LOCATION = 2;

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Display UI and wait for user interaction
        } else {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                    REQUEST_LOCATION);
        }
    } else {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1000, locationListener);
    }

    int delay = 30000; // delay for 30 sec.
    int period = 3000000; // repeat every 5.3min.
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            if (ActivityCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // Check Permissions Now
                final int REQUEST_LOCATION = 2;

                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
                    // Display UI and wait for user interaction
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION);
                }
            } else {
                locationManager.removeUpdates(locationListener);
            }
        }
    }, delay, period);

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

    Intent mIntent = getIntent();
    URL = Constants.SERVER_URL;
    if (mIntent.hasExtra("url")) {
        myWebView = null;
        startActivity(getIntent());
        String url = mIntent.getStringExtra("url");
        URL = Constants.SERVER_URL + url;
    }

    CookieSyncManager.createInstance(this);
    CookieSyncManager.getInstance().startSync();
    myWebView = (WebView) findViewById(R.id.webview);
    myWebView.getSettings().setGeolocationDatabasePath(this.getFilesDir().getPath());
    myWebView.getSettings().setGeolocationEnabled(true);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setUseWideViewPort(false);
    if (!DetectConnection.checkInternetConnection(this)) {
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        showNoConnectionDialog(this);
    } else {
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
    }
    webSettings.setJavaScriptEnabled(true);
    myWebView.addJavascriptInterface(new webappinterface(this), "android");
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setUseWideViewPort(true);
    myWebView.setOverScrollMode(View.OVER_SCROLL_NEVER);

    //location test
    webSettings.setAppCacheEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webSettings.setDomStorageEnabled(true);

    myWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            CookieSyncManager.getInstance().sync();
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed(); // Ignore SSL certificate errors
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().equals(Constants.HOST)
                    || Uri.parse(url).getHost().equals(Constants.WWWHOST)) {
                // This is my web site, so do not override; let my WebView load
                // the page
                return false;
            }
            // Otherwise, the link is not for a page on my site, so launch
            // another Activity that handles URLs
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
    });
    myWebView.setWebChromeClient(new WebChromeClient() {
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }

        @Override
        public void onPermissionRequest(final PermissionRequest request) {
            Log.d(TAG, "onPermissionRequest");
            runOnUiThread(new Runnable() {
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void run() {
                    if (request.getOrigin().toString().equals("https://apprtc-m.appspot.com/")) {
                        request.grant(request.getResources());
                    } else {
                        request.deny();
                    }
                }
            });
        }

        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams) {

            // Double check that we don't have any existing callbacks
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            // Set up the take picture intent
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Log.e(TAG, "Unable to create Image File", ex);
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            // Set up the intent to get an existing image
            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            // Set up the intents for the Intent chooser
            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }

    });
    // setContentView(myWebView);
    //        myWebView.loadUrl(URL);
    myWebView.loadUrl(URL);
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //                mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
        }
    };

    //CookieManager mCookieManager = CookieManager.getInstance();
    //Boolean hasCookies = mCookieManager.hasCookies();
    //while(!hasCookies);

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        //intent.putExtra("session", session);
        startService(intent);
    }

    Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isFirstRun", true);

    if (isFirstRun) {
        //show start activity
        startActivity(new Intent(MainActivity.this, MyIntro.class));
    }
    //if (!isOnline())
    //    showNoConnectionDialog(this);
    getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("isFirstRun", false).commit();

    //Pull-to-refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.container);
    mSwipeRefreshLayout.setOnRefreshListener(this);
}

From source file:com.kentli.cycletrack.RecordingService.java

public void pauseRecording() {
    this.state = STATE_PAUSED;
    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    lm.removeUpdates(this);
}

From source file:de.uni.stuttgart.informatik.ToureNPlaner.UI.Activities.MapScreen.MapScreen.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean isFirstStart = savedInstanceState == null;
    // If we get created for the first time we get our data from the intent
    Bundle data = savedInstanceState != null ? savedInstanceState : getIntent().getExtras();
    session = (Session) data.getSerializable(Session.IDENTIFIER);

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

    mapView = (MapView) findViewById(R.id.mapView);
    mapView.setClickable(true);/* ww  w  . j a v a  2  s.c  o m*/
    mapView.setLongClickable(true);
    mapView.setBuiltInZoomControls(true);
    mapView.getFileSystemTileCache().setPersistent(false);

    getSupportActionBar().setSubtitle(session.getSelectedAlgorithm().toString());
    initializeHandler();

    setupWayOverlay();

    setupGPS(savedInstanceState, isFirstStart);

    if (session.getResult() != null) {
        updateDistancePopup();
        if (session.getResult().getPoints() != null) {
            mapView.setCenter(session.getResult().getPoints().get(0).getGeoPoint());
        }
    }
    if (!mapView.getMapPosition().isValid()) {
        mapView.setCenter(new GeoPoint(51.33, 10.45));
    }

    mapView.getOverlays().add(nodeOverlay);

    session.registerListener(NodeOverlay.class, nodeOverlay);
    session.registerListener(MapScreen.class, this);
}

From source file:com.example.scrumptious.PickerActivity.java

@Override
protected void onStart() {
    super.onStart();
    if (FRIEND_PICKER.equals(getIntent().getData())) {
        try {/*w  ww  . j a  v  a2 s. com*/
            friendPickerFragment.loadData(false);
        } catch (Exception ex) {
            onError(ex);
        }
    } else if (PLACE_PICKER.equals(getIntent().getData())) {
        try {
            Location location = null;
            Criteria criteria = new Criteria();
            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            String bestProvider = locationManager.getBestProvider(criteria, false);
            if (bestProvider != null) {
                location = locationManager.getLastKnownLocation(bestProvider);
                if (locationManager.isProviderEnabled(bestProvider) && locationListener == null) {
                    locationListener = new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {
                            boolean updateLocation = true;
                            Location prevLocation = placePickerFragment.getLocation();
                            if (prevLocation != null) {
                                updateLocation = location.distanceTo(prevLocation) >= LOCATION_CHANGE_THRESHOLD;
                            }
                            if (updateLocation) {
                                placePickerFragment.setLocation(location);
                                placePickerFragment.loadData(true);
                            }
                        }

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

                        @Override
                        public void onProviderEnabled(String s) {
                        }

                        @Override
                        public void onProviderDisabled(String s) {
                        }
                    };
                    locationManager.requestLocationUpdates(bestProvider, 1, LOCATION_CHANGE_THRESHOLD,
                            locationListener, Looper.getMainLooper());
                }
            }
            if (location != null) {
                placePickerFragment.setLocation(location);
                placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
                placePickerFragment.setSearchText(SEARCH_TEXT);
                placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
                placePickerFragment.loadData(false);
            }
        } catch (Exception ex) {
            onError(ex);
        }
    }
}

From source file:com.cianmcgovern.android.ShopAndShare.Share.java

@Override
public void onCreate(Bundle savedInstanceState) {

    mContext = this;
    super.onCreate(savedInstanceState);

    setContentView(R.layout.share);//  www  .  ja  va2  s .  com

    Button upload = (Button) findViewById(R.id.uploadButton);
    upload.setText(R.string.upload);
    upload.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String userLoc = mLocationEdit.getText().toString();
            String userStore = mStore.getText().toString();
            // Don't allow empty text fields
            if (userLoc.length() > 1 && userStore.length() > 1) {
                runUpload(Results.getInstance(), userLoc, userStore);
            } else
                new AlertDialog.Builder(mContext).setTitle(R.string.invalidInput)
                        .setMessage(R.string.invalidFields).show();
        }

    });

    Button cancel = (Button) findViewById(R.id.cancelShareButton);
    cancel.setText(R.string.cancelButton);
    cancel.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mLocationListener != null)
                mLocationManager.removeUpdates(mLocationListener);
            finish();
        }

    });

    mLocationEdit = (EditText) findViewById(R.id.enterLocation);
    mLocationEdit.setOnKeyListener(new OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction()) == KeyEvent.ACTION_DOWN && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                in.hideSoftInputFromWindow(mLocationEdit.getApplicationWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
                return true;
            }
            return false;
        }

    });
    mStore = (EditText) findViewById(R.id.enterStore);
    mStore.setOnKeyListener(new OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction()) == KeyEvent.ACTION_DOWN && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                in.hideSoftInputFromWindow(mStore.getApplicationWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
                return true;
            }
            return false;
        }

    });

    mSearch = (Button) findViewById(R.id.locationButton);
    mSearch.setBackgroundResource(R.drawable.search);
    mSearch.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
            if (!CheckFeatures.haveGPS()) {
                new AlertDialog.Builder(mContext).setTitle("GPS Required")
                        .setMessage("You must have GPS to use this feature").show();
            }
            // Only use GPS if it is enabled
            else if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                mSearch.setEnabled(false);
                mSearch.setBackgroundResource(R.drawable.world);
                getLocation();
            } else {
                mGpsDialog = new AlertDialog.Builder(mContext).create();
                mGpsDialog.setTitle(R.string.gpsDisabled);
                mGpsDialog.setMessage(mContext.getText(R.string.gpsDisabledMessage));
                mGpsDialog.show();
            }
        }

    });
}

From source file:com.airbop.library.simple.CommonUtilities.java

/** 
 * Get the current location from the location manager, and when we get it
 * post that information to the Airbop servers
 * @param appContext/*from   w ww .j  av a  2s . c  o m*/
 * @param regId
 * @return
 */
public static boolean getCurrentLocation(LocationListener locationListener, final Context appContext) {
    if (true) {
        Criteria criteria = getCriteria();
        LocationManager locationManager = (LocationManager) appContext
                .getSystemService(Context.LOCATION_SERVICE);
        if (locationManager != null) {
            String provider = locationManager.getBestProvider(criteria, true);
            if (provider != null) {
                locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);
                // We've posted so let the caller know
                return true;
            }
        }
    }
    // We couldn't get the location manager so let the caller know
    return false;
}

From source file:com.eutectoid.dosomething.PickerActivity.java

@Override
protected void onStart() {
    super.onStart();
    if (FRIEND_PICKER.equals(getIntent().getData())) {
        try {/* w  w  w. j ava 2  s  .c  om*/
            friendPickerFragment.loadData(false);
        } catch (Exception ex) {
            onError(ex);
        }
    } else if (PLACE_PICKER.equals(getIntent().getData())) {
        try {
            Location location = null;
            Criteria criteria = new Criteria();

            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            String bestProvider = locationManager.getBestProvider(criteria, false);
            // API 23: we have to check if ACCESS_FINE_LOCATION and/or ACCESS_COARSE_LOCATION permission are granted
            if (ContextCompat.checkSelfPermission(this,
                    android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this,
                            android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                location = locationManager.getLastKnownLocation(bestProvider);
                if (locationManager.isProviderEnabled(bestProvider) && locationListener == null) {
                    locationListener = new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {
                            boolean updateLocation = true;
                            Location prevLocation = placePickerFragment.getLocation();
                            if (prevLocation != null) {
                                updateLocation = location.distanceTo(prevLocation) >= LOCATION_CHANGE_THRESHOLD;
                            }
                            if (updateLocation) {
                                placePickerFragment.setLocation(location);
                                placePickerFragment.loadData(true);
                            }
                        }

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

                        @Override
                        public void onProviderEnabled(String s) {
                        }

                        @Override
                        public void onProviderDisabled(String s) {
                        }
                    };
                    locationManager.requestLocationUpdates(bestProvider, 1, LOCATION_CHANGE_THRESHOLD,
                            locationListener, Looper.getMainLooper());
                }
            }
            if (location != null) {
                placePickerFragment.setLocation(location);
                placePickerFragment.setRadiusInMeters(SEARCH_RADIUS_METERS);
                placePickerFragment.setSearchText(SEARCH_TEXT);
                placePickerFragment.setResultsLimit(SEARCH_RESULT_LIMIT);
                placePickerFragment.loadData(false);
            }
        } catch (Exception ex) {
            onError(ex);
        }
    }
}

From source file:com.dat255.ht13.grupp23.view.MapView.java

/**
 * Initiating the GoogleMap and all necessary items for the configuration
 * //from  w w  w .  jav  a  2 s.  c  o m
 * @param fragmentActivity
 */
private void initiateMap(FragmentActivity fragmentActivity) {
    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(fragmentActivity.getBaseContext());

    // Showing status
    if (status != ConnectionResult.SUCCESS) { // Google Play Services are
        // not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, fragmentActivity, requestCode);
        dialog.show();

    } else { // Google Play Services are available

        // Getting reference to the SupportMapFragment of activity_main.xml
        SupportMapFragment fm = (SupportMapFragment) fragmentActivity.getSupportFragmentManager()
                .findFragmentById(R.id.map);

        // Getting GoogleMap object from the fragment
        googleMap = fm.getMap();

        // Enabling MyLocation Layer of Google Map
        googleMap.setMyLocationEnabled(true);

        // Getting LocationManager object from System Service
        // LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) fragmentActivity
                .getSystemService(Context.LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            onLocationChanged(location);
            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        }
    }

}

From source file:com.facebook.react.modules.location.LocationModule.java

/**
 * Start listening for location updates. These will be emitted via the
 * {@link RCTDeviceEventEmitter} as {@code geolocationDidChange} events.
 *
 * @param options map containing optional arguments: highAccuracy (boolean)
 *//*  w ww.ja  v a  2 s  . c  o m*/
@ReactMethod
public void startObserving(ReadableMap options) {
    if (LocationManager.GPS_PROVIDER.equals(mWatchedProvider)) {
        return;
    }
    LocationOptions locationOptions = LocationOptions.fromReactMap(options);

    try {
        LocationManager locationManager = (LocationManager) getReactApplicationContext()
                .getSystemService(Context.LOCATION_SERVICE);
        String provider = getValidProvider(locationManager, locationOptions.highAccuracy);
        if (provider == null) {
            emitError(PositionError.POSITION_UNAVAILABLE, "No location provider available.");
            return;
        }
        if (!provider.equals(mWatchedProvider)) {
            locationManager.removeUpdates(mLocationListener);
            locationManager.requestLocationUpdates(provider, 1000, locationOptions.distanceFilter,
                    mLocationListener);
        }
        mWatchedProvider = provider;
    } catch (SecurityException e) {
        throwLocationPermissionMissing(e);
    }
}

From source file:com.caju.uheer.app.services.infrastructure.ContactablesLoaderCallbacks.java

@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
    final ArrayList<String> infoAndName = new ArrayList<String>();
    try {/*  w w w. j  a v a2s.co  m*/
        for (int i = 0; i < usersFound.length(); i++) {
            infoAndName.add(usersFound.getJSONObject(i).getString("name"));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            Location geoPointLocation = new Location("geoPoint");
            try {
                infoAndName.clear();
                for (int i = 0; i < usersFound.length(); i++) {
                    String appendedText = "";
                    if (!usersFound.getJSONObject(i).has("channel")) {
                        geoPointLocation.setLongitude(usersFound.getJSONObject(i).getDouble("lon"));
                        geoPointLocation.setLatitude(usersFound.getJSONObject(i).getDouble("lat"));
                        float distance = location.distanceTo(geoPointLocation) / 1000;
                        appendedText = String.format("%.1f", distance) + "Km";
                    } else {
                        appendedText = usersFound.getJSONObject(i).getString("channel");
                    }
                    infoAndName.add(appendedText + usersFound.getJSONObject(i).getString("name"));
                    Log.e("infoandname", infoAndName.toString() + infoAndName.get(0) + infoAndName.get(1));
                    Toast.makeText(mContext, infoAndName.toString() + infoAndName.get(0) + infoAndName.get(1),
                            Toast.LENGTH_LONG).show();

                    // infoAndName tem a informacao de distancia ou canal e o nome. Precisa editar
                    //essa parte de baixo pra usar o infoAndName.
                    ArrayList<String> friendsEmails = new ArrayList<>();

                    friendsEmails.addAll(infoAndName);

                    friendsEmails = new ArrayList<>();
                    for (ArrayList<String> array : ServerInformation.getAllActiveListeners()) {
                        friendsEmails.addAll(array);
                        while (friendsEmails.contains(connectedEmail))
                            friendsEmails.remove(connectedEmail);
                    }
                    EmailListAdapter listAdapter = new EmailListAdapter(mContext, R.layout.adapter_email_list,
                            friendsEmails);
                    ListView emails = (ListView) ((Activity) mContext)
                            .findViewById(R.id.gps_friends_from_drawer);
                    emails.setAdapter(listAdapter);

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

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

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    // Minimum of 2 minutes between checks (120000 milisecs).
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 120000, 0, locationListener);
}