无法使用Geofire检测应用程序(Android)的其他用户

时间:2018-04-16 13:11:54

标签: android firebase geofire

我正在使用Geofire在一定范围内检测同一应用的用户。 我使用后台服务这样做。数据已更新到Firebase数据库,代码看起来很好,但无法检测到我的范围大约1 km的其他用户。

我想知道我使用的应用的某些用户是否在我附近。 即使用户坐在我旁边,使用相同的应用程序,我也无法检索任何信息。

以下是该服务的代码。 。 。

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) {

    }
}

下面给出了如何将数据存储在firebase中的示例。 。

My Firebase Database sample . . .

我应该怎样做才能完成手头的任务。

0 个答案:

没有答案