首页 > 解决方案 > 未收到基于位置半径的地理围栏通知

问题描述

我正在尝试在应用程序中实现地理围栏。一旦用户进入地理围栏半径,就会向用户显示通知,我尝试了以下代码但没有收到通知。纬度和经度基于我在地理围栏半径内的位置。任何帮助将不胜感激:

MainActivity.java

public class MainActivity extends AppCompatActivity implements LocationListener{

        PendingIntent mGeofencePendingIntent;
        public static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 100;
        private List<Geofence> mGeofenceList;
        private GoogleApiClient mGoogleApiClient;
        public static final String TAG = "Activity";
        LocationRequest mLocationRequest;
        double currentLatitude = 23.0023593, currentLongitude = 72.6665668;
        Boolean locationFound;
        protected LocationManager locationManager;
        protected LocationListener locationListener;

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

            if (savedInstanceState == null) {
                mGeofenceList = new ArrayList<Geofence>();

                int resp = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
                if (resp == ConnectionResult.SUCCESS) {
                    initGoogleAPIClient();
                    createGeofences(currentLatitude, currentLongitude);
                } else {
                    Log.e(TAG, "Your Device doesn't support Google Play Services.");
                }

                // Create the LocationRequest object
                mLocationRequest = LocationRequest.create()
                        .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                        .setInterval(1000)        
                        .setFastestInterval(1000);

            }

        }

        public void initGoogleAPIClient() {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(connectionAddListener)
                    .addOnConnectionFailedListener(connectionFailedListener)
                    .build();
            mGoogleApiClient.connect();
        }

        private GoogleApiClient.ConnectionCallbacks connectionAddListener =
                new GoogleApiClient.ConnectionCallbacks() {
                    @Override
                    public void onConnected(Bundle bundle) {
                        Log.i(TAG, "onConnected");

                        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

                        if (location == null) {
                            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, MainActivity.this);

                        } else {

                            currentLatitude = location.getLatitude();
                            currentLongitude = location.getLongitude();

                            Log.i(TAG, currentLatitude + " WORKS " + currentLongitude);

                            createGeofences(currentLatitude, currentLongitude);

                        }

                        try {
                            LocationServices.GeofencingApi.addGeofences(
                                    mGoogleApiClient,
                                    getGeofencingRequest(),
                                    getGeofencePendingIntent()
                            ).setResultCallback(new ResultCallback<Status>() {

                                @Override
                                public void onResult(Status status) {
                                    if (status.isSuccess()) {
                                        Log.i(TAG, "Saving Geofence");

                                    } else {
                                        Log.e(TAG, "Registering geofence failed: " + status.getStatusMessage() +
                                                " : " + status.getStatusCode());
                                    }
                                }
                            });

                        } catch (SecurityException securityException) {
                            Log.e(TAG, "Error");
                        }
                    }

                    @Override
                    public void onConnectionSuspended(int i) {
                        Log.e(TAG, "onConnectionSuspended");
                    }
                };

        public void createGeofences(double latitude, double longitude) {
            String id = UUID.randomUUID().toString();
            Geofence fence = new Geofence.Builder()
                    .setRequestId(id)
                    .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                    .setCircularRegion(latitude, longitude, 1000)
                    .setExpirationDuration(Geofence.NEVER_EXPIRE)
                    .build();
            mGeofenceList.add(fence);
        }

        private GoogleApiClient.OnConnectionFailedListener connectionFailedListener =
                new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(ConnectionResult connectionResult) {
                        Log.e(TAG, "onConnectionFailed");
                    }
                };

        private GeofencingRequest getGeofencingRequest() {
            GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
            builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
            builder.addGeofences(mGeofenceList);
            return builder.build();
        }

        private PendingIntent getGeofencePendingIntent() {

            if (mGeofencePendingIntent != null) {
                return mGeofencePendingIntent;
            }

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

        @Override
        public void onLocationChanged(Location location) {
            currentLatitude = location.getLatitude();
            currentLongitude = location.getLongitude();
            Log.i(TAG, "onLocationChanged");
        }
    }

GeofenceTransitionsIntentService.java

public class GeofenceTransitionsIntentService extends IntentService {

    private static final String TAG = "GeofenceTransitions";

    public GeofenceTransitionsIntentService() {
        super("GeofenceTransitionsIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.i(TAG, "onHandleIntent");

        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        if (geofencingEvent.hasError()) {
            //String errorMessage = GeofenceErrorMessages.getErrorString(this,
            //      geofencingEvent.getErrorCode());
            Log.e(TAG, "Goefencing Error " + geofencingEvent.getErrorCode());
            return;
        }

        int geofenceTransition = geofencingEvent.getGeofenceTransition();

        Log.i(TAG, "geofenceTransition = " + geofenceTransition + " Enter : " + Geofence.GEOFENCE_TRANSITION_ENTER + "Exit : " + Geofence.GEOFENCE_TRANSITION_EXIT);
        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER || geofenceTransition == Geofence.GEOFENCE_TRANSITION_DWELL){
            showNotification("Entered", "Entered the Location");
        }
        else if(geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
            Log.i(TAG, "Showing Notification...");
            showNotification("Exited", "Exited the Location");
        } else {
            showNotification("Error", "Error");
            Log.e(TAG, "Error ");
        }
    }

    public void showNotification(String text, String bigText) {
        NotificationManager notificationManager =
                (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Title")
                .setContentText(text)
                .setContentIntent(pendingNotificationIntent)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(bigText))
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(true)
                .build();
        notificationManager.notify(0, notification);
    }
}

清单.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.com.geofincingdemo">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".GeofenceTransitionsIntentService"
            android:exported="true" />
    </application>

</manifest>

我的 GPS 也以高精度开启,我在 API 级别 23 上运行。

标签: androidandroid-gpsandroid-geofence

解决方案


推荐阅读