Example usage for android.location Criteria Criteria

List of usage examples for android.location Criteria Criteria

Introduction

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

Prototype

public Criteria() 

Source Link

Document

Constructs a new Criteria object.

Usage

From source file:org.deviceconnect.android.deviceplugin.host.profile.HostGeolocationProfile.java

/**
 * ??./* ww  w. j a  v a 2 s.c o m*/
 * @param accuracy .
 * @param interval ?.
 */
private void startGPS(final boolean accuracy, final int interval) {
    if (ActivityCompat.checkSelfPermission(getContext(),
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(getContext(),
                    ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }

    Criteria criteria = new Criteria();
    if (accuracy) {
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
    } else {
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    }

    mLocationManager.requestLocationUpdates(mLocationManager.getBestProvider(criteria, true), interval, 0, this,
            Looper.getMainLooper());
}

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);/*from   ww w. j a  va  2 s .  co m*/

        // 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.tingbacke.wearmaps.MobileActivity.java

/**
 * This is where we can add markers or lines, add listeners or move the camera. In this case, we
 * just add a marker near Africa.// www  .j  a v a2  s.  c o  m
 * <p/>
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 */
private void setUpMap() {

    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    mMap.setMyLocationEnabled(true);
    /**
     * https://geolocation.ws/map/55.588227,13.002735/13/en?types=&limit=300&licenses=
     * Dammfrivgen 61 = 55.587116, 12.979788
     */
    /*
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.61015, 12.9786)).title("Cykelpump Kockums Torg"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.5877, 12.9887)).title("Cykelpump Malm gamla stadion"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6093, 12.9967)).title("Cykelpump, Anna Linds plats"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6025, 12.9679)).title("Cykelpump, Ribersborgsstigen"));
            
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6131, 12.9767)).title("Turning Torso"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6140, 12.9839)).title("Stapelbddsparken, skatepark"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6125, 12.9914)).title("Media Evolution City"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6144, 12.9895)).title("Doc Piazza Trattoria"));
            
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6156, 12.9857)).title("Kranen K3, Malm Hgskola"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6150, 12.9858)).title("Ubtshallen"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6108, 12.9949)).title("Orkanen, Malm Hgskola"));
            
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.5850, 12.9873)).title("Swedbank Stadion"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.5922, 12.9975)).title("Pildammsparken Entr"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.5901, 12.9887)).title("Pildammsparken Tallriken"));
            
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.5890, 12.9825)).title("Jet bensinmack, Lorensborg"));
            
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6048, 12.9658)).title("Ribersborgs Kallbadhus"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6041, 12.9735)).title("Toalett, Ribersborgsstigen"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6086, 12.9774)).title("Kockum fritid"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6138, 12.9812)).title("Varvsparken"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6137, 12.9725)).title("Daniabadet, Vstra Hamnen"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.6171, 12.9744)).title("Scaniabadet, Vstra Hamnen"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.5967, 13.0053)).title("MALM"));
    mMap.addMarker(new MarkerOptions().position(new LatLng(55.5986, 12.9836)).title("Kronprinsen"));
    //mMap.addMarker(new MarkerOptions().position(new LatLng()).title(""));
    */
    // Get LocationManager object from System Service LOCATION_SERVICE
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    // Create a criteria object to retrieve provider
    Criteria criteria = new Criteria();

    // Get the name of the best provider
    String provider = locationManager.getBestProvider(criteria, true);

    // Get Current Location
    Location myLocation = locationManager.getLastKnownLocation(provider);

    // Get latitude of the current location
    double latitude = myLocation.getLatitude();

    // Get longitude of the current location
    double longitude = myLocation.getLongitude();

    // Create a LatLng object for the current location
    LatLng latLng = new LatLng(latitude, longitude);

    // Show the current location in Google Map
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(18).bearing(0).tilt(25)
            .build();
    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    LatLng myCoordinates = new LatLng(latitude, longitude);
    CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(myCoordinates, 18);
    mMap.animateCamera(yourLocation);

}

From source file:be.artoria.belfortapp.fragments.MapFragment.java

private GeoPoint getCurrentLocation() {
    // Get the location manager
    final LocationManager locationManager = (LocationManager) getActivity().getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the locatioin provider -> use
    // default//  w ww . j a va2s .  c om
    final Criteria criteria = new Criteria();
    final String provider = locationManager.getBestProvider(criteria, false);
    final Location loc = locationManager.getLastKnownLocation(provider);

    if (loc != null) {
        return new GeoPoint(loc.getLatitude(), loc.getLongitude());
    } else {
        return new GeoPoint(DataManager.BELFORT_LAT, DataManager.BELFORT_LON);
    }
}

From source file:de.madvertise.android.sdk.MadvertiseUtil.java

/**
 * Try to update current location. Non blocking call.
 * /*from w w  w  . j  a  va  2 s  .  c o m*/
 * @param context
 *            application context
 */
public static void refreshCoordinates(final Context context) {
    MadvertiseUtil.logMessage(null, Log.DEBUG, "Trying to refresh location");

    if (context == null) {
        MadvertiseUtil.logMessage(null, Log.DEBUG, "Context not set - quit location refresh");
        return;
    }

    // check if we need a regular update
    if ((sLocationUpdateTimestamp + MadvertiseUtil.SECONDS_TO_REFRESH_LOCATION * 1000) > System
            .currentTimeMillis()) {
        MadvertiseUtil.logMessage(null, Log.DEBUG, "It's not time yet for refreshing the location");
        return;
    }

    synchronized (context) {
        // recheck, if location was updated by another thread while we
        // paused
        if ((sLocationUpdateTimestamp + MadvertiseUtil.SECONDS_TO_REFRESH_LOCATION * 1000) > System
                .currentTimeMillis()) {
            MadvertiseUtil.logMessage(null, Log.DEBUG, "Another thread updated the loation already");
            return;
        }

        boolean permissionCoarseLocation = MadvertiseUtil
                .checkPermissionGranted(android.Manifest.permission.ACCESS_COARSE_LOCATION, context);
        boolean permissionFineLocation = MadvertiseUtil
                .checkPermissionGranted(android.Manifest.permission.ACCESS_FINE_LOCATION, context);

        // return (null) if we do not have any permissions
        if (!permissionCoarseLocation && !permissionFineLocation) {
            MadvertiseUtil.logMessage(null, Log.DEBUG, "No permissions for requesting the location");
            return;
        }

        // return (null) if we can't get a location manager
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null) {
            MadvertiseUtil.logMessage(null, Log.DEBUG, "Unable to fetch a location manger");
            return;
        }

        String provider = null;
        Criteria criteria = new Criteria();
        criteria.setCostAllowed(false);

        // try to get coarse location first
        if (permissionCoarseLocation) {
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            provider = locationManager.getBestProvider(criteria, true);
        }

        // try to get gps location if coarse locatio did not work
        if (provider == null && permissionFineLocation) {
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            provider = locationManager.getBestProvider(criteria, true);
        }

        // still no provider, return (null)
        if (provider == null) {
            MadvertiseUtil.logMessage(null, Log.DEBUG, "Unable to fetch a location provider");
            return;
        }

        // create a finalized reference to the location manager, in order to
        // access it in the inner class
        final LocationManager finalizedLocationManager = locationManager;
        sLocationUpdateTimestamp = System.currentTimeMillis();
        locationManager.requestLocationUpdates(provider, 0, 0, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                MadvertiseUtil.logMessage(null, Log.DEBUG, "Refreshing location");
                sCurrentLocation = location;
                sLocationUpdateTimestamp = System.currentTimeMillis();
                // stop draining battery life
                finalizedLocationManager.removeUpdates(this);
            }

            // not used yet
            @Override
            public void onProviderDisabled(String provider) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }
        }, context.getMainLooper());
    }
}

From source file:com.google.android.dialer.provider.DialerProvider.java

private Location getLastLocation() {
    LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestSingleUpdate(new Criteria(), new LocationListener() {
        @Override//from   w w w .ja va  2s  .  com
        public void onLocationChanged(Location location) {
            if (Log.isLoggable("DialerProvider", Log.VERBOSE)) {
                Log.v("DialerProvider", "onLocationChanged: " + location);
            }
        }

        @Override
        public void onProviderDisabled(String provider) {
            if (Log.isLoggable("DialerProvider", Log.VERBOSE)) {
                Log.v("DialerProvider", "onProviderDisabled: " + provider);
            }
        }

        @Override
        public void onProviderEnabled(String provider) {
            if (Log.isLoggable("DialerProvider", Log.VERBOSE)) {
                Log.v("DialerProvider", "onProviderEnabled: " + provider);
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            if (Log.isLoggable("DialerProvider", Log.VERBOSE)) {
                Log.v("DialerProvider", "onStatusChanged: " + provider + ", " + status + ", " + extras);
            }
        }
    }, DialerProvider.mLooper);
    return locationManager.getLastLocation();
}

From source file:com.example.s_geomapsample.MainActivity.java

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

    mLatitude = (TextView) findViewById(R.id.latitude);
    mAccuracy = (TextView) findViewById(R.id.accuracy);
    mLongitude = (TextView) findViewById(R.id.longitude);

    mProvider = (TextView) findViewById(R.id.t01);

    mHandler = new Handler();

    // mApp = (ApplicationClass) getApplication();
    // mApp.setOnNotifiedMessageListener(mNotifiedMessageListener);
    // mLocationManager = new LocationServiceManager(getApplication());

    upReceiver = new UpdateReceiver();
    intentFilter = new IntentFilter();
    intentFilter.addAction("UPDATE_ACTION");
    registerReceiver(upReceiver, intentFilter);

    upReceiver.registerHandler(updateHandler);

    // ?//w ww  .ja  v  a2 s  .c  o  m
    Button setParamButton = (Button) findViewById(R.id.param);
    setParamButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mGeoFenceManager = new GeoFenceManager(MainActivity.this);
            HashMap<String, Object> defaultMap = new HashMap<String, Object>();
            {
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_CLIENTID, "JSZ3a03eb052f46|E7Tg6");
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_TMID, "t1000_1");
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_SECRET, "eNphiW-zYeDhnj37IL86bJeijmA");
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_TNTP, "1");
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_TATP, "1");
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_NCURL,
                        "https://test-mlp.its-mo.com/mlp/v1_0/request/SearchNotifyConditionList.php");
                defaultMap.put(GeoFenceManager.REQUEST_PARAM_KEY_AIURL,
                        "https://test-mlp.its-mo.com/mlp/v1_0/request/SearchAreaInfoList.php");
                defaultMap.put("SAVE_INTERVAL", "2");
            }

            int result = mGeoFenceManager.setParams(defaultMap, 1);
            if (result == GeoFenceManager.SET_PARAMS_RESULT_CODE_SUCCESS) {
                Toast.makeText(MainActivity.this, "SET_PARAMS_RESULT_CODE_SUCCESS", Toast.LENGTH_LONG).show();
            } else if (result == GeoFenceManager.SET_PARAMS_RESULT_CODE_NO_REQUIRED) {
                Toast.makeText(MainActivity.this, "SET_PARAMS_RESULT_CODE_NO_REQUIRED", Toast.LENGTH_LONG)
                        .show();
            }
        }
    });

    // Area
    Button updateButton = (Button) findViewById(R.id.update);
    updateButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            int updateAreaInfomation = mGeoFenceManager.updateAreaInfomation();
            Toast.makeText(MainActivity.this, "updateAreaInfomation = " + updateAreaInfomation,
                    Toast.LENGTH_LONG).show();
            // UpdateAreaAsync areaAsync = new
            // UpdateAreaAsync(MainActivity.this, mGeoFenceManager);
            // areaAsync.execute();
        }
    });
    // GPS???
    Button gpsButton = (Button) findViewById(R.id.gps_button);
    gpsButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            LocationServiceManager locationServiceManager = new LocationServiceManager(MainActivity.this);
            locationServiceManager.startLocationService();
        }
    });

    // Google Play Services???????
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

    // Showing status
    if (status != ConnectionResult.SUCCESS) {
        // Google Play Services ?????
        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
        dialog.show();

    } else {
        // Google Play Services ???
        // activity_main.xml?SupportMapFragment????
        SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        // fragment?GoogleMap object?
        gMap = fm.getMap();

        // Google Map?MyLocation???
        gMap.setMyLocationEnabled(true);
        gMap.setIndoorEnabled(true);
        gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        gMap.setTrafficEnabled(true);

        // ?LOCATION_SERVICE?LocationManager object?
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // retrieve provider?criteria object?
        Criteria criteria = new Criteria();

        // Best provider?????
        String provider = locationManager.getBestProvider(criteria, true);

        // ???
        Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(provider, 20000, 0, this);

    }

}

From source file:com.coincide.alphafitness.ui.Fragment_Main.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    //        final View v = inflater.inflate(R.layout.fragment_overview, null);
    View v = null;/*from   www.j a  v a2  s. c om*/

    v = inflater.inflate(R.layout.fragment_main, container, false);

    //        stepsView = (TextView) v.findViewById(R.id.steps);
    //        totalView = (TextView) v.findViewById(R.id.total);
    totalView = (TextView) v.findViewById(R.id.tv_distance);
    tv_avg = (TextView) v.findViewById(R.id.tv_avg);
    tv_max = (TextView) v.findViewById(R.id.tv_max);
    tv_min = (TextView) v.findViewById(R.id.tv_min);
    //        averageView = (TextView) v.findViewById(R.id.average);

    /*
            pg = (PieChart) v.findViewById(R.id.graph);
            
            // slice for the steps taken today
            sliceCurrent = new PieModel("", 0, Color.parseColor("#99CC00"));
            pg.addPieSlice(sliceCurrent);
            
            // slice for the "missing" steps until reaching the goal
            sliceGoal = new PieModel("", Fragment_Settings.DEFAULT_GOAL, Color.parseColor("#CC0000"));
            pg.addPieSlice(sliceGoal);
            
            pg.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(final View view) {
        showSteps = !showSteps;
        stepsDistanceChanged();
    }
            });
            
            pg.setDrawValueInPie(false);
            pg.setUsePieRotation(true);
            pg.startAnimation();
    */

    /*
    * MainActivity
    * */
    // Always cast your custom Toolbar here, and set it as the ActionBar.
    Toolbar tb = (Toolbar) v.findViewById(R.id.toolbar);
    ((AppCompatActivity) getActivity()).setSupportActionBar(tb);

    TextView tv_tb_center = (TextView) tb.findViewById(R.id.tv_tb_center);
    tv_tb_center.setText("ALPHA FITNESS");

    /*   ImageButton imgbtn_cart = (ImageButton) tb.findViewById(R.id.imgbtn_cart);
       imgbtn_cart.setVisibility(View.GONE);*/

    tb.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getActivity().onBackPressed();
        }
    });

    // Get the ActionBar here to configure the way it behaves.
    final ActionBar ab = ((AppCompatActivity) getActivity()).getSupportActionBar();
    //ab.setHomeAsUpIndicator(R.drawable.ic_menu); // set a custom icon for the default home button
    ab.setDisplayShowHomeEnabled(false); // show or hide the default home button
    ab.setDisplayHomeAsUpEnabled(false);
    ab.setDisplayShowCustomEnabled(false); // enable overriding the default toolbar layout
    ab.setDisplayShowTitleEnabled(false); // disable the default title element here (for centered title)

    tv_duration = (TextView) v.findViewById(R.id.tv_duration);

    startButton = (Button) v.findViewById(R.id.btn_start);
    if (isButtonStartPressed) {
        startButton.setBackgroundResource(R.drawable.btn_stop_states);
        startButton.setText(R.string.btn_stop);
        try {
            SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
            sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER),
                    SensorManager.SENSOR_DELAY_UI, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        try {
            SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
            sm.unregisterListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    startButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            onSWatchStart();
        }
    });
    iv_profile = (ImageView) v.findViewById(R.id.iv_profile);
    iv_profile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Database db = Database.getInstance(getActivity());
            tot_workouts = db.getTotWorkouts();
            tot_workTime = db.getWorkTime();
            Log.e("Tot Work time", tot_workTime + "");
            //                int seconds = (int) (tot_workTime / 1000) % 60;
            //                int minutes = (int) ((tot_workTime / (1000 * 60)) % 60);

            long millis = tot_workTime * 100; // obtained from StopWatch
            long hours = (millis / 1000) / 3600;
            long minutes = (millis / 1000) / 60;
            long seconds = (millis / 1000) % 60;

            db.close();

            Intent i = new Intent(getActivity(), ProfileActivity.class);
            i.putExtra("avg_distance", avg_distance + "");
            i.putExtra("all_distance", all_distance + "");
            i.putExtra("avg_time", tv_duration.getText().toString());
            i.putExtra("all_time", tv_duration.getText().toString());
            i.putExtra("avg_calories", avg_calories + "");
            i.putExtra("all_calories", all_calories + "");
            i.putExtra("tot_workouts", tot_workouts + "");
            i.putExtra("avg_workouts", tot_workouts + "");

            i.putExtra("tot_workTime", hours + " hrs " + minutes + " min " + seconds + " sec");

            startActivity(i);

        }
    });

    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity().getBaseContext());

    if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getActivity(), requestCode);
        dialog.show();

    } else { // Google Play Services are available

        // Initializing
        mMarkerPoints = new ArrayList<LatLng>();

        // Getting reference to SupportMapFragment of the activity_main
        //            SupportMapFragment fm = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
        MapFragment fm = (MapFragment) getActivity().getFragmentManager().findFragmentById(R.id.map);

        // Getting Map for the SupportMapFragment
        mGoogleMap = fm.getMap();

        // Enable MyLocation Button in the Map
        mGoogleMap.setMyLocationEnabled(true);

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

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location From GPS
        Location location;
        if (provider != null) {

            if (ActivityCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(getActivity(),
                            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 null;
            }
            location = locationManager.getLastKnownLocation(provider);
            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        } else {
            location = new Location("");
            location.setLatitude(0.0d);//your coords of course
            location.setLongitude(0.0d);
        }

        if (location != null) {
            onLocationChanged(location);
        }

        // Setting onclick event listener for the map
        mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

            @Override
            public void onMapClick(LatLng point) {

                // Already map contain destination location
                if (mMarkerPoints.size() > 1) {

                    FragmentManager fm = getActivity().getSupportFragmentManager();
                    mMarkerPoints.clear();
                    mGoogleMap.clear();
                    LatLng startPoint = new LatLng(mLatitude, mLongitude);
                    drawMarker(startPoint);
                }

                drawMarker(point);

                // Checks, whether start and end locations are captured
                if (mMarkerPoints.size() >= 2) {
                    LatLng origin = mMarkerPoints.get(0);
                    LatLng dest = mMarkerPoints.get(1);

                    // Getting URL to the Google Directions API
                    String url = getDirectionsUrl(origin, dest);

                    DownloadTask downloadTask = new DownloadTask();

                    // Start downloading json data from Google Directions API
                    downloadTask.execute(url);
                }
            }
        });
        fixedCentreoption = new MarkerOptions();

        mGoogleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {

            @Override
            public void onCameraChange(CameraPosition position) {
                // TODO Auto-generated method stub
                // Get the center of the Map.

                mGoogleMap.clear();

                LatLng centerOfMap = mGoogleMap.getCameraPosition().target;

                // Update your Marker's position to the center of the Map.
                fixedCentreoption.position(centerOfMap);
                //                   mGoogleMap.addMarker(fixedCentreoption);
                //                   drawMarker(centerOfMap);
                LatLng origin = new LatLng(0.0d, 0.0d);
                ;
                if (mMarkerPoints.size() > 0) {
                    origin = mMarkerPoints.get(0);
                }
                //                  LatLng dest = mMarkerPoints.get(1);
                LatLng dest = centerOfMap;
                // Getting URL to the Google Directions API
                String url = getDirectionsUrl(origin, dest);

                DownloadTask downloadTask = new DownloadTask();

                // Start downloading json data from Google Directions API
                downloadTask.execute(url);

                GPSTracker gpsTracker = new GPSTracker(getActivity().getApplicationContext());
                //               String Addrs = gpsTracker.location();
                Addrs = gpsTracker.locationBasedOnLatlng(centerOfMap);
                //               Toast.makeText(getApplicationContext(), Addrs, Toast.LENGTH_LONG).show();

            }
        });
    }

    SharedPreferences sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES,
            Context.MODE_PRIVATE);
    mBodyWeight = Float.parseFloat(sharedpreferences.getString(sp_weight, "50"));

    return v;
}

From source file:org.berlin_vegan.bvapp.activities.LocationsOverviewActivity.java

private void requestGpsLocationUpdates() {
    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    String provider = mLocationManager.getBestProvider(criteria, true);
    if (provider != null) {
        mGpsProviderAvailable = true;//w w w .java  2s . c o m
        mLocationManager.requestSingleUpdate(criteria, mLocationListener, null);
    } else {
        mGpsProviderAvailable = false;
    }
}