如何持续检查用户是否在特定位置

时间:2018-04-19 15:34:03

标签: android

我正在使用谷歌地图API。我已经能够让用户选择一个位置,用户选择的位置将通过共享首选项保存。当用户在该位置时,它调用方法但是它仅检查用户是否在用户打开应用程序时的位置,并且即使打开应用程序并且用户前往该位置,该应用程序也需要重新启动该方法被调用。我该怎么做才能连续检查用户是否在该位置,即使该应用程序已关闭。

以下是代码:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private PlaceAutocompleteAdapter mPlaceAutoCompleteAdapter;
    private static final LatLngBounds LAT_LNG_BOUNDS = new LatLngBounds(
            new LatLng(-40, -168), new LatLng(71,136));

    private AutoCompleteTextView mSearchText;
    private static final float METRES_100 = 100;
    private GoogleMap mMap;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    LocationRequest mLocationRequest;

    private static double latit;
    private static double longi;

    private static final LatLng POINTA = new LatLng(latit,longi);

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

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkLocationPermission();
        }
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }


    /**
     * Manipulates the map once available.
     * 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;

            if (DataPersistLoc.getLocation(MapsActivity.this).toString() == "") {

            } else {
                List<Address> addressList = null;
                Geocoder geocoder = new Geocoder(this);
                try {
                    addressList = geocoder.getFromLocationName(DataPersistLoc.getLocation(MapsActivity.this).toString(), 1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Address address = addressList.get(0);
                LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
                mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
                mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            }

            //Initialize Google Play Services
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {
                    buildGoogleApiClient();
                    mMap.setMyLocationEnabled(true);

                    mMap.getUiSettings().setZoomControlsEnabled(true);
                    mMap.getUiSettings().setZoomGesturesEnabled(true);
                    mMap.getUiSettings().setCompassEnabled(true);

                }
            }
            else {
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);
            }

        }


    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();

    }

    public void changeType(View view)
    {
        if(mMap.getMapType() == GoogleMap.MAP_TYPE_NORMAL)
        {
            mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        }
        else
            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    }

    public void onSearch(View view) {

            AutoCompleteTextView location_tf = (AutoCompleteTextView) findViewById(R.id.TFaddress);

            if (TextUtils.isEmpty(location_tf.getText())) {

                Toast.makeText(MapsActivity.this, "Enter Location",
                        Toast.LENGTH_LONG).show();

            } else {

                String location = location_tf.getText().toString();
                List<Address> addressList = null;
                if (location != null || !location.equals("")) {
                    Geocoder geocoder = new Geocoder(this);
                    try {
                        addressList = geocoder.getFromLocationName(location, 1);


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

                    SharedPreferences.Editor editor = prefs.edit();

                    Address address = addressList.get(0);
                    LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
                    latit = address.getLatitude();
                    //saves latitude value to shared preference
                    putDoubleLat(MapsActivity.this);

                    longi = address.getLongitude();
                    //saves latitude value to shared preference
                    putDoubleLong(MapsActivity.this);

                    mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
                    mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

                }


            }

    }


    private static SharedPreferences prefs;

    public static long LatPref = 0;
    public static String latPref = "LatPref";

    public static long LongPref = 0;
    public static String longPref = "LongPref";

    public static void putDoubleLat(Context context) {
        prefs = context.getSharedPreferences("com.mobile.counterappmobile", context.MODE_PRIVATE);
        LatPref = prefs.getLong(latPref, (long) latit);
        prefs.edit().putLong(latPref, Double.doubleToRawLongBits(latit)).commit();

    }

    public static double getDoubleLat(Context context) {
        SharedPreferences prefs = context.getSharedPreferences("com.mobile.counterappmobile", context.MODE_PRIVATE);
        return Double.longBitsToDouble(prefs.getLong(latPref, Double.doubleToLongBits(LatPref)));

    }

    public static void putDoubleLong(Context context) {
        prefs = context.getSharedPreferences("com.mobile.counterappmobile", context.MODE_PRIVATE);
        LongPref = prefs.getLong(longPref, (long) longi);
        prefs.edit().putLong(longPref, Double.doubleToRawLongBits(longi)).commit();

    }

    public static double getDoubleLong(Context context) {
        SharedPreferences prefs = context.getSharedPreferences("com.mobile.counterappmobile", context.MODE_PRIVATE);
        return Double.longBitsToDouble(prefs.getLong(longPref, Double.doubleToLongBits(LongPref)));

    }



    @Override
    public void onConnected(Bundle bundle) {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

//----------------------------------------------------------------------------
//Checks if user is at selected location

    @Override
    public void onLocationChanged(Location location) {

        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        //Place current location marker
        LatLng latLng1 = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng1);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mMap.addMarker(markerOptions);

        //move map camera
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng1));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(11));

        //stop location updates
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }

        SharedPreferences prefs = getSharedPreferences("com.mobile.counterappmobile", MODE_PRIVATE);

//Checks if user is at selected location
        Location target = new Location("target");
        for(LatLng point : new LatLng[]{POINTA}) {
            target.setLatitude(getDoubleLat(MapsActivity.this));
            target.setLongitude(getDoubleLong(MapsActivity.this));
            if(location.distanceTo(target) < METRES_100) {

                Toast.makeText(MapsActivity.this, "You Are At This Location",
                        Toast.LENGTH_LONG).show();
            } else {

            }
        }





    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    public boolean checkLocationPermission(){
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Asking user if explanation is needed
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

                //Prompt the user once explanation has been shown
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);


            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted. Do the
                    // contacts-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mMap.setMyLocationEnabled(true);
                    }

                } else {

                    // Permission denied, Disable the functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other permissions this app might request.
            // You can add here other case statements according to your requirement.
        }
    }
}

0 个答案:

没有答案