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:com.packpublishing.asynchronousandroid.chapter11.LocationActivity.java

@Override
public void onResume() {
    super.onResume();
    //EventBus.getDefault().register(this);
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Log.e(TAG, "Permission not granted and finishing...");
        finish();//from   w  w  w  . j  a va2 s . co  m
    }
    Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (location != null) {
        EventBus.getDefault().postSticky(new LocationEvent(location.getLatitude(), location.getLongitude()));
    }
    // Request a location update only if  device changed
    // must move before another update will be sent, in meters.
    manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3600, 100, listener);
}

From source file:com.geoffreybuttercrumbs.arewethereyet.ZonePicker.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
    setContentView(R.layout.main);//from www.ja  v a  2s .c  om

    // Setup the map
    setUpMapIfNeeded();
    AlarmOverlay alarmView = (AlarmOverlay) findViewById(R.id.alarm_overlay);
    alarmView.setMap(mMap, this);

    // Set the Behind View
    setBehindContentView(R.layout.menu_frame);
    FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
    mFrag = new DrawerFragment();
    t.replace(R.id.menu_frame, mFrag);
    t.commit();

    // customize the SlidingMenu
    SlidingMenu sm = getSlidingMenu();
    sm.setShadowWidthRes(R.dimen.shadow_width);
    sm.setShadowDrawable(R.drawable.shadow);
    sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
    sm.setFadeDegree(0.35f);
    sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    //Stop existing alarms
    stopService(new Intent(ZonePicker.this, AlarmService.class));

    //Reset to default ring tone. (Otherwise it is silent!)
    initTone();

    // Acquire a reference to the system Location Manager
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    crit.setAccuracy(Criteria.ACCURACY_FINE);
    Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, updateTime, updateRange, this);

    //If system has a last known location, use that...
    if (lastKnownLocation != null) {
        zone = new Zone(lastKnownLocation, 1000);
        animateTo(zone.getLocation());
        alarmView.setZone(zone);
    }
    //Else use an arbitrary point
    else {
        Location tempLocation = new Location("");
        tempLocation.setLatitude(42.36544);
        tempLocation.setLongitude(-71.103644);
        zone = new Zone(tempLocation, 1000);
        animateTo(zone.getLocation());
        alarmView.setZone(zone);
    }

    getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.ab_bg_black));
}

From source file:com.example.android.touroflondon.MainActivity.java

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

    //Verify that Google Play Services is available
    int playStatus = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());

    if (playStatus != ConnectionResult.SUCCESS) {
        // Google Play services is not available, prompt user and close application when dialog is dismissed
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(playStatus, this, 0);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override/*from  w  w  w. j a  va 2s  .co m*/
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        dialog.show();

        // Hide all active fragments
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.hide(mMapFragment);
        if (mPoiListFragment != null) {
            ft.hide(mPoiListFragment);
        }
        ft.commit();

    } else {

        // Getting reference to the SupportMapFragment of activity_main.xml
        TourMapFragment fm = (TourMapFragment) getFragmentManager().findFragmentById(R.id.fragment_map);

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

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

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

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 20000, 0, mMapFragment);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 20000, 0, mMapFragment);
        //            Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        // Make sure active fragments are shown when returning from Play Services dialog interaction
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.show(mMapFragment);
        if (mPoiListFragment != null) {
            ft.show(mPoiListFragment);
        }
        ft.commit();

    }

}

From source file:edu.neu.madcourse.kevinpacheco.butterflycatcher.MainActivity.java

private void setUpMap() {

    if (myMap == null) {
        SupportMapFragment myMapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        myMap = myMapFragment.getMap();//from  w  w w.ja v  a2s . c  o m
        myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    }
    if (myMap != null) {
        //add some code here to initialize map

        myMap.setMyLocationEnabled(true);
        myMap.setOnMyLocationChangeListener(this);

        myMap.getUiSettings().setZoomControlsEnabled(false);
        myMap.getUiSettings().setZoomGesturesEnabled(false);

        myMap.getUiSettings().setMyLocationButtonEnabled(false);

        locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
        String provider = locationmanager.getBestProvider(new Criteria(), true);

        Log.d(TAG, "provider = " + provider);

        if (provider == null || !locationmanager.isProviderEnabled(LocationManager.GPS_PROVIDER))
            onProviderDisabled(provider);

        if (provider != null) {
            Log.d(TAG, "locationmanager.getLastKnownLocation(provider) = "
                    + locationmanager.getLastKnownLocation(provider));
            LOCATION = locationmanager.getLastKnownLocation(provider);

            Runnable showWaitDialog = new Runnable() {
                @Override
                public void run() {
                    while (LOCATION == null) {
                        // Wait for first location fix (do nothing until LOCATION != null)
                    }
                    // After receiving first location fix dismiss the progress dialog
                    dialog.dismiss();
                }
            };
            // Create a dialog to let the user know that we're waiting for a location fix
            dialog = ProgressDialog.show(this, "Please wait.", "Retrieving location...", true);
            Thread t = new Thread(showWaitDialog);
            t.start();

            Log.d(TAG, "Map location = " + getLocation());

            if (getLocation() != null)
                animateCamera(getLocation(), birdseyeOn);

        }

    }

    myMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

        @Override
        public void onMapClick(LatLng arg0) {
            Log.d(TAG, "You click on " + arg0);
        }
    });
}

From source file:com.adampmarshall.speedo.LocationActivity.java

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

    // Check if the GPS setting is currently enabled on the device.
    // This verification should be done during onStart() because the system
    // calls this method
    // when the user returns to the activity, which ensures the desired
    // location provider is
    // enabled each time the activity resumes from the stopped state.
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

    if (!gpsEnabled) {
        // Build an alert dialog here that requests that the user enable
        // the location services, then when the user clicks the "OK" button,
        // call enableLocationSettings()
        new EnableGpsDialogFragment().show(getSupportFragmentManager(), "enableGpsDialog");
    }//from   w  w w .  j  a v a  2 s . co m
}

From source file:tcc.iesgo.activity.ClientMapActivity.java

public void showMap(Location location) throws JSONException {
    if (location == null)
        location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); //ltimo local registrado

    minLatitude = Integer.MAX_VALUE;
    maxLatitude = Integer.MIN_VALUE;
    minLongitude = Integer.MAX_VALUE;
    maxLongitude = Integer.MIN_VALUE;

    //Rotina p/ atualizar os objetos do mapa
    Overlay obj = mapOverlays.get(0); //Posio atual do usurio
    mapOverlays.clear(); //Limpa Overlays do mapa
    mapOverlays.add(obj); //Adiciona o usuario no mapa
    mapView.invalidate(); //Atualiza o mapa
    //Fim rotina/*from   w w w. j a v  a 2 s . co m*/

    //GeoPoint da posio atual do usurio
    geoActual = new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6));

    String taxis = getTaxis(location); //Json

    int length = getJsonResult(taxis, "id").length;
    String[] ids = new String[length];
    ids = getJsonResult(taxis, "id");
    String[] distances = new String[length];
    distances = getJsonResult(taxis, "distance");
    String[] latitudes = new String[length];
    latitudes = getJsonResult(taxis, "latitude");
    String[] longitudes = new String[length];
    longitudes = getJsonResult(taxis, "longitude");
    String[] names = new String[length];
    names = getJsonResult(taxis, "name");
    String[] vehicles = new String[length];
    vehicles = getJsonResult(taxis, "vehicle");
    String[] plaques = new String[length];
    plaques = getJsonResult(taxis, "plaque");
    String[] licenses = new String[length];
    licenses = getJsonResult(taxis, "license");
    String[] langs = new String[length];
    langs = getJsonResult(taxis, "lang");

    DecimalFormat conv = new DecimalFormat("0.00");

    for (int i = 0; i < length; i++) {

        String[] languages = langs[i].split(",");
        String lang = "";
        for (int j = 0; j < languages.length; j++) {

            if (languages[j].equals("pt")) {
                lang += "Portugus";
            } else if (languages[j].equals("en")) {
                lang += ", Ingls";
            } else if (languages[j].equals("es")) {
                lang += ", Espanhol";
            }
        }

        double lat = Double.parseDouble(latitudes[i]);
        double lng = Double.parseDouble(longitudes[i]);

        //GeoPoint da posio atual do taxista
        geoTaxi = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));

        overlayitem = new OverlayItem(geoTaxi, "RG: " + ids[i] + " - " + names[i],
                "Descrio:\nDistncia: " + conv.format(Double.parseDouble(distances[i]) / 1000)
                        + " km\nVeculo: " + vehicles[i] + "\nPlaca: " + plaques[i] + "\nLicena n: "
                        + licenses[i] + "\nIdiomas Conhecidos: " + lang + "\n");

        itemizedOverlay = new CustomItemizedOverlay(dTaxi, getParent(), mapView);

        itemizedOverlay.addOverlay(overlayitem);

        mapOverlays.add(itemizedOverlay);
    }

    //Localizao atual do usurio
    myLocationOverlay = new MyCustomLocationOverlay(ClientMapActivity.this, mapView);
    //Habilita o ponto azul de localizacao na tela
    myLocationOverlay.enableMyLocation();
    //Habilita atualizacoes do sensor
    myLocationOverlay.enableCompass();

    //Adiciona o overlay no mapa
    mapOverlays.add(myLocationOverlay);

    //Rotina p/ forar que todos os objetos encontrados apaream no mapa
    maxLatitude = Math.max(geoActual.getLatitudeE6(), maxLatitude);
    minLatitude = Math.min(geoActual.getLatitudeE6(), minLatitude);
    maxLongitude = Math.max(geoActual.getLongitudeE6(), maxLongitude);
    minLongitude = Math.min(geoActual.getLongitudeE6(), minLongitude);

    maxLatitude = Math.max(geoTaxi.getLatitudeE6(), maxLatitude);
    minLatitude = Math.min(geoTaxi.getLatitudeE6(), minLatitude);
    maxLongitude = Math.max(geoTaxi.getLongitudeE6(), maxLongitude);
    minLongitude = Math.min(geoTaxi.getLongitudeE6(), minLongitude);

    mc.animateTo(new GeoPoint((maxLatitude + minLatitude) / 2, (maxLongitude + minLongitude) / 2));
    mc.zoomToSpan(Math.abs(maxLatitude - minLatitude), Math.abs(maxLongitude - minLongitude));

    Integer zoomlevel = mapView.getZoomLevel();
    Integer zoomlevel2 = zoomlevel - 1;
    mc.setZoom(zoomlevel2);
    //Fim rotina

    try {
        updateClientLocation(location); //Atualiza a posio do cliente
    } catch (Exception e) {
        Toast.makeText(ClientMapActivity.this, getString(R.string.login_error_connection), Toast.LENGTH_SHORT)
                .show();
    }

    mapInfo.setText("O txi mais prximo de voc est a: "
            + conv.format(Double.parseDouble(distances[0]) / 1000) + " km");
}

From source file:com.vonglasow.michael.satstat.PasvLocListenerService.java

@Override
public void onLocationChanged(Location location) {
    if (!location.getProvider().equals(LocationManager.GPS_PROVIDER))
        return;//from   w  ww . j  ava 2 s .co  m
    if (mNotifyFix && (mStatus != GPS_INACTIVE)) {
        mStatus = GPS_FIX;
        GpsStatus status = mLocationManager.getGpsStatus(null);
        int satsInView = 0;
        int satsUsed = 0;
        Iterable<GpsSatellite> sats = status.getSatellites();
        for (GpsSatellite sat : sats) {
            satsInView++;
            if (sat.usedInFix()) {
                satsUsed++;
            }
        }
        double lat = Math.abs(location.getLatitude());
        double lon = Math.abs(location.getLongitude());
        String ns = (location.getLatitude() > 0) ? getString(R.string.value_N)
                : (location.getLatitude() < 0) ? getString(R.string.value_S) : "";
        String ew = (location.getLongitude() > 0) ? getString(R.string.value_E)
                : (location.getLongitude() < 0) ? getString(R.string.value_W) : "";
        String title = String.format("%.5f%s%s %.5f%s%s", lat, getString(R.string.unit_degree), ns, lon,
                getString(R.string.unit_degree), ew);
        String text = "";
        if (location.hasAltitude()) {
            text = text + String.format("%.0f%s", location.getAltitude(), getString(R.string.unit_meter));
        }
        if (location.hasSpeed()) {
            text = text + (text.equals("") ? "" : ", ")
                    + String.format("%.0f%s", (location.getSpeed() * 3.6), getString(R.string.unit_km_h));
        }
        if (location.hasAccuracy()) {
            text = text + (text.equals("") ? "" : ", ")
                    + String.format("\u03b5 = %.0f%s", location.getAccuracy(), getString(R.string.unit_meter));
        }
        text = text + (text.equals("") ? "" : ", ") + String.format("%d/%d", satsUsed, satsInView);
        text = text + (text.equals("") ? "" : ",\n")
                + String.format("TTFF %d s", status.getTimeToFirstFix() / 1000);
        mBuilder.setSmallIcon(R.drawable.ic_stat_notify_location);
        mBuilder.setContentTitle(title);
        mBuilder.setContentText(text);
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(text));

        startForeground(ONGOING_NOTIFICATION, mBuilder.build());
    } else {
        stopForeground(true);
    }
}

From source file:com.example.android.camera2video.CameraActivity.java

public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == TAG_PERMISSION_FINE_LOCATION) {
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
        }//from  w  w  w .  jav  a 2  s . c  om
    }
}

From source file:com.swetha.easypark.GetParkingLots.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    if (!isGooglePlayServicesAvailable()) {
        finish();/*from w  w  w.  j  a  v a2s . co  m*/
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.getparkinglots);

    SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    googleMap = supportMapFragment.getMap();

    googleMap.setMyLocationEnabled(true);
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if (gps_enabled) {
        Criteria criteria = new Criteria();

        provider = locationManager.getBestProvider(criteria, true);

        if (provider != null && !provider.equals("")) {

            locationManager.requestLocationUpdates(provider, 500, 1, GetParkingLots.this);
            // Get the location from the given provider 
            location = locationManager.getLastKnownLocation(provider);

        }
    }
    Log.i("GetParkingLots", "Value of network_enabled and location" + network_enabled + location);
    if (location == null && network_enabled) {

        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500, 1, GetParkingLots.this);

    }

    if (location == null && !network_enabled && !gps_enabled) {
        Toast.makeText(getBaseContext(), "Enable your location services", Toast.LENGTH_LONG).show();
    }
    if (location != null)
        onLocationChanged(location);
    else {

        Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
    }

    tv_fromTime = (TextView) findViewById(R.id.tv_fromTime);
    fromTimeString = Constants.dtf.format(new Date()).toString();
    tv_fromTime.setText(fromTimeString);
    long lval = DateTimeHelpers.convertToLongFromTime(Constants.dtf.format(new Date()).toString());
    Log.i("GetParkingLots",
            "The value of current time:" + Constants.dtf.format(new Date()).toString() + "in long is" + lval);
    Log.i("GetParkingLots",
            "The value of current time:" + lval + "in long is" + DateTimeHelpers.convertToTimeFromLong(lval));
    tv_toTime = (TextView) findViewById(R.id.tv_ToTime);
    // Parsing the date
    toTimeString = Constants.dtf.format(new Date()).toString();
    tv_toTime.setText(toTimeString);

    btnFromTime = (Button) findViewById(R.id.fromButton);
    btnFromTime.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            // Create the dialog
            final Dialog mDateTimeDialog = new Dialog(GetParkingLots.this);
            // Inflate the root layout
            final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater()
                    .inflate(R.layout.date_time_dialog, null);
            // Grab widget instance
            mDateTimePicker = (DateTimePicker) mDateTimeDialogView.findViewById(R.id.DateTimePicker);
            mDateTimePicker.setDateChangedListener(GetParkingLots.this);

            // Update demo TextViews when the "OK" button is clicked 
            ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime))
                    .setOnClickListener(new OnClickListener() {
                        Calendar cal;

                        @SuppressWarnings("deprecation")
                        public void onClick(View v) {
                            mDateTimePicker.clearFocus();
                            try {
                                cal = new GregorianCalendar(mDateTimePicker.getYear(),
                                        Integer.parseInt(mDateTimePicker.getMonth()), mDateTimePicker.getDay(),
                                        mDateTimePicker.getHour(), mDateTimePicker.getMinute());
                                fromTimeString = DateTimeHelpers.dtf.format(cal.getTime());
                                tv_fromTime.setText(fromTimeString);
                            } catch (Exception e) {
                                final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this)
                                        .create();

                                alertDialog.setMessage("Enter a valid date");

                                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {

                                        alertDialog.dismiss();
                                    }
                                });

                                alertDialog.show();
                            }

                            mDateTimeDialog.dismiss();
                        }
                    });

            // Cancel the dialog when the "Cancel" button is clicked
            ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog))
                    .setOnClickListener(new 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 OnClickListener() {

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

            // Setup TimePicker
            // 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();

        }
    });

    btnToTime = (Button) findViewById(R.id.toButton);
    btnToTime.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            // Create the dialog
            final Dialog mDateTimeDialog = new Dialog(GetParkingLots.this);
            // Inflate the root layout
            final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater()
                    .inflate(R.layout.date_time_dialog, null);
            // Grab widget instance
            final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView
                    .findViewById(R.id.DateTimePicker);
            mDateTimePicker.setDateChangedListener(GetParkingLots.this);

            // Update demo TextViews when the "OK" button is clicked 
            ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime))
                    .setOnClickListener(new OnClickListener() {
                        Calendar cal;

                        @SuppressWarnings("deprecation")
                        public void onClick(View v) {
                            mDateTimePicker.clearFocus();

                            Log.i("toButton", "Value of ToString before cal" + toTimeString);
                            try {
                                cal = new GregorianCalendar(mDateTimePicker.getYear(),
                                        Integer.parseInt(mDateTimePicker.getMonth()), mDateTimePicker.getDay(),
                                        mDateTimePicker.getHour(), mDateTimePicker.getMinute());
                                toTimeString = DateTimeHelpers.dtf.format(cal.getTime());
                                Log.i("toButton", "Value of ToString before cal" + toTimeString);

                                tv_toTime.setText(toTimeString);

                            } catch (Exception e) // fixing the bug where the user doesnt enter anything in the textbox
                            {
                                final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this)
                                        .create();

                                alertDialog.setMessage("Enter a valid date");
                                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        alertDialog.dismiss();
                                    }
                                });

                                alertDialog.show();
                            }
                            //dateTimeTo = new DateTime(mDateTimePicker.getYear(), Integer.parseInt(mDateTimePicker.getMonth()) ,  mDateTimePicker.getDay(),  mDateTimePicker.getHour(),  mDateTimePicker.getMinute()); ;

                            mDateTimeDialog.dismiss();
                        }
                    });

            ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog))
                    .setOnClickListener(new 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 OnClickListener() {

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

            // Setup TimePicker
            // 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();

        }
    });

    btnGetParkingLots = (Button) findViewById(R.id.getNearByParkingLotsButton);
    btnGetParkingLots.setOnClickListener(new View.OnClickListener() {

        @SuppressWarnings("deprecation")
        public void onClick(View v) {
            et_search = (EditText) findViewById(R.id.edittextsearch);
            rg = (RadioGroup) findViewById(R.id.rg);
            checkedRbId = rg.getCheckedRadioButtonId();
            Log.i("LOG_TAG: GetParkingLots", "checked radiobutton id is" + checkedRbId);

            if (checkedRbId == R.id.rbradius) {
                isRadiusIndicator = true;
                radius = et_search.getText().toString();
            } else {
                isRadiusIndicator = false;
                zipcode = et_search.getText().toString();
            }

            final Intent intent = new Intent(GetParkingLots.this, DisplayVacantParkingLots.class);
            Log.i(TAG, "Inside getNearByParkingLots");
            Log.i(TAG, "Value of fromString" + fromTimeString);
            long lFromVal = DateTimeHelpers.convertToLongFromTime(fromTimeString);
            Log.i(TAG, "Value of ToString" + toTimeString);
            long lToVal = DateTimeHelpers.convertToLongFromTime(toTimeString);
            if ((lToVal - lFromVal) < Constants.thrityMinInMilliSeconds) {
                final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this).create();

                alertDialog.setMessage("You have to park the car for at least 30 min");

                alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        alertDialog.dismiss();
                    }
                });

                alertDialog.show();

            } else {
                intent.putExtra(LATITUDE, latitude);
                intent.putExtra(LONGITUDE, longitude);
                intent.putExtra(FROMTIME, lFromVal);
                intent.putExtra(TOTIME, lToVal);
                intent.putExtra(RadiusOrZIPCODE, isRadiusIndicator);
                if (isRadiusIndicator)
                    try {

                        intent.putExtra(RADIUS, Double.parseDouble(radius));
                        startActivity(intent);
                    } catch (Exception e) {
                        final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this).create();

                        alertDialog.setMessage("Enter valid radius");

                        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                                alertDialog.dismiss();

                            }
                        });

                        alertDialog.show();
                    }
                else {
                    try {

                        intent.putExtra(ZIPCODE, Long.parseLong(zipcode));
                        startActivity(intent);
                    } catch (Exception e) {
                        final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this).create();

                        alertDialog.setMessage("Enter a valid Zip code");

                        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                alertDialog.dismiss();

                            }
                        });

                        alertDialog.show();
                    }
                }

            }

        }
    });

}

From source file:com.nextgis.rehacompdemo.RoutingActivity.java

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

    String sRadius = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.PREF_RADIUS, "6");
    mActivationDistance = Integer.parseInt(sRadius);

    int routeNum = -1;
    Bundle extras = getIntent().getExtras();

    if (extras != null) {
        routeNum = extras.getInt(Constants.BUNDLE_ROUTE_ID);

        if (getSupportActionBar() != null)
            getSupportActionBar().setTitle(extras.getString(Constants.BUNDLE_ROUTE_NAME));
    }//from w w w.  jav a2s  .c o m

    if (routeNum == -1)
        return;

    mRoute = "route_" + routeNum;
    mPoints = "points_" + routeNum;

    mSteps = (ListView) findViewById(R.id.lv_steps);
    mAdapter = new StepAdapter(this, R.layout.item_step, getRouteSteps());
    mSteps.setAdapter(mAdapter);
    mSteps.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);

    mSteps.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //                view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
            mSteps.requestFocusFromTouch();
            mSteps.setSelection(position);
        }
    });

    mMap = (MapDrawable) ((GISApplication) getApplication()).getMap();
    new MapLoader().execute();

    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, Constants.GPS_MIN_TIME,
            Constants.GPS_MIN_DIST, this);
}