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.vonglasow.michael.satstat.ui.MapSectionFragment.java

/**
 * Creates layers and associated tile caches for the map view.
 * //  www. j  a v  a2 s.  co  m
 * @param createOverlays Whether to create overlays (circle and markers) or just tile layers
 */
private void createLayers(boolean createOverlays) {
    LayerManager layerManager = mapMap.getLayerManager();
    Layers layers = layerManager.getLayers();

    if (mainActivity.prefMapOffline && (ContextCompat.checkSelfPermission(mainActivity,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
        /*
         * If offline maps are enabled AND we have storage permission, use offline map tiles.
         * Skip this step if we don't have permission, else we would pollute the cache with blank tiles.
         */
        if (mapRendererTileCache == null)
            mapRendererTileCache = AndroidUtil.createExternalStorageTileCache(this.getContext(),
                    Const.TILE_CACHE_INTERNAL_RENDER_THEME,
                    Math.round(AndroidUtil.getMinimumCacheSize(this.getContext(),
                            mapMap.getModel().displayModel.getTileSize(),
                            mapMap.getModel().frameBufferModel.getOverdrawFactor(), 1f)),
                    mapMap.getModel().displayModel.getTileSize(), true);

        /*
         * If the offline map path changes, we need to purge the cache. This ensures we don't serve stale
         * tiles generated from the old map set.
         * 
         * We accomplish this by comparing the current map path to the map path for which we last
         * instantiated a cache. If they differ, we flush the cache and store the new map path.
         */
        String cachedPath = mainActivity.mSharedPreferences.getString(Const.KEY_PREF_MAP_CACHED_PATH, "");
        if (!cachedPath.equals(mainActivity.prefMapPath)) {
            mapRendererTileCache.purge();
            SharedPreferences.Editor spEditor = mainActivity.mSharedPreferences.edit();
            spEditor.putString(Const.KEY_PREF_MAP_CACHED_PATH, mainActivity.prefMapPath);
            spEditor.commit();
        }

        MultiMapDataStore mapDataStore = new MultiMapDataStore(DataPolicy.DEDUPLICATE);
        File mapDir = new File(mainActivity.prefMapPath);
        Log.i(TAG, String.format("Looking for maps in: %s", mapDir.getName()));
        if (mapDir.exists() && mapDir.canRead() && mapDir.isDirectory())
            for (File file : mapDir.listFiles())
                if (file.isFile())
                    try {
                        MapFile mapFile = new MapFile(file);
                        mapDataStore.addMapDataStore(mapFile, false, false);
                        Log.i(TAG, String.format("Added map file: %s", file.getName()));
                    } catch (MapFileException e) {
                        // not a map file, skip
                        Log.w(TAG, String.format("Could not add map file: %s", file.getName()));
                    }

        mapRendererLayer = new TileRendererLayer(mapRendererTileCache, mapDataStore,
                mapMap.getModel().mapViewPosition, false, true, false, AndroidGraphicFactory.INSTANCE);

        mapRendererLayer.setXmlRenderTheme(InternalRenderTheme.OSMARENDER);

        //mapRendererLayer.setTextScale(1.5f); // FIXME
        layers.add(0, mapRendererLayer);
        mapAttribution.setText(R.string.osm_attribution);
    } else if (!mainActivity.prefMapOffline) {
        // use online map tiles
        if (mapDownloadTileCache == null)
            mapDownloadTileCache = AndroidUtil.createExternalStorageTileCache(this.getContext(),
                    Const.TILE_CACHE_OSM,
                    Math.round(AndroidUtil.getMinimumCacheSize(this.getContext(),
                            mapMap.getModel().displayModel.getTileSize(),
                            mapMap.getModel().frameBufferModel.getOverdrawFactor(), 1f)),
                    mapMap.getModel().displayModel.getTileSize(), true);

        mapDownloadLayer = new TileDownloadLayer(mapDownloadTileCache, mapMap.getModel().mapViewPosition,
                onlineTileSource, AndroidGraphicFactory.INSTANCE);
        layers.add(0, mapDownloadLayer);
        /*
         * Since tiles are now sourced from OSM (following Mapquest's decision to discontinue their free
         * tile service), attribution is the same for online and offline. This may change if we switch
         * to a different tile source (or allow multiple ones) - therefore, attribution should still
         * depend on the map source.
         */
        mapAttribution.setText(R.string.osm_attribution);
    } else
        mapAttribution.setText("");

    //parse list of location providers
    if (createOverlays)
        onLocationProvidersChanged(mainActivity.mSharedPreferences.getStringSet(Const.KEY_PREF_LOC_PROV,
                new HashSet<String>(Arrays.asList(
                        new String[] { LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER }))));

    // mark cache as purged
    SharedPreferences.Editor spEditor = mainActivity.mSharedPreferences.edit();
    spEditor.putBoolean(Const.KEY_PREF_MAP_PURGE, false);
    spEditor.commit();
}

From source file:edu.drake.research.android.lipswithmaps.activity.MapsActivity.java

/**
 * Gets the current location/*from  www. jav a  2  s .  c om*/
 */
private void getCurrentLongLat() {
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    //Check permission
    // Register the listener with the Location Manager to receive location updates
    if (ContextCompat.checkSelfPermission(this, locationPermission) == PackageManager.PERMISSION_GRANTED) {
        mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, mLocationListener);
        wifiScan();
    } else {
        askPermission();
    }

}

From source file:org.opensmc.mytracks.cyclesmc.MainInput.java

/** Called when the activity is first created. */
@Override/*  w  w  w  . ja v  a 2  s  . c o  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Firebase.setAndroidContext(this);

    final Firebase ref = new Firebase("https://org.opensmc.mytracks.cyclesmc.firebaseio.com");
    final Firebase phlref = new Firebase("https://phl.firebaseio.com");
    // Let's handle some launcher lifecycle issues:
    // If we're recording or saving right now, jump to the existing activity.
    // (This handles user who hit BACK button while recording)
    setContentView(R.layout.main);
    weatherFont = Typeface.createFromAsset(getAssets(), "cyclesmc.ttf");

    weatherText = (TextView) findViewById(R.id.weatherView);
    weatherText.setTypeface(weatherFont);
    weatherText.setText(R.string.cloudy);

    Intent rService = new Intent(this, RecordingService.class);
    ServiceConnection sc = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
        }

        public void onServiceConnected(ComponentName name, IBinder service) {
            IRecordService rs = (IRecordService) service;
            int state = rs.getState();
            if (state > RecordingService.STATE_IDLE) {
                if (state == RecordingService.STATE_FULL) {
                    startActivity(new Intent(MainInput.this, SaveTrip.class));
                } else { // RECORDING OR PAUSED:
                    startActivity(new Intent(MainInput.this, RecordingActivity.class));
                }
                MainInput.this.finish();
            } else {
                // Idle. First run? Switch to user prefs screen if there are no prefs stored yet
                SharedPreferences settings = getSharedPreferences("PREFS", 0);
                String anon = settings.getString("" + PREF_ANONID, "NADA");

                if (settings.getAll().isEmpty()) {
                    showWelcomeDialog();
                } else if (anon == "NADA") {
                    showWelcomeDialog();
                }
                // Not first run - set up the list view of saved trips
                ListView listSavedTrips = (ListView) findViewById(R.id.ListSavedTrips);
                populateList(listSavedTrips);
            }
            MainInput.this.unbindService(this); // race?  this says we no longer care
        }
    };
    // This needs to block until the onServiceConnected (above) completes.
    // Thus, we can check the recording status before continuing on.
    bindService(rService, sc, Context.BIND_AUTO_CREATE);

    // And set up the record button
    final Button startButton = (Button) findViewById(R.id.ButtonStart);
    final Intent i = new Intent(this, RecordingActivity.class);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
    SharedPreferences settings = getSharedPreferences("PREFS", 0);
    final String anon = settings.getString("" + PREF_ANONID, "NADA");

    Firebase weatherRef = new Firebase("https://publicdata-weather.firebaseio.com/philadelphia");
    Firebase tempRef = new Firebase("https://publicdata-weather.firebaseio.com/philadelphia/currently");

    tempRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Object val = dataSnapshot.getValue();
            String cardinal = null;

            TextView tempState = (TextView) findViewById(R.id.temperatureView);
            //                TextView liveTemp = (TextView) findViewById(R.id.warning);
            String apparentTemp = ((Map) val).get("apparentTemperature").toString();
            String windSpeed = ((Map) val).get("windSpeed").toString();
            Double windValue = (Double) ((Map) val).get("windSpeed");
            Long windBearing = (Long) ((Map) val).get("windBearing");

            //                liveTemp.setText(" "+apparentTemp.toString()+DEGREE);
            WindDirection[] windDirections = WindDirection.values();
            for (int i = 0; i < windDirections.length; i++) {
                if (windDirections[i].startDegree < windBearing && windDirections[i].endDegree > windBearing) {
                    //Get Cardinal direction
                    cardinal = windDirections[i].cardinal;
                }
            }

            if (windValue > 4) {
                tempState.setTextColor(0xFFDC143C);
                tempState.setText("winds " + cardinal + " at " + windSpeed + " mph. Ride with caution.");
            } else {
                tempState.setTextColor(0xFFFFFFFF);
                tempState.setText("winds " + cardinal + " at " + windSpeed + " mph.");
            }

        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

    connectedListener = ref.getRoot().child(".info/connected").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            boolean connected = (Boolean) dataSnapshot.getValue();
            if (connected) {
                System.out.println("connected " + dataSnapshot.toString());
                //                    Firebase cycleRef = new Firebase(FIREBASE_REF+"/"+anon+"/connections");
                //                    cycleRef.setValue(Boolean.TRUE);
                //                    cycleRef.onDisconnect().removeValue();
            } else {
                System.out.println("disconnected");
            }
        }

        @Override
        public void onCancelled(FirebaseError error) {
            // No-op
        }
    });
    weatherRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            Object value = snapshot.getValue();
            Object hourly = ((Map) value).get("currently");
            String alert = ((Map) hourly).get("summary").toString();
            //                TextView weatherAlert = (TextView) findViewById(R.id.weatherAlert);
            //                weatherAlert.setText(alert);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

    // Acquire a reference to the system Location Manager
    // Define a listener that responds to location updates
    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            // Called when a new location is found by the network location provider.

            mySpot = new LatLng(location.getLatitude(), location.getLongitude());
            makeUseOfNewLocation(location);
        }

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

        public void onProviderEnabled(String provider) {
        }

        public void onProviderDisabled(String provider) {
        }
    };

    //nearbyStations = (RecyclerView) findViewById(R.id.nearbyStationList);
    //nearbyStations.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
    //Listener for Indego Changes
    /*indegoRef = new Firebase("https://phl.firebaseio.com/indego/kiosks");
    indegoRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        //Updates! Add them to indego data list
        indegoDataList = dataSnapshot;
            
            
    }
            
    @Override
    public void onCancelled(FirebaseError firebaseError) {
            
    }
    });*/

    // Register the listener with the Location Manager to receive location updates

    //indegoGeofireRef = new Firebase("https://phl.firebaseio.com/indego/_geofire");
    //GeoFire geoFire = new GeoFire(indegoGeofireRef);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    mySpot = myCurrentLocation();
    //indegoList = new ArrayList<IndegoStation>();
    System.out.println("lo: " + mySpot.toString());

    /* GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(mySpot.latitude,mySpot.longitude), 0.5);
     geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
    @Override
    public void onKeyEntered(String key, GeoLocation location) {
        System.out.println(String.format("Key %s entered the search area at [%f,%f]", key, location.latitude, location.longitude));
        //Create Indego Station object. To-do: check if object exists
       // IndegoStation station = new IndegoStation();
        //station.kioskId = key;
        //station.location = location;
       /* if(indegoDataList != null){
            //get latest info from list
            station.name = (String) indegoDataList.child(key).child("properties").child("name").getValue();
        }
        System.out.println(station.name);
        //indegoList.add(station);
        //To-do: Add indego station info to RideIndegoAdapter
            
    }
            
    @Override
    public void onKeyExited(String key) {
            
    }
            
    @Override
    public void onKeyMoved(String key, GeoLocation location) {
            
    }
            
    @Override
        /* public void onGeoQueryReady() {
        //System.out.println("GEO READY :"+indegoList.toString());
       // indegoAdapter = new RideIndegoAdapter(getApplicationContext(),indegoList);
        //nearbyStations.setAdapter(indegoAdapter);
            
            
    }
            
    @Override
    public void onGeoQueryError(FirebaseError error) {
        System.out.println("GEO error");
    }
     });*/

    startButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Before we go to record, check GPS status
            final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                buildAlertMessageNoGps();
            } else {
                startActivity(i);
                MainInput.this.finish();
            }
        }
    });

    toolbar = (Toolbar) findViewById(R.id.dashboard_bar);
    toolbar.setTitle(getString(R.string.app_name));

    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(true);
}

From source file:com.grayfox.android.app.fragment.ExploreFragment.java

private boolean areAnyLocationProvidersEnabled() {
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}

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

@Override
public boolean onMyLocationButtonClick() {
    LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    if (!mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        ProgressManger.showToast("  .");
    } else {// w  ww.j a v a2 s  .c  o m
        ProgressManger.showToast("  ...");
    }
    return false;
}

From source file:com.chalmers.schmaps.CheckInActivity.java

/**
 * Method to define what the activity does on resume.
 * Updates the coordinates of the current position.
 *//* www  .j  a  v  a2  s .c o  m*/
@Override
protected void onResume() {
    super.onResume();
    try {
        // Register the listener with the Location Manager to receive
        // location updates
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, UPDATEFREQUENCYINMS,
                UPDATEAAREA, locationListener);
    } catch (Exception e) {
    }
}

From source file:org.globalquakemodel.org.idctdo.EQForm_MapView.java

@Override
public void onResume() {
    super.onResume();
    if (DEBUG_LOG)
        Log.d("IDCT", "ON RESUME");

    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    //SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);      
    showGPSDetails = (settings.getBoolean("showPositionDetailsCheckBox", false));

    if (showGPSDetails) {
        text_view_gpsInfo.setVisibility(View.VISIBLE);//
        text_view_gpsInfo2.setVisibility(View.VISIBLE);//
    } else {/*from   www .j  a  v a 2 s  . c om*/
        text_view_gpsInfo.setVisibility(View.INVISIBLE);//
        text_view_gpsInfo2.setVisibility(View.INVISIBLE);//
    }

    /*
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10f, mlocListener);
    locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
            
    // Register the listener with the Location Manager to receive location
    // updates
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
       locationManager.requestLocationUpdates(
       LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
    } else {
       locationManager.requestLocationUpdates(
       LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
    }
     */

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

    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        Toast.makeText(this, "GPS is Enabled in your device", Toast.LENGTH_SHORT).show();
    } else {
        //showGPSDisabledAlertToUser();
    }

    if (DEBUG_LOG)
        Log.d("IDCT", "Requesting location updates for network");

    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, minTimePositionUpdates,
            minDistPositionUpdates, mlocListener);
    if (DEBUG_LOG)
        Log.d("IDCT", "Requesting location updates for GPS");
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTimePositionUpdates,
            minDistPositionUpdates, mlocListener);

    mWebView.loadUrl("javascript:clearMyPositions()");
    loadPrevSurveyPoints();

    GEMSurveyObject g = (GEMSurveyObject) getApplication();
    if (DEBUG_LOG)
        Log.d(TAG, "RESUMING MAP, global vars " + g.getLon() + " lat: " + g.getLat());
    if (g.getLat() == 0 && g.getLon() == 0) {
        Toast.makeText(this, "Waiting for location", Toast.LENGTH_SHORT).show();
    } else {
        mWebView.loadUrl("javascript:locateMe(" + g.getLat() + "," + g.getLon() + "," + currentLocationAccuracy
                + "," + currentLocationSetAsCentre + ")");
    }

    //If there is unsaved edits draw the current candidate survey point
    if (g.unsavedEdits) {
        //Draw a candidate survey point
        if (DEBUG_LOG)
            Log.d(TAG, "RESUMING EDITS. DRAWING MOVEABLE POINT, " + g.getLon() + " lat: " + g.getLat());
        mWebView.loadUrl("javascript:drawCandidateSurveyPoint(" + g.getLon() + "," + g.getLat() + ")");

    } else {
        //Set the screen up to be ready for user drawing a new survey point
        if (DEBUG_LOG)
            Log.d(TAG, "NO UNSAVED EDITS. Hide the survey button. , " + g.getLon() + " lat: " + g.getLat());
        btn_edit_points.setChecked(false);
        isEditingPoints = false;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btn_startSurvey.setVisibility(View.INVISIBLE);//Dodgy threading stuff using this
                btn_cancelSurveyPoint.setVisibility(View.INVISIBLE);//Dodgy threading stuff using this
                btn_startSurveyFavourite.setVisibility(View.INVISIBLE);//Dodgy threading stuff using this
                //btn_take_survey_photo.setVisibility(View.INVISIBLE);//Poss Dodgy threading stuff using this
                btn_takeCameraPhoto.setBackgroundResource(R.drawable.camera);
                btn_edit_points.setEnabled(true);
            }
        });
    }
}

From source file:com.shafiq.myfeedle.core.MyfeedleCreatePost.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int itemId = item.getItemId();
    if (itemId == R.id.menu_post_accounts)
        chooseAccounts();/*from   w  w  w .j  a  v  a  2s .co  m*/
    else if (itemId == R.id.menu_post_photo) {
        boolean supported = false;
        Iterator<Integer> services = mAccountsService.values().iterator();
        while (services.hasNext() && ((supported = sPhotoSupported.contains(services.next())) == false))
            ;
        if (supported) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PHOTO);
        } else
            unsupportedToast(sPhotoSupported);
        //      } else if (itemId == R.id.menu_post_tags) {
        //         if (mAccountsService.size() == 1) {
        //            if (sTaggingSupported.contains(mAccountsService.values().iterator().next()))
        //               selectFriends(mAccountsService.keySet().iterator().next());
        //            else
        //               unsupportedToast(sTaggingSupported);
        //         } else {
        //            // dialog to select an account
        //            Iterator<Long> accountIds = mAccountsService.keySet().iterator();
        //            HashMap<Long, String> accountEntries = new HashMap<Long, String>();
        //            while (accountIds.hasNext()) {
        //               Long accountId = accountIds.next();
        //               Cursor account = this.getContentResolver().query(Accounts.getContentUri(this), new String[]{Accounts._ID, ACCOUNTS_QUERY}, Accounts._ID + "=?", new String[]{Long.toString(accountId)}, null);
        //               if (account.moveToFirst() && sTaggingSupported.contains(mAccountsService.get(accountId)))
        //                  accountEntries.put(account.getLong(0), account.getString(1));
        //            }
        //            int size = accountEntries.size();
        //            if (size != 0) {
        //               final long[] accountIndexes = new long[size];
        //               final String[] accounts = new String[size];
        //               int i = 0;
        //               Iterator<Map.Entry<Long, String>> entries = accountEntries.entrySet().iterator();
        //               while (entries.hasNext()) {
        //                  Map.Entry<Long, String> entry = entries.next();
        //                  accountIndexes[i] = entry.getKey();
        //                  accounts[i++] = entry.getValue();
        //               }
        //               mDialog = (new AlertDialog.Builder(this))
        //                     .setTitle(R.string.accounts)
        //                     .setSingleChoiceItems(accounts, -1, new DialogInterface.OnClickListener() {
        //                        @Override
        //                        public void onClick(DialogInterface dialog, int which) {
        //                           selectFriends(accountIndexes[which]);
        //                           dialog.dismiss();
        //                        }
        //                     })
        //                     .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
        //                        @Override
        //                        public void onClick(DialogInterface dialog, int which) {
        //                           dialog.dismiss();
        //                        }
        //                     })
        //                     .create();
        //               mDialog.show();
        //            } else
        //               unsupportedToast(sTaggingSupported);
        //         }
    } else if (itemId == R.id.menu_post_location) {
        LocationManager locationManager = (LocationManager) MyfeedleCreatePost.this
                .getSystemService(Context.LOCATION_SERVICE);
        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (location != null) {
            mLat = Double.toString(location.getLatitude());
            mLong = Double.toString(location.getLongitude());
            if (mAccountsService.size() == 1) {
                if (sLocationSupported.contains(mAccountsService.values().iterator().next()))
                    setLocation(mAccountsService.keySet().iterator().next());
                else
                    unsupportedToast(sLocationSupported);
            } else {
                // dialog to select an account
                Iterator<Long> accountIds = mAccountsService.keySet().iterator();
                HashMap<Long, String> accountEntries = new HashMap<Long, String>();
                while (accountIds.hasNext()) {
                    Long accountId = accountIds.next();
                    Cursor account = this.getContentResolver().query(Accounts.getContentUri(this),
                            new String[] { Accounts._ID, ACCOUNTS_QUERY }, Accounts._ID + "=?",
                            new String[] { Long.toString(accountId) }, null);
                    if (account.moveToFirst() && sLocationSupported.contains(mAccountsService.get(accountId)))
                        accountEntries.put(account.getLong(account.getColumnIndex(Accounts._ID)),
                                account.getString(account.getColumnIndex(Accounts.USERNAME)));
                }
                int size = accountEntries.size();
                if (size != 0) {
                    final long[] accountIndexes = new long[size];
                    final String[] accounts = new String[size];
                    int i = 0;
                    Iterator<Map.Entry<Long, String>> entries = accountEntries.entrySet().iterator();
                    while (entries.hasNext()) {
                        Map.Entry<Long, String> entry = entries.next();
                        accountIndexes[i] = entry.getKey();
                        accounts[i++] = entry.getValue();
                    }
                    mDialog = (new AlertDialog.Builder(this)).setTitle(R.string.accounts)
                            .setSingleChoiceItems(accounts, -1, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    setLocation(accountIndexes[which]);
                                    dialog.dismiss();
                                }
                            })
                            .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create();
                    mDialog.show();
                } else
                    unsupportedToast(sLocationSupported);
            }
        } else
            (Toast.makeText(this, getString(R.string.location_unavailable), Toast.LENGTH_LONG)).show();
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.example.administrator.myapplication2._2_exercise._2_Status_heart.fragments.LeftFragment.java

/**
 *   ??  ? /* ww w .j  a  va  2 s .c  o  m*/
 */
private void startLocationService() {
    //  ? ? 
    manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

    //   ?   ? ?
    gpsListener = new GPSListener();
    long minTime = 5000;//GPS    - 20  
    float minDistance = 1;//?? (10m)

    // GPS   
    manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, gpsListener);

    // ?   
    manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, minTime, minDistance, gpsListener);

    /*   //  ?? ? ?? ? ??    ?
       try {
    Location lastLocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (lastLocation != null) {
        Double latitude = lastLocation.getLatitude();
        Double longitude = lastLocation.getLongitude();
            
    }
       } catch(Exception ex) {
    ex.printStackTrace();
       }*/

}

From source file:com.adwhirl.AdWhirlManager.java

public Location getLocation() {
    if (contextReference == null) {
        return null;
    }/* ww w  .  java 2  s  . co  m*/

    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;
}