地理围栏绘图不显示圆边界

时间:2019-03-21 17:28:27

标签: android geofencing

因此,我正在遵循有关地理围栏的教程,但是后来GeoFencingApi和FusedLocation更改为FusedLocationProviderClient和GeofencingClient,这让我感到困惑,并寻找了一些答案。 现在的问题是,即使我按照教程进行操作,也无法显示边界圆。

这是我现在正在处理的代码:

地图活动

public class MapActivity extends AppCompatActivity implements OnMapReadyCallback, LocationListener,
        GoogleMap.OnMarkerClickListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        GoogleMap.OnMapClickListener,
        ResultCallback<Status>
      {

    //Map Access
    private GoogleMap mMap;
    private ChildEventListener mChildEventListener;
    private DatabaseReference mChild;
    Marker marker;
    private static final String TAG = "UserProfile";
    private final Handler handler = new Handler();
    private static final float DEFAULT_ZOOM = 15f;
    SmsReceiver smsReceiver = new SmsReceiver();
    private HashMap<String, Double> coordinates = new HashMap<String, Double>();

    private GoogleApiClient googleApiClient;
    private GeofencingClient geofencingClient;
    LocationRequest request;
    LatLng latLngStart;
    private static final String NOTIFICATION_MSG = "NOTIFICATION MSG";
    // Create a Intent send by the notification
    public static Intent makeNotificationIntent(Context context, String msg) {
              Intent intent = new Intent( context, MapActivity.class );
              intent.putExtra( NOTIFICATION_MSG, msg );
              return intent;
    }
    private FusedLocationProviderClient fusedLocationClient;

          //SMS
    private static final int SMS_PERMISSION_CODE = 0;


  //  RecyclerAdapter recyclerAdapter;
  //  ArrayList<ChildArray> carray = new ArrayList<>();
  //  SQLiteDatabase sqLiteDatabase;


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

        geofencingClient = LocationServices.getGeofencingClient(this);
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        createGoogleApi();

        if (!hasReadSmsPermission()) {
            showRequestPermissionsInfoAlertDialog();
        }

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

        ChildEventListener mChildEventListener;
        mChild = FirebaseDatabase.getInstance().getReference("conilocationdata/conilocationdata/conilocationdata");
        mChild.push().setValue(marker);


        DBHelper mydb = new DBHelper(this);
        sqLiteDatabase = mydb.getReadableDatabase();

//        refreshDataList();
    }

          // Create GoogleApiClient instance
          private void createGoogleApi() {
              Log.d(TAG, "createGoogleApi()");
              if ( googleApiClient == null ) {
                  googleApiClient = new GoogleApiClient.Builder( this )
                          .addConnectionCallbacks( this )
                          .addOnConnectionFailedListener( this )
                          .addApi( LocationServices.API )
                          .build();
              }
          }

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

              // Call GoogleApiClient connection when starting the Activity
              googleApiClient.connect();
          }

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

              // Disconnect GoogleApiClient when stopping Activity
              googleApiClient.disconnect();
          }

          @Override
          public void onConnected(@Nullable Bundle bundle) {
              Log.d(TAG, "Google Api Client Connected");
              request = new LocationRequest().create();
              request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
              request.setInterval(1000);

//              LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, request, this);
              fusedLocationClient.getLastLocation()
                      .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                          @Override
                          public void onSuccess(Location location) {

                              if (location != null) 
                              {
                                  // Logic to handle location object
                              }
                          }
                      });
                     }

          @Override
          public void onConnectionSuspended(int i) 
          {
              Log.d(TAG, "Google Connection Suspended");
          }

          @Override
          public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
              Log.e(TAG, "Connection Failed:" + connectionResult.getErrorMessage());
          }

          @Override
          public void onLocationChanged(Location location) {

          }

          public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        switch (id) {
            case R.id.add_boundary:
                startGeofence();
                break;
            case R.id.menu_acctset:
                //Insert Intent
                break;

            case R.id.menu_logout:
                Intent toMain = new Intent(MapActivity.this, MainActivity.class);
                startActivity(toMain);
                Toast.makeText(MapActivity.this, "Disconnected.", Toast.LENGTH_SHORT).show();
                break;
        }
        return true;
}
          @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(GEOFENCE_RADIUS);

                  geoFenceLimits = mMap.addCircle(circleOptions);

          }

          // Add the created GeofenceRequest to the device's monitoring list
            private void addGeofence(final GeofencingRequest request) {

                geofencingClient.addGeofences(request, createGeofencePendingIntent())
                        .addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                                // your success code
                              drawGeoFence();
                        createGeofencePendingIntent();
                            }
                        })
                        .addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                // your fail code;
                            }
                        });}


          private PendingIntent geoFencePendingIntent;
          private final int GEOFENCE_REQ_CODE = 0;
          private PendingIntent createGeofencePendingIntent() {
              if ( geoFencePendingIntent != null )
                  return geoFencePendingIntent;

              Intent intent = new Intent( this, GeofenceTransitionService.class);
              return PendingIntent.getService(
                      this, GEOFENCE_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT );
          }

          // Start Geofence creation process
        private void startGeofence() {
            if( geoFenceMarker != null ) {
                Geofence geofence = createGeofence( geoFenceMarker.getPosition(), GEOFENCE_RADIUS );
                GeofencingRequest geofenceRequest = createGeofenceRequest( geofence );
                addGeofence( geofenceRequest );
            } else {
                Log.e(TAG, "Geofence marker is null");
            }
        }

          private static final long GEO_DURATION = 60 * 60 * 1000;
          private static final String GEOFENCE_REQ_ID = "My Geofence";
          private static final float GEOFENCE_RADIUS = 500f; // in meters

          // Create a Geofence
          private Geofence createGeofence(LatLng latLng, float radius ) {
              return new Geofence.Builder()
                      .setRequestId(GEOFENCE_REQ_ID)
                      .setCircularRegion( latLng.latitude, latLng.longitude, radius)
                      .setExpirationDuration( GEO_DURATION )
                      .setTransitionTypes( Geofence.GEOFENCE_TRANSITION_ENTER
                              | Geofence.GEOFENCE_TRANSITION_EXIT )
                      .build();
          }

          // Create a Geofence Request
          private GeofencingRequest createGeofenceRequest( Geofence geofence) {
              return new GeofencingRequest.Builder()
                      .setInitialTrigger( GeofencingRequest.INITIAL_TRIGGER_ENTER )
                      .addGeofence(geofence)
                      .build();
          }


    @Override
    public boolean onMarkerClick(Marker marker) {
        return false;
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

        mMap = googleMap;
        mMap.setMinZoomPreference(15.0f);
        mMap.setMaxZoomPreference(20.0f);
        mMap.setOnMapClickListener(this);
        mMap.setOnMarkerClickListener(this);
        final LatLng putatan = new LatLng(14.397420, 121.033051);

        final DatabaseReference mRef = FirebaseDatabase.getInstance().getReference("conilocationdata");

        ValueEventListener postListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // Get Post object and use the values to update the UI

                for(DataSnapshot ds : dataSnapshot.getChildren()) {

                    Bundle bundle = getIntent().getExtras();
                    if(bundle != null) {
                        double lat1 = bundle.getDouble("lat");
                        double lon2 = bundle.getDouble("lon");

                        LatLng location = new LatLng(lat1,lon2);
                        marker = mMap.addMarker(new MarkerOptions()
                                .position(location)
                                .title("Here")
                                .flat(true));

    mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
                    } else {
                        System.out.println("Bundle null");
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                // Getting Post failed, log a message
                Log.w(TAG, "loadPost:onCancelled", databaseError.toException());

            }
        };
        mRef.orderByKey().limitToLast(1).addValueEventListener(postListener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

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

          Marker geoFenceMarker;
          private void markerForGeofence(LatLng latLng) {
            MarkerOptions optionMarker = new MarkerOptions()
                    .position(latLng)
                    .title("Geofence Marker");


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

                geoFenceMarker = mMap.addMarker(optionMarker);
            }

          }

          private void removeGeofenceDraw() {
              Log.d(TAG, "removeGeofenceDraw()");
              if ( geoFenceMarker != null)
                  geoFenceMarker.remove();
              if ( geoFenceLimits != null )
                  geoFenceLimits.remove();
          }


          //    SMS PERMISSIONS

          private void showRequestPermissionsInfoAlertDialog() {
              AlertDialog.Builder builder = new AlertDialog.Builder(this);
              builder.setTitle(R.string.permission_alert_dialog_title);
              builder.setMessage(R.string.permission_dialog_message);
              builder.setPositiveButton(R.string.action_ok, new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                      dialog.dismiss();
                      requestReadAndSendSmsPermission();
                  }
              });
              builder.show();
          }

          private boolean hasReadSmsPermission() {
              return ContextCompat.checkSelfPermission(MapActivity.this,
                      Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED &&
                      ContextCompat.checkSelfPermission(MapActivity.this,
                              Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED;
          }

          private void requestReadAndSendSmsPermission() {
              if (ActivityCompat.shouldShowRequestPermissionRationale(MapActivity.this, Manifest.permission.READ_SMS)) {
                  Log.d(TAG, "shouldShowRequestPermissionRationale(), no permission requested");
                  return;
              }
              ActivityCompat.requestPermissions(MapActivity.this, new String[]{Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS},
                      SMS_PERMISSION_CODE);
          }
 }

GeoFenceTransitionService活动

import static android.support.constraint.Constraints.TAG;
import static com.google.android.gms.common.GooglePlayServicesUtilLight.getErrorString;

class GeofenceTransitionService extends IntentService {
    public static final int GEOFENCE_NOTIFICATION_ID = 0;

    public GeofenceTransitionService(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        // Handling errors
        if ( geofencingEvent.hasError() ) {
            String errorMsg = String.valueOf(geofencingEvent.getErrorCode() );
            Toast.makeText(getApplicationContext(), "Error Code" +errorMsg,Toast.LENGTH_SHORT).show();
            return;
        }

        int geoFenceTransition = geofencingEvent.getGeofenceTransition();
        // Check if the transition type is of interest
        if ( geoFenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
                geoFenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT ) {
            // Get the geofence that were triggered
            List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();

            String geofenceTransitionDetails = getGeofenceTrasitionDetails(geoFenceTransition, triggeringGeofences );

            // Send notification details as a String
            sendNotification( geofenceTransitionDetails );
        }
    }

    private String getGeofenceTrasitionDetails(int geoFenceTransition, List<Geofence> triggeringGeofences) {
        // get the ID of each geofence triggered
        ArrayList<String> triggeringGeofencesList = new ArrayList<>();
        for ( Geofence geofence : triggeringGeofences ) {
            triggeringGeofencesList.add( geofence.getRequestId() );
        }

        String status = null;
        if ( geoFenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER )
            status = "Entering ";
        else if ( geoFenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT )
            status = "Exiting ";
        return status + TextUtils.join( ", ", triggeringGeofencesList);
    }

    private void sendNotification( String msg ) {
        Log.i(TAG, "sendNotification: " + msg );

        // Intent to start the main Activity
        Intent notificationIntent = MapActivity.makeNotificationIntent(
                getApplicationContext(), msg
        );

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(notificationIntent);
        PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);


        // Creating and sending Notification
        NotificationManager notificatioMng =
                (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE );
        notificatioMng.notify(
                GEOFENCE_NOTIFICATION_ID,
                createNotification(msg, notificationPendingIntent));

    }

    // Create notification
    private Notification createNotification(String msg, PendingIntent notificationPendingIntent) {
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
        notificationBuilder
                .setSmallIcon(R.drawable.ic_location_on_black_24dp)
                .setColor(Color.RED)
                .setContentTitle(msg)
                .setContentText("Geofence Notification!")
                .setContentIntent(notificationPendingIntent)
                .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
                .setAutoCancel(true);
        return notificationBuilder.build();
    }


    private static String getErrorString(int errorCode) {
        switch (errorCode) {
            case GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE:
                return "GeoFence not available";
            case GeofenceStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES:
                return "Too many GeoFences";
            case GeofenceStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS:
                return "Too many pending intents";
            default:
                return "Unknown error.";
        }
    }
}

这是我关注的教程的链接:[地理学教程] https://www.youtube.com/watch?v=iIsQeCPGU2U

https://github.com/tinmegali/geofencing_tutorial

0 个答案:

没有答案