0

I am using Geofire to detect users of the same app within a certain range. Am using a background services to do so. The data has been updated to the Firebase database and the code looks fine but couldn't detect the other user which is in my range approx 1 km.

I want to know if some user of the app that I am using is near me. I couldn't retrieve any information even if the user is sitting next to me, using the same app.

Here is the code for the service . . . .

public class Service_Location extends Service implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    long BACKGROUND_INTERVAL = 10000;

    String TAG = "Service_Location";

    String U_id, U_key, Usr_Name;
    PendingIntent pendingIntent;

    NotificationManager mNotificationManager;
    NotificationCompat.Builder notice;
    Intent intent, intent_Map;
    //Firebase Reference . . . .
    DatabaseReference databaseReference;
    FirebaseAuth auth = FirebaseAuth.getInstance();
    FirebaseUser user;

    //GeoFire Reference . . . .

    GeoFire geofire;
    GeoQuery geoQuery;

    SharedPreferences preferences;
    SharedPreferences.Editor editor;

    public Service_Location() {
        super();
    }

    //Google Api Connection . . .
    @SuppressLint("RestrictedApi")
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("Loc", "Service_Location");
        //Shared Preferences . . .
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        //
        user = auth.getCurrentUser();
        U_key = auth.getUid();
        if (user != null) {
            U_id = user.getDisplayName();
        }
        Log.d("FireBase_Data", "U_id: " + U_id);
        databaseReference = FirebaseDatabase.getInstance().getReference();
        Log.d("FireBase_Data", "databaseReference: " + databaseReference);
        geofire = new GeoFire(databaseReference.child(U_key));

        //creating intent if the notification is selected . . .
        try {
            //the builder
            notice = new NotificationCompat.Builder(this);
            notice.setContentTitle("NearBy");
            notice.setSmallIcon(R.drawable.logo);
            //the notification manager . .
            mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            //intent and pending intent . . .
            intent = new Intent(this, MapsNotif.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
            //pass the PendingIntent to the notification
            notice.setContentIntent(pendingIntent);
        } catch (Exception e) {
            Log.d(TAG, String.valueOf(e));
        }
        try {
            if (isGooglePlayServicesAvailable()) {
                mLocationRequest = new LocationRequest();
                mLocationRequest.setInterval(BACKGROUND_INTERVAL);
                mLocationRequest.setFastestInterval(BACKGROUND_INTERVAL);
                mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                //mLocationRequest.setSmallestDisplacement(10.0f);  /* min dist for location change, here it is 10 meter */
                mGoogleApiClient = new GoogleApiClient.Builder(this)
                        .addApi(LocationServices.API)
                        .addConnectionCallbacks(this)
                        .addOnConnectionFailedListener(this)
                        .build();

                mGoogleApiClient.connect();
            }
        } catch (Exception e) {
            Log.d(TAG, String.valueOf(e));
        }
        //intent for tr MapsNotify Activity . . . .
        //intent_Map = new Intent(this, MapsNotif.class);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "Data received from intent Reference_id:" + intent.getStringExtra("Reference_id"));
        //reference_id = intent.getStringExtra("Reference_id");
        return START_STICKY;
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        //When remove app from background then start it again
        startService(new Intent(this, Service_Location.class));
        super.onTaskRemoved(rootIntent);
    }


    private boolean isGooglePlayServicesAvailable() {
        Log.d(TAG, "isGooglePlayServicesAvailable()");
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        return ConnectionResult.SUCCESS == status;
    }

    //Service
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    //Location Listener. . .
    @Override
    public void onLocationChanged(final Location location) {
        Log.d(TAG, "OnLocationChanged()");
        update(location);
    }

    private void update(Location location) {

        final GeoLocation geoLocation = new GeoLocation(location.getLatitude(), location.getLongitude());
        Log.d(TAG, "Updating Location");

        //databaseReference.setValue(map);

        try {
            geofire.setLocation(U_key, geoLocation, new GeoFire.CompletionListener() {
                @Override
                public void onComplete(String key, DatabaseError error) {
                    if (error != null) {
                        Log.d(TAG, String.valueOf(error));
                    } else {
                        Log.d(TAG, "Location Updated");
                    }
                }
            });
            geoQuery = geofire.queryAtLocation(geoLocation, 1);
        } catch (Exception e) {
            Log.d(TAG, String.valueOf(e));
        }

        try {
            geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
                @Override
                public void onKeyEntered(String key, GeoLocation location) {
                    if (!key.equals(U_key)) {
                        DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child(key);
                        Log.d("QUERY", "key: " + key + " entered your proximity. . .");
                        Log.d("QUERY", "Location: " + location);

                        editor = preferences.edit();
                        editor.putFloat("Latitude", (float) location.latitude);
                        editor.putFloat("Longitude", (float) location.longitude);
                        editor.apply();

                        reference.addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                Usr_Name = (String) dataSnapshot.child("UserName").getValue();
                                Log.d("QUERY_", "UserName: " + Usr_Name);
                                sendNotif(Usr_Name);
                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {
                                Log.d("QUERY_", String.valueOf(databaseError));
                            }
                        });
                    }
                }

                @Override
                public void onKeyExited(String key) {
                    if (!key.equals(U_key)) {
                        Log.d("QUERY", "key: " + key + " left your proximity. . .");
                        DatabaseReference reference = FirebaseDatabase.getInstance().getReference(key);
                        reference.addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                Usr_Name = (String) dataSnapshot.child("UserName").getValue();
                                Log.d("QUERY_", "UserName: " + Usr_Name);
                                sendNotif1(Usr_Name);
                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {
                                Log.d("QUERY_", String.valueOf(databaseError));
                            }
                        });
                    }
                }

                private void sendNotif1(String name) {
                    Toast.makeText(getApplicationContext(), name + " is leaving your area ", Toast.LENGTH_SHORT).show();
                    notice.setContentText(name + " is leaving your area Don't let go . . ");
                    mNotificationManager.notify(0, notice.build());
                }

                private void sendNotif(String name) {
                    Toast.makeText(getApplicationContext(), name + " is around you . . .", Toast.LENGTH_SHORT).show();
                    notice.setContentText(name + " is around you . . .");
                    mNotificationManager.notify(0, notice.build());
                }

                @Override
                public void onKeyMoved(String key, GeoLocation location) {
                    Log.d("QUERY_", "UserName: " + "On Key Moved . . .");
                }

                @Override
                public void onGeoQueryReady() {
                    Log.d("QUERY_", "onGeoQueryReady()");
                }

                @Override
                public void onGeoQueryError(DatabaseError error) {
                    Log.d("QUERY_", String.valueOf(error));
                }
            });
        } catch (Exception e) {
            Log.d("QUERY_", String.valueOf(e));
        }
    }

    //Google API Client

    public void onConnected(Bundle bundle) {
        Log.d(TAG, "On_Connected()");
        Log.d(TAG, "Moving to getDocs()");
        startLocationUpdates();
    }

    protected void startLocationUpdates() {
        Log.d(TAG, "onStartLocationUpdates()");
        try {
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions((Activity) getBaseContext(), new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 0);
                return;
            }
            PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
                    mGoogleApiClient, mLocationRequest, this);
        } catch (Exception e) {
            Log.d("Service", String.valueOf(e));
        }
    }


    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
}

An example on how data is stored in firebase is given below . .

My Firebase Database sample . . .

What should I do to achieve the task at hand.

André Kool
  • 4,668
  • 12
  • 33
  • 43
jack
  • 29
  • 5
  • 1
    Questions seeking debugging help ("**why isn't this code working?**") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it **in the question itself**. Questions without a **clear problem statement** are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Zun Apr 16 '18 at 13:17
  • How to debug :: https://stackoverflow.com/questions/32902702/how-to-debug-in-android-studio OR THIS :: https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems – Barns Apr 16 '18 at 13:30
  • My question was more related to geofire and firebase. I have edited this question. I hope this will help the readers to help me solve this issue – jack Apr 16 '18 at 13:40
  • You'll find that Stack Overflow is an incredibly inefficient remote debugging tool. So instead of just saying that the code doesn't work, try to show us what did and didn't happen. For example, does `update ` ever get called? If so, what's the value of `location `? Does it ever get to `addGeoQueryEventListener`? If so, does your `onKeyEntered` get triggered? If so, what is the value of `key` in there? – Frank van Puffelen Apr 16 '18 at 14:30
  • update gets called ,the value of location is same as my current location and the key is same as that of the current user I dot get the key neither the location of the other user in my proximity – jack Apr 16 '18 at 14:35
  • Well this helped me in solving this problem https://stackoverflow.com/questions/35301799/geofire-query-on-user-location – jack Apr 16 '18 at 19:55

0 Answers0