Example usage for android.location LocationManager GPS_PROVIDER

List of usage examples for android.location LocationManager GPS_PROVIDER

Introduction

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

Prototype

String GPS_PROVIDER

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

Click Source Link

Document

Name of the GPS location provider.

Usage

From source file:biz.bokhorst.bpt.BPTService.java

protected synchronized void startLocating() {
    // Start activity recognition
    if (activityRecognitionClient == null)
        activityRecognitionClient = new GoogleApiClient.Builder(this).addApi(ActivityRecognition.API)
                .addConnectionCallbacks(BPTService.this).build();

    // Connect activity recognition
    if (!activityRecognitionClient.isConnected() && !activityRecognitionClient.isConnecting()) {
        sendActivity(getString(R.string.connecting), -1, new Date().getTime());
        activityRecognitionClient.connect();
    }/*from ww  w.  j  ava  2  s  .c o m*/

    // Schedule next alarm
    long interval = Integer.parseInt(
            preferences.getString(Preferences.PREF_TRACKINTERVAL, Preferences.PREF_TRACKINTERVAL_DEFAULT)) * 60L
            * 1000L;
    long alarmTime = SystemClock.elapsedRealtime() + interval;
    alarmManager.cancel(pendingAlarmIntent);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, alarmTime, pendingAlarmIntent);

    // Prepare user feedback
    nextTrackTime = new Date(System.currentTimeMillis() + interval);

    // Use activity recognition?
    boolean recognition = preferences.getBoolean(Preferences.PREF_ACTIVITYRECOGNITION,
            Preferences.PREF_ACTIVITYRECOGNITION_DEFAULT);

    if (recognition && !should)
        sendStage(String.format(getString(R.string.StageStill), TIME_FORMATTER.format(nextTrackTime)));

    if (!locating && (recognition ? should || once : true)) {
        locating = true;
        locationwait = false;
        wakeLock.acquire();

        // Start waiting for fix
        long timeout = Integer.parseInt(
                preferences.getString(Preferences.PREF_FIXTIMEOUT, Preferences.PREF_FIXTIMEOUT_DEFAULT))
                * 1000L;
        taskHandler.postDelayed(FixTimeoutTask, timeout);

        // Request location updates
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this,
                taskHandler.getLooper());
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this,
                taskHandler.getLooper());
        locationManager.addGpsStatusListener(this);

        // User feedback
        Date timeoutTime = new Date(System.currentTimeMillis() + timeout);
        boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        sendStage(String.format(getString(R.string.StageFixWait), TIME_FORMATTER.format(timeoutTime)));
        sendStatus(gpsEnabled ? getString(R.string.On) : getString(R.string.Off));
        sendSatellites(-1, -1);
    }
}

From source file:com.smsc.usuario.ui.MapaActivity.java

public void getLocation() {
    try {/*w  ww  . j a  v a  2  s  .  co  m*/
        locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
            Toast.makeText(this, "Por favor Active su GPS", Toast.LENGTH_SHORT).show();
        } else {
            this.canGetLocation = true;
            // First get location from Network Provider
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        onLocationChanged(location);
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            onLocationChanged(location);
                        }
                    }
                }
            }
        }

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

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

private void setup() {

    Location gpsLocation = null;//from w w  w  . j a  v  a 2  s. c o  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:fr.univsavoie.ltp.client.MainActivity.java

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

    // Appliquer le thme LTP a l'ActionBar
    //setTheme(R.style.Theme_ltp);

    // Cration de l'activit principale
    setContentView(R.layout.activity_main);

    // Instancier les classes utiles
    setPopup(new Popup(this));
    setSession(new Session(this));
    setTools(new Tools(this));

    // Afficher la ActionBar
    ActionBar mActionBar = getSupportActionBar();
    mActionBar.setHomeButtonEnabled(true);
    mActionBar.setDisplayShowHomeEnabled(true);

    // MapView settings
    map = (MapView) findViewById(R.id.openmapview);
    map.setTileSource(TileSourceFactory.MAPNIK);
    map.setBuiltInZoomControls(false);//from   w ww  .  j a  va 2s.c  om
    map.setMultiTouchControls(true);

    // MapController settings
    mapController = map.getController();

    //To use MapEventsReceiver methods, we add a MapEventsOverlay:
    overlay = new MapEventsOverlay(this, this);
    map.getOverlays().add(overlay);

    boolean isWifiEnabled = false;
    boolean isGPSEnabled = false;

    // Vrifier si le wifi ou le rseau mobile est activ
    final ConnectivityManager connMgr = (ConnectivityManager) this
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    final NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (wifi.isAvailable() && (wifi.getDetailedState() == DetailedState.CONNECTING
            || wifi.getDetailedState() == DetailedState.CONNECTED)) {
        Toast.makeText(this, R.string.toast_wifi, Toast.LENGTH_LONG).show();
        isWifiEnabled = true;
    } else if (mobile.isAvailable() && (mobile.getDetailedState() == DetailedState.CONNECTING
            || mobile.getDetailedState() == DetailedState.CONNECTED)) {
        Toast.makeText(this, R.string.toast_3G, Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(this, R.string.toast_aucun_reseau, Toast.LENGTH_LONG).show();
    }

    // Obtenir le service de localisation
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    // Verifier si le service de localisation GPS est actif, le cas echeant, tester le rseau
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30 * 1000, 250.0f, this);
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        isGPSEnabled = true;
    } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30 * 1000, 250.0f, this);
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }

    // Afficher une boite de dialogue et proposer d'activer un ou plusieurs services pas actifs
    if (!isWifiEnabled || !isGPSEnabled) {
        //getTools().showSettingsAlert(this, isWifiEnabled, isGPSEnabled);
    }

    // Si on a une localisation, on dfinit ses coordonnes geopoint
    if (location != null) {
        startPoint = new GeoPoint(location.getLatitude(), location.getLongitude());
    } else {
        // Sinon, on indique des paramtres par dfaut
        location = getTools().getLastKnownLocation(locationManager);
        if (location == null) {
            location = new Location("");
            location.setLatitude(46.227638);
            location.setLongitude(2.213749000000);
        }
        startPoint = new GeoPoint(46.227638, 2.213749000000);
    }

    setLongitude(location.getLongitude());
    setLatitude(location.getLatitude());

    destinationPoint = null;
    viaPoints = new ArrayList<GeoPoint>();

    // On recupre quelques paramtres de la session prcdents si possible
    if (savedInstanceState == null) {
        mapController.setZoom(15);
        mapController.setCenter(startPoint);
    } else {
        mapController.setZoom(savedInstanceState.getInt("zoom_level"));
        mapController.setCenter((GeoPoint) savedInstanceState.getParcelable("map_center"));
    }

    // Crer un overlay sur la carte pour afficher notre point de dpart
    myLocationOverlay = new SimpleLocationOverlay(this, new DefaultResourceProxyImpl(this));
    map.getOverlays().add(myLocationOverlay);
    myLocationOverlay.setLocation(startPoint);

    // Boutton pour zoomer la carte
    ImageButton btZoomIn = (ImageButton) findViewById(R.id.btZoomIn);
    btZoomIn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            map.getController().zoomIn();
        }
    });

    // Boutton pour dezoomer la carte
    ImageButton btZoomOut = (ImageButton) findViewById(R.id.btZoomOut);
    btZoomOut.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            map.getController().zoomOut();
        }
    });

    // Pointeurs d'itinrairea:
    final ArrayList<ExtendedOverlayItem> waypointsItems = new ArrayList<ExtendedOverlayItem>();
    itineraryMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, waypointsItems, map,
            new ViaPointInfoWindow(R.layout.itinerary_bubble, map));
    map.getOverlays().add(itineraryMarkers);
    //updateUIWithItineraryMarkers();

    Button searchButton = (Button) findViewById(R.id.buttonSearch);
    searchButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            handleSearchLocationButton();
        }
    });

    //context menu for clicking on the map is registered on this button. 
    registerForContextMenu(searchButton);

    // Routes et Itinraires
    final ArrayList<ExtendedOverlayItem> roadItems = new ArrayList<ExtendedOverlayItem>();
    roadNodeMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, roadItems, map);
    map.getOverlays().add(roadNodeMarkers);

    if (savedInstanceState != null) {
        mRoad = savedInstanceState.getParcelable("road");
        updateUIWithRoad(mRoad);
    }

    //POIs:
    //POI search interface:
    String[] poiTags = getResources().getStringArray(R.array.poi_tags);
    poiTagText = (AutoCompleteTextView) findViewById(R.id.poiTag);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,
            poiTags);
    poiTagText.setAdapter(adapter);
    Button setPOITagButton = (Button) findViewById(R.id.buttonSetPOITag);
    setPOITagButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //Hide the soft keyboard:
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(poiTagText.getWindowToken(), 0);
            //Start search:
            getPOIAsync(poiTagText.getText().toString());
        }
    });

    //POI markers:
    final ArrayList<ExtendedOverlayItem> poiItems = new ArrayList<ExtendedOverlayItem>();
    poiMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, poiItems, map,
            new POIInfoWindow(map));
    map.getOverlays().add(poiMarkers);
    if (savedInstanceState != null) {
        mPOIs = savedInstanceState.getParcelableArrayList("poi");
        updateUIWithPOI(mPOIs);
    }

    // Load friends ListView
    lvListeFriends = (ListView) findViewById(R.id.listViewFriends);
    //lvListeFriends.setBackgroundResource(R.drawable.listview_roundcorner_item);
    lvListeFriends.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
            Friends item = (Friends) adapter.getItemAtPosition(position);
            if (item.getLongitude() != 0.0 && item.getLatitude() != 0.0) {
                destinationPoint = new GeoPoint(item.getLongitude(), item.getLatitude());
                markerDestination = putMarkerItem(markerDestination, destinationPoint, DEST_INDEX,
                        R.string.destination, R.drawable.marker_destination, -1);
                getRoadAsync();
                map.getController().setCenter(destinationPoint);
            } else {
                Toast.makeText(MainActivity.this, R.string.toast_friend_statut, Toast.LENGTH_LONG).show();
            }
        }
    });

    viewMapFilters = (ScrollView) this.findViewById(R.id.scrollViewMapFilters);
    viewMapFilters.setVisibility(View.GONE);

    // Initialiser tout ce qui est donnes utilisateur propres  l'activit
    init();

    getTools().relocateUser(mapController, map, myLocationOverlay, location);
}

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

private void setup() {
    Location gpsLocation = null;//w  w  w  .j  ava 2s . 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:com.warp10.app.LocationService.java

/**
 * Handler of action Start/*www  . j  av a  2 s . co m*/
 * @param isListenGPS if asked register GPS
 * @param isListenNetWork if asked register Network location
 */
private void handleActionStart(boolean isListenGPS, boolean isListenNetWork, final Context context,
        boolean recGPS, boolean recNetwork, final String prefixGTS) {
    // Define a listener that responds to location updates

    if (isRunning) {
        this.onDestroy();
    }
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    final boolean record = recGPS || recNetwork;

    locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            if (record) {
                //Log.d("GPSLOCA",location.toString());
                long timestamp = System.currentTimeMillis() * 1000;
                // If buffer have full size
                if (null == stringBuffer) {
                    stringBuffer = new StringBuffer();
                }
                if (stringBuffer.length() >= BUFFER_SIZE) {
                    emptyBuffer();
                }
                if (stringBuffer.length() > 0) {
                    stringBuffer.append("\n");
                }
                String fix = "";
                /**
                 if(prefixGTS.equals(new String()))
                 {
                 prefixGTS = "android";
                 }*/
                if (prefixGTS.length() != prefixGTS.lastIndexOf(".")) {
                    fix = ".";
                }
                String string = timestamp + "/" + location.getLatitude() + ":" + location.getLongitude() + "/ "
                        + prefixGTS + fix + location.getProvider() + "{" + "source=android" + "} true";
                stringBuffer.append(string);
                //Log.d("Location Handler", stringBuffer.toString());
            }
        }

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

        public void onProviderEnabled(String provider) {
        }

        public void onProviderDisabled(String provider) {
            emptyBuffer();
        }

        /**
         * empty current buffer
         */
        public void emptyBuffer() {
            if (null != stringBuffer) {
                //Log.d("LocationService", stringBuffer.toString());
                final StringBuffer buffer = new StringBuffer(stringBuffer);
                if (CollectService.isPostActive) {
                    FileService.writeToFile(buffer.toString(), context);
                } else {
                    if (CollectService.ws.isClosed()) {
                        FileService.writeToFile(buffer.toString(), context);
                    } else {
                        List<File> allFiles = FileService.getAllFiles("fill", context, true);
                        for (File file : allFiles) {
                            String data = FileService.readMetricFile(file);
                            if (CollectService.ws.writeData(data)) {
                                file.delete();
                            }
                        }
                        if (!CollectService.ws.writeData(buffer.toString())) {
                            FileService.writeToFile(buffer.toString(), context);
                        }
                    }
                }
                stringBuffer = new StringBuffer();
            }
        }
    };

    // Register the listener with the Location Manager to receive location updates
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    if (isListenGPS || recGPS) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, locationListener);
        setLocManager();
    }
    if (isListenNetWork || recNetwork) {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 10, locationListener);
        setLocManager();
    }
    //Log.d("LOCATIONB", locationManager.getAllProviders().toString());
    //Log.d("LOCATIONB", locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER).toString());
    isRunning = true;

}

From source file:com.patil.geobells.lite.MainActivity.java

public void checkLocationServicesEnabled() {
    LocationManager lm = null;/*from w  ww  . ja va  2 s .  c  om*/
    boolean gps_enabled = true, network_enabled = true;
    if (lm == null)
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    try {
        gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    } catch (Exception ex) {
    }
    try {
        network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex) {
    }

    if (!gps_enabled || !network_enabled) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(R.string.dialog_title_enable_locationservices);
        dialog.setMessage(getString(R.string.dialog_message_enable_locationservices));
        dialog.setCancelable(false);
        dialog.setPositiveButton(getString(R.string.dialog_button_open_location_settings),
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        paramDialogInterface.dismiss();
                        Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(myIntent);
                    }
                });
        dialog.setNegativeButton(getString(R.string.dialog_button_nothanks),
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        finish();
                    }
                });
        dialog.create().show();

    }
}

From source file:com.wirelessmoves.cl.MainActivity.java

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

    if (isListenerActive == false) {
        Tel.listen(MyListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
        isListenerActive = true;/*  w w w. j  a v  a 2s  .  c o  m*/

        /* start getting GPS information again */
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsListener);

    }

    /* prevent the screen lock after a timeout again */
    wl.acquire();
}

From source file:com.platform.middlewares.plugins.GeoLocationPlugin.java

private JSONObject getAuthorizationError(Context app) {
    String error = null;/*from w w w .j a v  a2 s.co  m*/

    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.upmoon.alexanderbean.barcrawlr.fragments.PlanSelectorFragment.java

private void updateLocation() {
    if (getActivity().checkCallingOrSelfPermission(
            "android.permission.ACCESS_FINE_LOCATION") == PackageManager.PERMISSION_GRANTED) {
        mLM = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);

        //gets last known location, low energy use, low effort
        Location location = mLM.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        //handles mildy rare case where device has no known last location
        if (!(location == null)) {
            mLongitude = location.getLongitude();
            mLatitude = location.getLatitude();
        } else {//from   www. j a  v a  2s .  c o m
            mLongitude = 0;
            mLatitude = 0;
        }
    }
}