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 . .
What should I do to achieve the task at hand.