当用户进入地图上的地理围栏半径但不起作用时,会发出警报

时间:2019-05-22 11:53:32

标签: java android google-maps geofencing android-geofence

我需要帮助!我希望用户点击地图并在点击标记时添加标记,询问用户是否要在点击“是”按钮时向该标记添加警报,它将启动地理围栏并在用户当前位置标记进入地理围栏区域时发出警报。我已经实现了许多解决方案和代码,但是地理围栏无法正常工作,请帮助我。我必须在本周之前完成这项任务。非常感谢您<3。     代码在下面给出

# AndroidLocationAlarm.java #

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location_alarm);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setNavigation();

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkLocationPermission();
        }

        if (!CheckGooglePlayServices()) {
            Log.d("onCreate", "Finishing test case since Google Play Services are not available");
            finish();
        } else {
            Log.d("onCreate", "Google Play Services available.");
        }



        if (!Places.isInitialized()) {
            Places.initialize(getApplicationContext(), "API_KEY");
        }

        final List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME,Place.Field.LAT_LNG);



        autocompleteFragment = (AutocompleteSupportFragment)
                getSupportFragmentManager().findFragmentById(R.id.place_autocomplete);



        searchClick = findViewById(R.id.searchClick);
        searchClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, fields).build(AlarmLocationActivity.this);
                startActivityForResult(intent, 1);
            }
        });
        if (autocompleteFragment != null) {
            autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));
        }
        else {
            Toast.makeText(AlarmLocationActivity.this,"Auto Complete is null no Place field is set",Toast.LENGTH_LONG).show();
        }


        if (autocompleteFragment != null) {
            autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
                @Override
                public void onPlaceSelected(@NonNull Place place) {


                    Toast.makeText(AlarmLocationActivity.this, "Auto Complete is Not null setting new Location", Toast.LENGTH_LONG).show();

                    Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());

                }

                @Override
                public void onError(@NonNull Status status) {
                    Toast.makeText(AlarmLocationActivity.this, status.toString(), Toast.LENGTH_LONG).show();
                }
            });

        }

        else {
            Toast.makeText(AlarmLocationActivity.this,"Auto Complete is null no Location is set",Toast.LENGTH_LONG).show();
        }



                    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        geofencingClient = LocationServices.getGeofencingClient(this);
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
        builder1.setMessage("Set Alarm At this Location?");
        builder1.setCancelable(true);

        builder1.setPositiveButton(
                "Yes",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                        startGeofencing();
                        dialog.cancel();
                    }
                });

        builder1.setNegativeButton(
                "No",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });

        AlertDialog alert11 = builder1.create();
        alert11.show();
        return false;
    }

    Marker geofenceMarker=null;
    @Override
    public void onMarkerDragStart(Marker marker) {

    }

    @Override
    public void onMarkerDrag(Marker marker) {

    }

    @Override
    public void onMarkerDragEnd(Marker marker) {

    }

    @Override
    public void onMapClick(LatLng latLng) {
        markerForGeofence(latLng);
    }

    private void markerForGeofence(LatLng latLng) {
        MarkerOptions markerOptions = new MarkerOptions()
                .position(latLng)
                .title("Your Setted Location");


        if(mMap!=null){
            if(geofenceMarker!=null){
                geofenceMarker.remove();
            }

            geofenceMarker = mMap.addMarker(markerOptions);
            geofenceMarker.setDraggable(true);

        }
    }
    GeofencingRequest geofencingRequest;
    private void startGeofencing() {
        if(geofenceMarker!=null){
            Geofence geofence = createGeofence(geofenceMarker.getPosition(),400f);
            geofencingRequest = createGeofencingRequest(geofence);
            addGeofence(geofence);
        }
    }

    private void addGeofence(Geofence geofence) {
        LocationServices.GeofencingApi.addGeofences(mGoogleApiClient,geofencingRequest,createGeofencingPendingIntent())
                .setResultCallback(this);
    }
    PendingIntent geofencePendingIntent=null;

    private PendingIntent createGeofencingPendingIntent() {
        if(geofencePendingIntent != null){
            Log.d("not Runned","UNRUN");
            return geofencePendingIntent;
        }
        Log.d("Runned","RUNNING");
        startActivity(new Intent(this,AlarmActivity.class));
        Intent i = new Intent(AlarmLocationActivity.this,GeofenceTransitionService.class);
        return PendingIntent.getService(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);

    }

    private GeofencingRequest createGeofencingRequest(Geofence geofence) {
        GeofencingRequest req= new GeofencingRequest.Builder()
                // Notification to trigger when the Geofence is created
                .setInitialTrigger( GeofencingRequest.INITIAL_TRIGGER_ENTER )
                .addGeofence( geofence ) // add a Geofence
                .build();
        return req;
    }

    private Geofence createGeofence(LatLng position, float v) {
        return new Geofence.Builder()
                .setRequestId("My Geofence")
                .setCircularRegion(position.latitude,position.longitude,v)
                .setExpirationDuration(60 * 60 * 1000)
                .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER| Geofence.GEOFENCE_TRANSITION_EXIT)
                .build();
    }

    @Override
    public void onResult(@NonNull Status status) {
        drawGeofence();
    }
    Circle geofenceLimits;

    private void drawGeofence() {
        if (geofenceLimits != null) {
            geofenceLimits.remove();
        }
        CircleOptions circleOptions = new CircleOptions()
                .center(geofenceMarker.getPosition())
                .strokeColor(Color.argb(50,70,70,70))
                .fillColor(Color.argb(100,150,150,150))
                .radius(400f);
        geofenceLimits = mMap.addCircle(circleOptions);

    }




}

现在是GeofenceTransition我正在使用它     #GeofenceTransitionService.java#

package com.asfandali.androlocationalarm;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingEvent;

import java.util.ArrayList;
import java.util.List;

public class GeofenceTransitionService extends IntentService {
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public GeofenceTransitionService(String name) {
        super(name);
    }

    public GeofenceTransitionService(){
        super("Running");
        Log.d("Runned 1","RUNNING 1");
    }


    @Override
    protected void onHandleIntent(@Nullable Intent intent) {

        Log.d("Runned 2","RUNNING 2");
        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        if(geofencingEvent.hasError()){
            String error = String.valueOf(geofencingEvent.getErrorCode());
            Toast.makeText(this,"Error code = "+ error,Toast.LENGTH_LONG).show();
            return;
        }

        int geofenceTransition = geofencingEvent.getGeofenceTransition();
        if(geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER || geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT){
            List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
            String geoTransDetails = getGeofenceTransitionDetails(geofenceTransition,triggeringGeofences);
        }
    }

    private String getGeofenceTransitionDetails(int geofenceTransition, List<Geofence> triggeringGeofences) {
        ArrayList<String> triggerFenceList = new ArrayList<>();
        for (Geofence geofence : triggeringGeofences) {
            triggerFenceList.add(geofence.getRequestId());
        }
        String status = null;
        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {

            startAlert();
            Toast.makeText(this,"Entering into Location",Toast.LENGTH_LONG).show();
            status = "ENTERING:";

        } else if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
            status = "EXIT";
            Toast.makeText(this,"Exiting From Location",Toast.LENGTH_LONG).show();
        }
        return status + TextUtils.join(",", triggerFenceList);

    }

    public void startAlert(){

        int i = 200;
        Intent intent = new Intent(this, AlarmService.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this.getApplicationContext(), 234324243, intent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                + (i * 1000), pendingIntent);
        Toast.makeText(this, "Alarm set in " + i + " seconds",Toast.LENGTH_LONG).show();
    }
}

0 个答案:

没有答案