Example usage for android.location LocationManager getLastKnownLocation

List of usage examples for android.location LocationManager getLastKnownLocation

Introduction

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

Prototype

@RequiresPermission(anyOf = { ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION })
public Location getLastKnownLocation(String provider) 

Source Link

Document

Returns a Location indicating the data from the last known location fix obtained from the given provider.

Usage

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();/*www  .  jav  a 2s.  c o 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.shafiq.myfeedle.core.MyfeedleCreatePost.java

protected void chooseAccounts() {
    // don't limit accounts to the widget...
    Cursor c = this.getContentResolver().query(Accounts.getContentUri(this),
            new String[] { Accounts._ID, ACCOUNTS_QUERY, Accounts.SERVICE }, null, null, null);
    if (c.moveToFirst()) {
        int i = 0;
        ;//www  .j  av a 2  s.  c  o m
        int count = c.getCount();
        final long[] accountIndexes = new long[count];
        final String[] accounts = new String[count];
        final boolean[] defaults = new boolean[count];
        final int[] accountServices = new int[count];
        while (!c.isAfterLast()) {
            long id = c.getLong(0);
            accountIndexes[i] = id;
            accounts[i] = c.getString(1);
            accountServices[i] = c.getInt(2);
            defaults[i++] = mAccountsService.containsKey(id);
            c.moveToNext();
        }
        mDialog = (new AlertDialog.Builder(this)).setTitle(R.string.accounts)
                .setMultiChoiceItems(accounts, defaults, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        if (isChecked) {
                            final long accountId = accountIndexes[which];
                            mAccountsService.put(accountId, accountServices[which]);
                            if (sLocationSupported.contains(accountServices[which])) {
                                if (mLat == null) {
                                    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 ((mLat != null) && (mLong != null)) {
                                    dialog.cancel();
                                    mDialog = (new AlertDialog.Builder(MyfeedleCreatePost.this))
                                            .setTitle(R.string.set_location)
                                            .setPositiveButton(android.R.string.ok,
                                                    new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            setLocation(accountId);
                                                            dialog.dismiss();
                                                        }
                                                    })
                                            .setNegativeButton(android.R.string.cancel,
                                                    new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            dialog.dismiss();
                                                        }
                                                    })
                                            .create();
                                    mDialog.show();
                                }
                            }
                        } else {
                            mAccountsService.remove(accountIndexes[which]);
                            mAccountsLocation.remove(accountIndexes[which]);
                            mAccountsTags.remove(accountIndexes[which]);
                        }
                    }
                }).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create();
        mDialog.show();
    }
    c.close();
}

From source file:org.odk.collect.android.activities.GeoTraceOsmMapActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.geotrace_osm_layout);
    setTitle(getString(R.string.geotrace_title)); // Setting title of the action

    mapView = (MapView) findViewById(R.id.geotrace_mapview);
    helper = new MapHelper(this, mapView, GeoTraceOsmMapActivity.this);
    mapView.setMultiTouchControls(true);
    mapView.setBuiltInZoomControls(true);
    mapView.getController().setZoom(zoomLevel);
    myLocationOverlay = new MyLocationNewOverlay(mapView);

    inflater = this.getLayoutInflater();
    traceSettingsView = inflater.inflate(R.layout.geotrace_dialog, null);
    polygonPolylineView = inflater.inflate(R.layout.polygon_polyline_dialog, null);
    timeDelay = (Spinner) traceSettingsView.findViewById(R.id.trace_delay);
    timeDelay.setSelection(3);// w w w.jav  a2  s  .co m
    timeUnits = (Spinner) traceSettingsView.findViewById(R.id.trace_scale);
    layersButton = (ImageButton) findViewById(R.id.layers);
    layersButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            helper.showLayersDialog(GeoTraceOsmMapActivity.this);

        }
    });

    locationButton = (ImageButton) findViewById(R.id.show_location);
    locationButton.setEnabled(false);
    locationButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            reset_trace_settings();
            showZoomDialog();
        }

    });

    clearButton = (ImageButton) findViewById(R.id.clear);
    clearButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            showClearDialog();

        }

    });

    ImageButton saveButton = (ImageButton) findViewById(R.id.geotrace_save);
    saveButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            if (mapMarkers.size() != 0) {
                alertDialog.show();
            } else {
                saveGeoTrace();
            }
        }
    });
    if (mapMarkers == null || mapMarkers.size() == 0) {
        clearButton.setEnabled(false);
    }
    manualCaptureButton = (Button) findViewById(R.id.manual_button);
    manualCaptureButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            addLocationMarker();
        }
    });
    pauseButton = (ImageButton) findViewById(R.id.pause);
    playButton = (ImageButton) findViewById(R.id.play);
    playButton.setEnabled(false);
    beenPaused = false;
    traceMode = 1;

    playButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            if (!playCheck) {
                if (!beenPaused) {
                    alert.show();
                } else {
                    RadioGroup rb = (RadioGroup) traceSettingsView.findViewById(R.id.radio_group);
                    int radioButtonID = rb.getCheckedRadioButtonId();
                    View radioButton = rb.findViewById(radioButtonID);
                    traceMode = rb.indexOfChild(radioButton);
                    if (traceMode == 0) {
                        setupManualMode();
                    } else if (traceMode == 1) {
                        setupAutomaticMode();
                    } else {
                        reset_trace_settings();
                    }
                }
                playCheck = true;
            } else {
                playCheck = false;
                startGeoTrace();
            }
        }
    });

    pauseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            playButton.setVisibility(View.VISIBLE);
            if (mapMarkers != null && mapMarkers.size() > 0) {
                clearButton.setEnabled(true);
            }
            pauseButton.setVisibility(View.GONE);
            manualCaptureButton.setVisibility(View.GONE);
            playCheck = true;
            modeActive = false;
            myLocationOverlay.disableFollowLocation();

            try {
                schedulerHandler.cancel(true);
            } catch (Exception e) {
                // Do nothing
            }
        }
    });

    overlayMapLayerListener();
    buildDialogs();
    Intent intent = getIntent();
    if (intent != null && intent.getExtras() != null) {
        if (intent.hasExtra(GeoTraceWidget.TRACE_LOCATION)) {
            String s = intent.getStringExtra(GeoTraceWidget.TRACE_LOCATION);
            playButton.setEnabled(false);
            clearButton.setEnabled(true);
            overlayIntentTrace(s);
            locationButton.setEnabled(true);
            //zoomToCentroid();
            zoomToBounds();

        }
    } else {
        myLocationOverlay.runOnFirstFix(centerAroundFix);
    }

    Button polygonSaveButton = (Button) polygonPolylineView.findViewById(R.id.polygon_save);
    polygonSaveButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mapMarkers.size() > 2) {
                createPolygon();
                alertDialog.dismiss();
                saveGeoTrace();
            } else {
                alertDialog.dismiss();
                showPolygonErrorDialog();
            }

        }
    });
    Button polylineSaveButton = (Button) polygonPolylineView.findViewById(R.id.polyline_save);
    polylineSaveButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            alertDialog.dismiss();
            saveGeoTrace();

        }
    });

    zoomDialogView = getLayoutInflater().inflate(R.layout.geoshape_zoom_dialog, null);

    zoomLocationButton = (Button) zoomDialogView.findViewById(R.id.zoom_location);
    zoomLocationButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            zoomToMyLocation();
            mapView.invalidate();
            zoomDialog.dismiss();
        }
    });

    zoomPointButton = (Button) zoomDialogView.findViewById(R.id.zoom_shape);
    zoomPointButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //zoomToCentroid();
            zoomToBounds();
            mapView.invalidate();
            zoomDialog.dismiss();
        }
    });

    mapView.invalidate();
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = locationManager.getProviders(true);
    for (String provider : providers) {
        if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) {
            locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            gpsOn = true;
        }
        if (provider.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)) {
            locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            networkOn = true;
        }
    }
    if (gpsOn) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    }
    if (networkOn) {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
    }
}

From source file:com.zainsoft.ramzantimetable.QiblaActivity.java

private void registerForGPS() {
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);/*from   w ww  .  j av a  2  s .c  o m*/
    criteria.setSpeedRequired(false);
    criteria.setCostAllowed(true);
    LocationManager locationManager = ((LocationManager) getSystemService(Context.LOCATION_SERVICE));
    String provider = locationManager.getBestProvider(criteria, true);

    if (provider != null) {
        locationManager.requestLocationUpdates(provider, MIN_LOCATION_TIME, MIN_LOCATION_DISTANCE,
                qiblaManager);
    }
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_LOCATION_TIME,
            MIN_LOCATION_DISTANCE, qiblaManager);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_LOCATION_TIME,
            MIN_LOCATION_DISTANCE, qiblaManager);
    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (location == null) {
        location = ((LocationManager) getSystemService(Context.LOCATION_SERVICE))
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
    }
    if (location != null) {
        qiblaManager.onLocationChanged(location);
    }

}

From source file:org.ohmage.activity.SurveyActivity.java

private void storeResponse() {

    //finalize photos
    for (int i = 0; i < mSurveyElements.size(); i++) {
        if (mSurveyElements.get(i) instanceof PhotoPrompt) {
            PhotoPrompt photoPrompt = (PhotoPrompt) mSurveyElements.get(i);
            final String uuid = (String) photoPrompt.getResponseObject();

            if (photoPrompt.isDisplayed() && !photoPrompt.isSkipped()) {
                File[] files = Campaign.getCampaignImageDir(this, mCampaignUrn).listFiles(new FilenameFilter() {

                    @Override//from   w w  w. j  ava  2 s .  c o m
                    public boolean accept(File dir, String filename) {
                        if (filename.contains("temp" + uuid)) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                });

                for (File f : files) {
                    f.renameTo(new File(Campaign.getCampaignImageDir(this, mCampaignUrn), uuid + ".jpg"));

                    // TODO: add thumbnail generation, oddly enough as a png
                }
            }
        }
    }

    SharedPreferencesHelper helper = new SharedPreferencesHelper(this);
    String username = helper.getUsername();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar now = Calendar.getInstance();
    String date = dateFormat.format(now.getTime());
    long time = now.getTimeInMillis();
    String timezone = TimeZone.getDefault().getID();

    LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (loc == null || System.currentTimeMillis() - loc.getTime() > SurveyGeotagService.LOCATION_STALENESS_LIMIT
            || loc.getAccuracy() > SurveyGeotagService.LOCATION_ACCURACY_THRESHOLD) {
        Log.w(TAG, "gps provider disabled or location stale or inaccurate");
        loc = null;
    }

    String surveyId = mSurveyId;

    //get launch context from trigger glue
    JSONObject surveyLaunchContextJson = new JSONObject();
    try {
        surveyLaunchContextJson.put("launch_time", mLaunchTime);
        surveyLaunchContextJson.put("active_triggers",
                TriggerFramework.getActiveTriggerInfo(this, mCampaignUrn, mSurveyTitle));
    } catch (JSONException e) {
        Log.e(TAG, "JSONException when trying to generate survey launch context json", e);
        throw new RuntimeException(e);
    }
    String surveyLaunchContext = surveyLaunchContextJson.toString();

    JSONArray responseJson = new JSONArray();
    JSONArray repeatableSetResponseJson = new JSONArray();
    JSONArray iterationResponseJson = new JSONArray();
    JSONObject itemJson = null;
    boolean inRepeatableSet = false;

    for (int i = 0; i < mSurveyElements.size(); i++) {
        if (mSurveyElements.get(i) instanceof Prompt) {
            if (!inRepeatableSet) {
                itemJson = new JSONObject();
                try {
                    itemJson.put("prompt_id", ((AbstractPrompt) mSurveyElements.get(i)).getId());
                    itemJson.put("value", ((AbstractPrompt) mSurveyElements.get(i)).getResponseObject());
                    Object extras = ((AbstractPrompt) mSurveyElements.get(i)).getExtrasObject();
                    if (extras != null) {
                        // as of now we don't actually have "extras" we only have "custom_choices" for the custom types
                        // so this is currently only used by single_choice_custom and multi_choice_custom
                        itemJson.put("custom_choices", extras);
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "JSONException when trying to generate response json", e);
                    throw new RuntimeException(e);
                }
                responseJson.put(itemJson);
            } else {
                JSONObject subItemJson = new JSONObject();
                try {
                    subItemJson.put("prompt_id", ((AbstractPrompt) mSurveyElements.get(i)).getId());
                    subItemJson.put("value", ((AbstractPrompt) mSurveyElements.get(i)).getResponseObject());
                    Object extras = ((AbstractPrompt) mSurveyElements.get(i)).getExtrasObject();
                    if (extras != null) {
                        // as of now we don't actually have "extras" we only have "custom_choices" for the custom types
                        // so this is currently only used by single_choice_custom and multi_choice_custom
                        subItemJson.put("custom_choices", extras);
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "JSONException when trying to generate response json", e);
                    throw new RuntimeException(e);
                }
                iterationResponseJson.put(subItemJson);
            }
        } else if (mSurveyElements.get(i) instanceof RepeatableSetHeader) {
            inRepeatableSet = true;
            if (i != 0 && (mSurveyElements.get(i - 1) instanceof RepeatableSetTerminator)
                    && ((RepeatableSetHeader) mSurveyElements.get(i)).getId()
                            .equals(((RepeatableSetTerminator) mSurveyElements.get(i - 1)).getId())) {
                //continue existing set
                iterationResponseJson = new JSONArray();
            } else {
                //start new set
                itemJson = new JSONObject();
                try {
                    itemJson.put("repeatable_set_id", ((RepeatableSetHeader) mSurveyElements.get(i)).getId());
                    itemJson.put("skipped", "false");
                    itemJson.put("not_displayed",
                            ((RepeatableSetHeader) mSurveyElements.get(i)).isDisplayed() ? "false" : "true");
                    repeatableSetResponseJson = new JSONArray();
                    iterationResponseJson = new JSONArray();
                } catch (JSONException e) {
                    Log.e(TAG, "JSONException when trying to generate response json", e);
                    throw new RuntimeException(e);
                }
            }
        } else if (mSurveyElements.get(i) instanceof RepeatableSetTerminator) {
            inRepeatableSet = false;
            repeatableSetResponseJson.put(iterationResponseJson);
            try {
                itemJson.put("responses", repeatableSetResponseJson);
            } catch (JSONException e) {
                Log.e(TAG, "JSONException when trying to generate response json", e);
                throw new RuntimeException(e);
            }
            if (!(i + 1 < mSurveyElements.size() && (mSurveyElements.get(i + 1) instanceof RepeatableSetHeader)
                    && ((RepeatableSetHeader) mSurveyElements.get(i + 1)).getId()
                            .equals(((RepeatableSetTerminator) mSurveyElements.get(i)).getId()))) {
                responseJson.put(itemJson);
            }
        }
    }
    String response = responseJson.toString();

    // insert the response, which indirectly populates the prompt response tables, etc.
    Response candidate = new Response();

    candidate.campaignUrn = mCampaignUrn;
    candidate.username = username;
    candidate.date = date;
    candidate.time = time;
    candidate.timezone = timezone;
    candidate.surveyId = surveyId;
    candidate.surveyLaunchContext = surveyLaunchContext;
    candidate.response = response;
    candidate.status = Response.STATUS_STANDBY;

    if (loc != null) {
        candidate.locationStatus = SurveyGeotagService.LOCATION_VALID;
        candidate.locationLatitude = loc.getLatitude();
        candidate.locationLongitude = loc.getLongitude();
        candidate.locationProvider = loc.getProvider();
        candidate.locationAccuracy = loc.getAccuracy();
        candidate.locationTime = loc.getTime();
    } else {
        candidate.locationStatus = SurveyGeotagService.LOCATION_UNAVAILABLE;
        candidate.locationLatitude = -1;
        candidate.locationLongitude = -1;
        candidate.locationProvider = null;
        candidate.locationAccuracy = -1;
        candidate.locationTime = -1;
        candidate.status = Response.STATUS_WAITING_FOR_LOCATION;
    }

    ContentResolver cr = getContentResolver();
    cr.insert(Responses.CONTENT_URI, candidate.toCV());

    // create an intent and broadcast it to any interested receivers
    Intent i = new Intent("org.ohmage.SURVEY_COMPLETE");

    i.putExtra(Responses.CAMPAIGN_URN, mCampaignUrn);
    i.putExtra(Responses.RESPONSE_USERNAME, username);
    i.putExtra(Responses.RESPONSE_DATE, date);
    i.putExtra(Responses.RESPONSE_TIME, time);
    i.putExtra(Responses.RESPONSE_TIMEZONE, timezone);

    if (loc != null) {
        i.putExtra(Responses.RESPONSE_LOCATION_STATUS, SurveyGeotagService.LOCATION_VALID);
        i.putExtra(Responses.RESPONSE_LOCATION_LATITUDE, loc.getLatitude());
        i.putExtra(Responses.RESPONSE_LOCATION_LONGITUDE, loc.getLongitude());
        i.putExtra(Responses.RESPONSE_LOCATION_PROVIDER, loc.getProvider());
        i.putExtra(Responses.RESPONSE_LOCATION_ACCURACY, loc.getAccuracy());
        i.putExtra(Responses.RESPONSE_LOCATION_TIME, loc.getTime());
    } else {
        i.putExtra(Responses.RESPONSE_LOCATION_STATUS, SurveyGeotagService.LOCATION_UNAVAILABLE);
        i.putExtra(Responses.RESPONSE_STATUS, Response.STATUS_WAITING_FOR_LOCATION);
    }

    i.putExtra(Responses.SURVEY_ID, surveyId);
    i.putExtra(Responses.RESPONSE_SURVEY_LAUNCH_CONTEXT, surveyLaunchContext);
    i.putExtra(Responses.RESPONSE_JSON, response);

    this.sendBroadcast(i);
}

From source file:org.mozilla.gecko.GeckoAppShell.java

public static void enableLocation(final boolean enable) {
    getMainHandler().post(new Runnable() {
        public void run() {
            LayerView v = GeckoApp.mAppContext.getLayerController().getView();

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

            if (enable) {
                Criteria criteria = new Criteria();
                String provider = lm.getBestProvider(criteria, true);
                if (provider == null)
                    return;

                Looper l = Looper.getMainLooper();
                Location loc = lm.getLastKnownLocation(provider);
                if (loc != null) {
                    GeckoApp.mAppContext.onLocationChanged(loc);
                }/*from www  .  j  a  v a  2 s.co  m*/
                lm.requestLocationUpdates(provider, 100, (float) .5, GeckoApp.mAppContext, l);
            } else {
                lm.removeUpdates(GeckoApp.mAppContext);
            }
        }
    });
}

From source file:com.scoreflex.Scoreflex.java

/**
 * Returns the Location as set in {@link setLocation(Location)} or the best
 * last known location of the {@link LocationManager} or null if permission
 * was not given.//from  w w  w.  ja  v  a  2s  . c  om
 */

public static Location getLocation() {
    if (null != sLocation)
        return sLocation;

    Context applicationContext = getApplicationContext();

    if (applicationContext == null)
        return null;

    LocationManager locationManager = (LocationManager) applicationContext
            .getSystemService(Context.LOCATION_SERVICE);
    try {
        Location locations[] = { locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER),
                locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER),
                locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER), };

        Location best = null;
        for (int i = 0; i < locations.length; i++) {

            // If this location is null, discard
            if (null == locations[i])
                continue;

            // If we have no best yet, use this first location
            if (null == best) {
                best = locations[i];
                continue;
            }

            // If this location is significantly older, discard
            long timeDelta = locations[i].getTime() - best.getTime();
            if (timeDelta < -1000 * 60 * 2)
                continue;

            // If we have no accuracy, discard
            if (0 == locations[i].getAccuracy())
                continue;

            // If this location is less accurate, discard
            if (best.getAccuracy() < locations[i].getAccuracy())
                continue;

            best = locations[i];
        }

        return best;
    } catch (java.lang.SecurityException e) {
        // Missing permission;
        return null;
    }
}

From source file:vn.co.taxinet.mobile.newactivity.MapActivity.java

private void displayLocation() {

    rider_send_request_information = (RelativeLayout) findViewById(R.id.rider_send_request_information);
    rider_send_request_information.setVisibility(View.GONE);

    rider_send_request_first_step = (RelativeLayout) findViewById(R.id.rider_send_request_first_step);
    rider_send_request_first_step.setVisibility(View.GONE);

    no_driver_nearby = (RelativeLayout) findViewById(R.id.no_driver_nearby);
    no_driver_nearby.setVisibility(View.GONE);

    rider_send_request_waiting_step = (RelativeLayout) findViewById(R.id.rider_send_request_waiting_step);
    rider_send_request_waiting_step.setVisibility(View.GONE);

    rider_send_request_driver_accept = (RelativeLayout) findViewById(R.id.rider_send_request_driver_accept);
    rider_send_request_driver_accept.setVisibility(View.GONE);

    pick_point = (RelativeLayout) findViewById(R.id.pick_point);
    pick_point.setVisibility(View.GONE);

    pick_start_point = (Button) findViewById(R.id.btn_pick_start_point);
    pick_end_point = (Button) findViewById(R.id.btn_pick_end_point);

    pick_start_point_value = (Button) findViewById(R.id.btn_pick_start_point_value);
    pick_end_point_value = (Button) findViewById(R.id.btn_pick_end_point_value);
    pick_start_point_value.setVisibility(View.GONE);
    pick_end_point_value.setVisibility(View.GONE);

    Button cancelWaitingRequest, cancelAcceptedRequest;
    cancelWaitingRequest = (Button) findViewById(R.id.btn_rider_cancel_waiting_request);
    cancelAcceptedRequest = (Button) findViewById(R.id.btn_rider_cancel_driver_accept_request);

    // Trip trip = databaseHandler.getTripStatus();

    tripBO = new TripBO();

    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();

    lastLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, true));
    Toast.makeText(getApplicationContext(), "111", Toast.LENGTH_SHORT).show();
    if (lastLocation != null) {
        getDriverBO = new GetDriverBO(this, "" + lastLocation.getLatitude(), "" + lastLocation.getLongitude(),
                googleMap);/*w  w w. j  a  v a2s  . c  om*/

        // for (int i = 0; i < listDriver.size(); i++) {
        // Driver driver = listDriver.get(i);
        // LatLng latLng = new LatLng(driver.getLatitude(),
        // driver.getLongitude());
        // MarkerOptions markerOptions = new MarkerOptions();
        // markerOptions.title(driver.getFirstName() + " "
        // + driver.getLastName());
        // markerOptions.snippet(distance);
        // markerOptions.position(latLng);
        // googleMap.addMarker(markerOptions);
        // }

        rider_current_position = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude());

        riderPosition = new MarkerOptions();
        riderPosition.title("U stand here");
        riderPosition.position(rider_current_position);
        googleMap.addMarker(riderPosition);

        // LatLng Taxi1 = new LatLng(21.009809, 105.523515);
        // LatLng Taxi2 = new LatLng(21.014917, 105.530317);
        // LatLng Taxi3 = new LatLng(21.010250, 105.532162);
        // final LatLng me = new LatLng(21.013475, 105.525425);
        //
        // MarkerOptions tx1 = new MarkerOptions();
        // tx1.title("Nguyn Vn A");
        // tx1.snippet("5KM");
        // tx1.position(Taxi1);
        // MarkerOptions tx2 = new MarkerOptions();
        // tx2.title("Nguyn Vn B");
        // tx2.snippet("1KM");
        // tx2.position(Taxi2);
        // MarkerOptions tx3 = new MarkerOptions();
        // tx3.title("Nguyn Vn C");
        // tx3.snippet("2KM");
        // tx3.position(Taxi3);
        // MarkerOptions me1 = new MarkerOptions();
        // me1.title("Here I stand");
        // me1.position(me);
        //
        // googleMap.addMarker(tx1);
        // googleMap.addMarker(tx2);
        // googleMap.addMarker(tx3);
        // googleMap.addMarker(me1);

        googleMap.setMyLocationEnabled(true);

        googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {

            @Override
            public boolean onMarkerClick(Marker marker) {
                // TODO Auto-generated method stub
                List<Driver> drivers = AppController.getListDrivers();
                for (int i = 0; i < drivers.size(); i++) {
                    LatLng latLng = new LatLng(drivers.get(i).getLatitude(), drivers.get(i).getLongitude());
                    if (latLng.equals(marker.getPosition())) {
                        driver = drivers.get(i);
                    }
                }

                // Getting URL to the Google Directions API
                String url = getDirectionsUrl(rider_current_position, marker.getPosition());

                DownloadTask downloadTask = new DownloadTask();

                // Start downloading json data from Google Directions API
                downloadTask.execute(url);
                Toast.makeText(getApplicationContext(), "" + AppController.getDistance(), 3).show();

                rider_send_request_information.setVisibility(View.VISIBLE);
                rider_send_request_first_step.setVisibility(View.VISIBLE);
                pick_point.setVisibility(View.VISIBLE);

                pick_start_point_value = (Button) findViewById(R.id.btn_pick_start_point_value);
                pick_end_point_value = (Button) findViewById(R.id.btn_pick_end_point_value);

                // Pich Start Point
                pick_start_point.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        pick_start_point_value.setVisibility(View.VISIBLE);
                        // googleMap.clear();
                        PointLongitude = null;
                        PointLatitude = null;
                        googleMap.setOnMapClickListener(new OnMapClickListener() {

                            @Override
                            public void onMapClick(LatLng arg0) {
                                Location targetLocation = new Location("");
                                targetLocation.setLatitude(arg0.latitude);
                                targetLocation.setLongitude(arg0.longitude);

                                PointLongitude = arg0.longitude;
                                PointLatitude = arg0.latitude;

                                if (lastMarker2 != null) {
                                    lastMarker2.remove();
                                }
                                MarkerOptions startPoint = new MarkerOptions();
                                startPoint.position(arg0);
                                startPoint.icon(BitmapDescriptorFactory
                                        .defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                                startPoint.title("Start Point");
                                Marker marker = googleMap.addMarker(startPoint);
                                lastMarker2 = marker;

                            }
                        });
                        pick_start_point_value.setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                Toast.makeText(getApplicationContext(), "" + PointLatitude, Toast.LENGTH_SHORT)
                                        .show();
                                if (PointLatitude != null & PointLongitude != null) {
                                    start_lat = PointLatitude;
                                    start_lng = PointLongitude;
                                } else
                                    Toast.makeText(getApplicationContext(), "Please pick Start Point",
                                            Toast.LENGTH_LONG).show();
                                pick_start_point_value.setVisibility(View.GONE);
                                pick_start_point.setText("Repick");

                            }
                        });

                    }
                });

                // Pick End Point

                pick_end_point.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        pick_end_point_value.setVisibility(View.VISIBLE);
                        // googleMap.clear();
                        PointLongitude = null;
                        PointLatitude = null;
                        googleMap.setOnMapClickListener(new OnMapClickListener() {

                            @Override
                            public void onMapClick(LatLng arg0) {

                                PointLongitude = arg0.longitude;
                                PointLatitude = arg0.latitude;

                                if (lastMarker3 != null) {
                                    lastMarker3.remove();
                                }
                                MarkerOptions endPoint = new MarkerOptions();
                                endPoint.position(arg0);
                                endPoint.icon(BitmapDescriptorFactory
                                        .defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
                                endPoint.title("End Point");
                                Marker marker = googleMap.addMarker(endPoint);
                                lastMarker3 = marker;

                            }
                        });
                        pick_end_point_value.setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                if (PointLatitude != null & PointLongitude != null) {
                                    end_lat = PointLatitude;
                                    end_lng = PointLongitude;
                                } else
                                    Toast.makeText(getApplicationContext(), "Please pick End Point",
                                            Toast.LENGTH_LONG).show();
                                pick_end_point_value.setVisibility(View.GONE);
                                pick_end_point.setText("Repick");

                            }
                        });

                    }
                });

                send_request = (Button) findViewById(R.id.btn_rider_send_request);
                send_request.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (Utils.isConnectingToInternet(getApplicationContext())) {
                            DatabaseHandler handler = new DatabaseHandler(getApplicationContext());
                            Rider rider = handler.findRider();
                            driverid = driver.getId();
                            riderid = rider.getId();
                            tripBO.CreateTrip(MapActivity.this, riderid, driverid, "" + start_lat,
                                    "" + start_lng, "" + end_lat, "" + end_lng);
                            rider_send_request_first_step.setVisibility(View.GONE);
                            removeLayout();
                            rider_send_request_waiting_step.setVisibility(View.VISIBLE);
                            handler.createTrip(AppController.getTripID(), TripStatus.NEW_TRIP);
                        } else {
                            // show error message
                            alert.showAlertDialog(MapActivity.this,
                                    getResources().getString(R.string.alert_internet_error_title),
                                    getResources().getString(R.string.alert_internet_error_message), false);
                        }

                    }
                });

                return false;
            }
        });

        // Cancel Waiting Request

        cancelWaitingRequest.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                DatabaseHandler handler = new DatabaseHandler(getApplicationContext());
                Rider rider = handler.findRider();
                riderid = rider.getId();
                tripBO.UpdateTrip(MapActivity.this, AppController.getTripID(), riderid, TripStatus.CANCELLED);
                rider_send_request_waiting_step.setVisibility(View.GONE);

                // rider_send_request_driver_accept.setVisibility(View.VISIBLE);

            }
        });

        // Cancel Accepted Request

        cancelAcceptedRequest.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                DatabaseHandler handler = new DatabaseHandler(getApplicationContext());
                Rider rider = handler.findRider();
                riderid = rider.getId();
                tripBO.UpdateTrip(MapActivity.this, AppController.getTripID(), riderid, TripStatus.CANCELLED);
                rider_send_request_driver_accept.setVisibility(View.GONE);

            }
        });

        googleMap.setOnMapClickListener(new OnMapClickListener() {

            @Override
            public void onMapClick(LatLng arg0) {
                // TODO Auto-generated method stub

                // Hide infor box
                rider_send_request_first_step.setVisibility(View.GONE);
                rider_send_request_information.setVisibility(View.GONE);

                // Location targetLocation = new Location("");
                // targetLocation.setLatitude(arg0.latitude);
                // targetLocation.setLongitude(arg0.longitude);
                //
                // float distanceInMeters = targetLocation
                // .distanceTo(lastLocation);
                // if (distanceInMeters > 1000) {
                // Toast.makeText(getApplicationContext(), "Out of range",
                // Toast.LENGTH_SHORT).show();
                // }
                // Toast.makeText(getApplicationContext(),
                // " " + arg0.latitude + "  " + arg0.longitude,
                // Toast.LENGTH_SHORT).show();
                // if (lastMarker != null) {
                // lastMarker.remove();
                // }
                // MarkerOptions hereIStand = new MarkerOptions();
                // hereIStand.position(arg0);
                // Marker marker = googleMap.addMarker(hereIStand);
                // lastMarker = marker;

            }
        });

        LatLng latLng = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude());
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13));

        CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng) // Sets the center of the map to location
                // user
                .zoom(15) // Sets the zoom
                .build(); // Creates a CameraPosition from the builder
        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    }
}

From source file:com.example.angel.parkpanda.MainActivity.java

public Location moveMyPosCamera() {

    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return null;
    }//from w ww . j  av  a 2s  .  com
    Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (myLocation == null) {
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        String provider = lm.getBestProvider(criteria, true);
        myLocation = lm.getLastKnownLocation(provider);
    }
    return myLocation;
}

From source file:fashiome.android.fragments.MapListFragment.java

private LatLng getLastKnownLocation(boolean isMoveMarker) {
    LocationManager lm = (LocationManager) AppStarter.getAppContext()
            .getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_LOW);
    String provider = lm.getBestProvider(criteria, true);
    if (provider == null) {
        return null;
    }//from w w w .  j  av a  2 s .  com
    Activity activity = getActivity();
    if (activity == null) {
        return null;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (activity.checkSelfPermission(
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && activity.checkSelfPermission(
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return null;
        }
    }
    Location loc = lm.getLastKnownLocation(provider);
    if (loc != null) {
        LatLng latLng = new LatLng(loc.getLatitude(), loc.getLongitude());
        if (isMoveMarker) {
            moveMarker(latLng);
        }
        return latLng;
    }
    return null;
}