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:it.sasabz.android.sasabus.fragments.OnlineSearchFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    this.inflater_glob = inflater;
    result = inflater.inflate(R.layout.online_search_layout, container, false);

    Date datum = new Date();
    SimpleDateFormat simple = new SimpleDateFormat("dd.MM.yyyy HH:mm");

    TextView datetime = (TextView) result.findViewById(R.id.time);
    String datetimestring = "";

    datetimestring = simple.format(datum);

    datetime.setText(datetimestring);/*from  w  w  w  .  jav  a  2  s . co m*/

    Button search = (Button) result.findViewById(R.id.search);

    search.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AutoCompleteTextView from = (AutoCompleteTextView) result.findViewById(R.id.from_text);
            AutoCompleteTextView to = (AutoCompleteTextView) result.findViewById(R.id.to_text);
            TextView datetime = (TextView) result.findViewById(R.id.time);

            String from_txt = getThis().getResources().getString(R.string.from_txt);

            if ((!from.getText().toString().trim().equals("")
                    || !from.getHint().toString().trim().equals(from_txt))
                    && !to.getText().toString().trim().equals("")) {
                //Intent getSelect = new Intent(getThis().getActivity(), OnlineSelectStopActivity.class);
                String fromtext = "";
                if (from.getText().toString().trim().equals(""))
                    fromtext = from.getHint().toString();
                else
                    fromtext = from.getText().toString();
                String totext = to.getText().toString();
                fromtext = "(" + fromtext.replace(" -", ")");
                totext = "(" + totext.replace(" -", ")");
                Fragment fragment = new OnlineSelectFragment(fromtext, totext, datetime.getText().toString());
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction ft = fragmentManager.beginTransaction();

                Fragment old = fragmentManager.findFragmentById(R.id.onlinefragment);
                if (old != null) {
                    ft.remove(old);
                }
                ft.add(R.id.onlinefragment, fragment);
                ft.addToBackStack(null);
                ft.commit();
                fragmentManager.executePendingTransactions();
            }
        }
    });

    datetime.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            // Create the dialog
            final Dialog mDateTimeDialog = new Dialog(getThis().getActivity());
            // Inflate the root layout
            final RelativeLayout mDateTimeDialogView = (RelativeLayout) inflater_glob
                    .inflate(R.layout.date_time_dialog, null);
            // Grab widget instance
            final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView
                    .findViewById(R.id.DateTimePicker);
            TextView dt = (TextView) result.findViewById(R.id.time);
            String datetimestring = dt.getText().toString();

            SimpleDateFormat datetimeformat = new SimpleDateFormat("dd.MM.yyyy HH:mm");
            Date datetime = null;
            try {
                datetime = datetimeformat.parse(datetimestring);
            } catch (Exception e) {
                ;
            }
            mDateTimePicker.updateTime(datetime.getHours(), datetime.getMinutes());
            mDateTimePicker.updateDate(datetime.getYear() + 1900, datetime.getMonth(), datetime.getDate());
            // Check is system is set to use 24h time (this doesn't seem to
            // work as expected though)
            final String timeS = android.provider.Settings.System.getString(
                    getThis().getActivity().getContentResolver(), android.provider.Settings.System.TIME_12_24);
            final boolean is24h = !(timeS == null || timeS.equals("12"));

            ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime))
                    .setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            mDateTimePicker.clearFocus();
                            String datetimestring = "";
                            int day = mDateTimePicker.get(Calendar.DAY_OF_MONTH);
                            int month = mDateTimePicker.get(Calendar.MONTH) + 1;
                            int year = mDateTimePicker.get(Calendar.YEAR);
                            int hour = 0;
                            int min = 0;
                            int append = 0;
                            if (mDateTimePicker.is24HourView()) {
                                hour = mDateTimePicker.get(Calendar.HOUR_OF_DAY);
                                min = mDateTimePicker.get(Calendar.MINUTE);
                            } else {
                                hour = mDateTimePicker.get(Calendar.HOUR);
                                min = mDateTimePicker.get(Calendar.MINUTE);
                                if (mDateTimePicker.get(Calendar.AM_PM) == Calendar.AM) {
                                    append = 1;
                                } else {
                                    append = 2;
                                }
                            }
                            if (day < 10) {
                                datetimestring += "0";
                            }
                            datetimestring += (day + ".");
                            if (month < 10) {
                                datetimestring += "0";
                            }
                            datetimestring += (month + "." + year + " ");
                            if (hour < 10) {
                                datetimestring += "0";
                            }
                            datetimestring += (hour + ":");
                            if (min < 10) {
                                datetimestring += "0";
                            }
                            datetimestring += min;

                            switch (append) {
                            case 1:
                                datetimestring += " AM";
                                break;
                            case 2:
                                datetimestring += " PM";
                                break;
                            }

                            TextView time = (TextView) result.findViewById(R.id.time);
                            time.setText(datetimestring);
                            mDateTimeDialog.dismiss();
                        }
                    });
            // Cancel the dialog when the "Cancel" button is clicked
            ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog))
                    .setOnClickListener(new View.OnClickListener() {

                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            mDateTimeDialog.cancel();
                        }
                    });

            // Reset Date and Time pickers when the "Reset" button is
            // clicked
            ((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime))
                    .setOnClickListener(new View.OnClickListener() {

                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            mDateTimePicker.reset();
                        }
                    });

            // Setup TimePicker
            mDateTimePicker.setIs24HourView(is24h);
            // No title on the dialog window
            mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            // Set the dialog content view
            mDateTimeDialog.setContentView(mDateTimeDialogView);
            // Display the dialog
            mDateTimeDialog.show();
        }

    });

    ImageButton datepicker = (ImageButton) result.findViewById(R.id.datepicker);

    datepicker.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            // Create the dialog
            final Dialog mDateTimeDialog = new Dialog(getThis().getActivity());
            // Inflate the root layout
            final RelativeLayout mDateTimeDialogView = (RelativeLayout) inflater_glob
                    .inflate(R.layout.date_time_dialog, null);
            // Grab widget instance
            final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView
                    .findViewById(R.id.DateTimePicker);
            TextView dt = (TextView) result.findViewById(R.id.time);
            String datetimestring = dt.getText().toString();
            SimpleDateFormat datetimeformat = new SimpleDateFormat("dd.MM.yyyy HH:mm");
            Date datetime = null;
            try {
                datetime = datetimeformat.parse(datetimestring);
            } catch (Exception e) {
                ;
            }
            mDateTimePicker.updateTime(datetime.getHours(), datetime.getMinutes());
            mDateTimePicker.updateDate(datetime.getYear() + 1900, datetime.getMonth(), datetime.getDate());
            // Check is system is set to use 24h time (this doesn't seem to
            // work as expected though)
            final String timeS = android.provider.Settings.System.getString(
                    getThis().getActivity().getContentResolver(), android.provider.Settings.System.TIME_12_24);
            final boolean is24h = !(timeS == null || timeS.equals("12"));

            // Update demo TextViews when the "OK" button is clicked
            ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime))
                    .setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            mDateTimePicker.clearFocus();
                            String datetimestring = "";
                            int day = mDateTimePicker.get(Calendar.DAY_OF_MONTH);
                            int month = mDateTimePicker.get(Calendar.MONTH) + 1;
                            int year = mDateTimePicker.get(Calendar.YEAR);
                            int hour = 0;
                            int min = 0;
                            int append = 0;
                            if (mDateTimePicker.is24HourView()) {
                                hour = mDateTimePicker.get(Calendar.HOUR_OF_DAY);
                                min = mDateTimePicker.get(Calendar.MINUTE);
                            } else {
                                hour = mDateTimePicker.get(Calendar.HOUR);
                                min = mDateTimePicker.get(Calendar.MINUTE);
                                if (mDateTimePicker.get(Calendar.AM_PM) == Calendar.AM) {
                                    append = 1;
                                } else {
                                    append = 2;
                                }
                            }
                            if (day < 10) {
                                datetimestring += "0";
                            }
                            datetimestring += (day + ".");
                            if (month < 10) {
                                datetimestring += "0";
                            }
                            datetimestring += (month + "." + year + " ");
                            if (hour < 10) {
                                datetimestring += "0";
                            }
                            datetimestring += (hour + ":");
                            if (min < 10) {
                                datetimestring += "0";
                            }
                            datetimestring += min;

                            switch (append) {
                            case 1:
                                datetimestring += " AM";
                                break;
                            case 2:
                                datetimestring += " PM";
                                break;
                            }

                            TextView time = (TextView) result.findViewById(R.id.time);
                            time.setText(datetimestring);
                            mDateTimeDialog.dismiss();
                        }
                    });
            // Cancel the dialog when the "Cancel" button is clicked
            ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog))
                    .setOnClickListener(new View.OnClickListener() {

                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            mDateTimeDialog.cancel();
                        }
                    });

            // Reset Date and Time pickers when the "Reset" button is
            // clicked
            ((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime))
                    .setOnClickListener(new View.OnClickListener() {

                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            mDateTimePicker.reset();
                        }
                    });

            // Setup TimePicker
            mDateTimePicker.setIs24HourView(is24h);
            // No title on the dialog window
            mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            // Set the dialog content view
            mDateTimeDialog.setContentView(mDateTimeDialogView);
            // Display the dialog
            mDateTimeDialog.show();
        }

    });
    from = (AutoCompleteTextView) result.findViewById(R.id.from_text);
    to = (AutoCompleteTextView) result.findViewById(R.id.to_text);

    from.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            InputMethodManager mgr = (InputMethodManager) getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            mgr.hideSoftInputFromWindow(from.getWindowToken(), 0);
        }
    });

    to.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            InputMethodManager mgr = (InputMethodManager) getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            mgr.hideSoftInputFromWindow(to.getWindowToken(), 0);
        }
    });

    LocationManager locman = (LocationManager) this.getActivity().getSystemService(Context.LOCATION_SERVICE);
    Location lastloc = locman.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (MySQLiteDBAdapter.exists(this.getActivity())) {
        if (lastloc == null) {
            lastloc = locman.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
        if (lastloc != null) {
            try {
                Palina palina = PalinaList.getPalinaGPS(lastloc);
                if (palina != null) {
                    from.setHint(palina.toString());
                }
            } catch (Exception e) {
                Log.e("HomeActivity", "Fehler bei der Location", e);
            }
        } else {
            Log.v("HomeActivity", "No location found!!");
        }
        Vector<DBObject> palinalist = PalinaList.getNameList();
        MyAutocompleteAdapter adapterfrom = new MyAutocompleteAdapter(this.getActivity(),
                android.R.layout.simple_list_item_1, palinalist);
        MyAutocompleteAdapter adapterto = new MyAutocompleteAdapter(this.getActivity(),
                android.R.layout.simple_list_item_1, palinalist);

        from.setAdapter(adapterfrom);
        to.setAdapter(adapterto);
        InputMethodManager mgr = (InputMethodManager) getActivity()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        mgr.hideSoftInputFromWindow(from.getWindowToken(), 0);
        mgr.hideSoftInputFromWindow(to.getWindowToken(), 0);
    }
    Button favorites = (Button) result.findViewById(R.id.favorites);
    favorites.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            SelectFavoritenDialog dialog = new SelectFavoritenDialog(getThis());
            dialog.show();
        }
    });

    Button mappicker = (Button) result.findViewById(R.id.map);
    mappicker.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), MapSelectActivity.class);
            startActivityForResult(intent, REQUESTCODE_ACTIVITY);
        }
    });
    return result;
}

From source file:de.sindzinski.wetter.MainActivity.java

public Location getLocation() {
    Location location = null;/*ww  w  . ja v a2s. co m*/
    String provider = "";
    String locationSetting = "";

    if (!checkAndAskForPermission()) {
        return null;
    }

    try {
        // Get the location manager
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // Define the criteria how to select the locatioin provider -> use
        // default
        Criteria criteria = new Criteria();
        if (locationManager != null) {
            provider = locationManager.getBestProvider(criteria, false);
            location = locationManager.getLastKnownLocation(provider);
        }

    } catch (Exception ex) {
        Log.e(LOG_TAG, "Error creating location service: " + ex.getMessage());
    }

    return location;
}

From source file:com.ht.app.RestaurantsActivity.java

private Location getLastKnownLocation() {
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    String provider = lm.getBestProvider(criteria, true);
    if (provider == null) {
        return null;
    }/* w  w  w .jav a 2s  .  c  om*/
    return lm.getLastKnownLocation(provider);
}

From source file:havidarou.com.appgpsqr.MapsActivity.java

/**
 * Manipulates the map once available./*from  w  w w  .  j a v a  2 s  . c  o m*/
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    // Add a marker to the new target
    if (latitude != 0.0 && longitude != 0.0) { // Checking if we have read a code
        LatLng target = new LatLng(latitude, longitude);
        mMap.addMarker(new MarkerOptions().position(target).title("New target!"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(target));
        mMap.setMyLocationEnabled(true);
        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) {
            // 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;
        }

        Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        longitude = location.getLongitude();
        latitude = location.getLatitude();
        // Call the route class to calculate a route
        route = new Route();
        // And the we draw it on the map
        route.drawRoute(mMap, MapsActivity.this, new LatLng(latitude, longitude), target, "es");
    }
}

From source file:it.unipr.informatica.autobusparma.MappaFragment.java

public Location getLocation(long MIN_DISTANCE, long MIN_TIME) {
    Location location = null;//from  w  ww.  j  a  v  a2 s  .  c  o m
    try {
        LocationManager locationManager = (LocationManager) getActivity()
                .getSystemService(Context.LOCATION_SERVICE);
        // getting GPS status e network
        boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE,
                        this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE,
                            this);
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    }
                }
            }
        }

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

    return location;
}

From source file:org.runnerup.tracker.component.TrackerGPS.java

@Override
public ResultCode onConnecting(final Callback callback, Context context) {
    if (ContextCompat.checkSelfPermission(this.tracker,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        mWithoutGps = true;/*  ww w  .  j av  a2 s .  c om*/
    }
    try {
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        frequency_ms = Integer
                .valueOf(preferences.getString(context.getString(R.string.pref_pollInterval), "500"));
        if (!mWithoutGps) {
            String frequency_meters = preferences.getString(context.getString(R.string.pref_pollDistance), "5");
            lm.requestLocationUpdates(GPS_PROVIDER, frequency_ms, Integer.valueOf(frequency_meters), tracker);
            mGpsStatus = new GpsStatus(context);
            mGpsStatus.start(this);
            mConnectCallback = callback;
            return ResultCode.RESULT_PENDING;
        } else {
            String list[] = { GPS_PROVIDER, NETWORK_PROVIDER, PASSIVE_PROVIDER };
            mLastLocation = null;
            for (String s : list) {
                Location tmp = lm.getLastKnownLocation(s);
                if (mLastLocation == null || tmp.getTime() > mLastLocation.getTime()) {
                    mLastLocation = tmp;
                }
            }
            if (mLastLocation != null) {
                mLastLocation.removeSpeed();
                mLastLocation.removeAltitude();
                mLastLocation.removeAccuracy();
                mLastLocation.removeBearing();
            }
            gpsLessLocationProvider.run();
            return ResultCode.RESULT_OK;
        }

    } catch (Exception ex) {
        return ResultCode.RESULT_ERROR;
    }
}

From source file:com.RSMSA.policeApp.OffenceReportForm.java

/**
 * get the last known location from a specific provider (network/gps)
 *///www. j a v a 2  s  . c  o m
private Location getLocationByProvider(String provider) {
    Location location = null;
    LocationManager locationManager = (LocationManager) getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);
    try {
        if (locationManager.isProviderEnabled(provider)) {
            location = locationManager.getLastKnownLocation(provider);
        }
    } catch (IllegalArgumentException e) {
        Log.d(TAG, "Cannot acces Provider " + provider);
    }
    return location;
}

From source file:com.piusvelte.sonet.core.SonetCreatePost.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int itemId = item.getItemId();
    if (itemId == R.id.menu_post_accounts)
        chooseAccounts();/* w  w  w  .j ava 2s.c om*/
    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) SonetCreatePost.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.njlabs.amrita.aid.about.Amrita.java

public void directions_cbe(View view) {
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, false);
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;/*from  w  w w  .j  a va2  s  . co m*/
    }

    LocationListener loc_listener = new LocationListener() {
        public void onLocationChanged(Location l) {
        }

        public void onProviderEnabled(String p) {
        }

        public void onProviderDisabled(String p) {
        }

        public void onStatusChanged(String p, int status, Bundle extras) {
        }
    };
    locationManager.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
    Location location = locationManager.getLastKnownLocation(bestProvider);

    double lat;
    double lon;
    try {
        lat = location.getLatitude();
        lon = location.getLongitude();
    } catch (NullPointerException e) {
        lat = -1.0;
        lon = -1.0;
    }
    Uri uri = Uri.parse(
            "http://maps.google.com/maps?f=d&saddr=" + lat + "," + lon + "&daddr=10.900539,76.902806&hl=en");
    Intent it = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(it);

}

From source file:com.piusvelte.sonet.core.SonetCreatePost.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;
        ;/* w w  w.ja  v  a  2s .  com*/
        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) SonetCreatePost.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(SonetCreatePost.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();
}