应用在后台时,地理围栏通知未被触发

9

我已经查看了很多 SO 帖子,但是对我来说仍然没有用。

我正在尝试在设备进入地理围栏时触发通知,但除非应用程序打开,否则不会触发。

如何在应用程序在后台运行时触发通知?

地理围栏:

public class Geofencing implements ResultCallback {

    // Constants
    public static final String TAG = Geofencing.class.getSimpleName();
    private static final float GEOFENCE_RADIUS = 50; // 50 meters
    private static final long GEOFENCE_TIMEOUT = 24 * 60 * 60 * 1000; // 24 hours

    private List<Geofence> mGeofenceList;
    private PendingIntent mGeofencePendingIntent;
    private GoogleApiClient mGoogleApiClient;
    private Context mContext;

    public Geofencing(Context context, GoogleApiClient client) {
        mContext = context;
        mGoogleApiClient = client;
        mGeofencePendingIntent = null;
        mGeofenceList = new ArrayList<>();
    }

    /***
     * Registers the list of Geofences specified in mGeofenceList with Google Place Services
     * Uses {@code #mGoogleApiClient} to connect to Google Place Services
     * Uses {@link #getGeofencingRequest} to get the list of Geofences to be registered
     * Uses {@link #getGeofencePendingIntent} to get the pending intent to launch the IntentService
     * when the Geofence is triggered
     * Triggers {@link #onResult} when the geofences have been registered successfully
     */
    public void registerAllGeofences() {
        // Check that the API client is connected and that the list has Geofences in it
        if (mGoogleApiClient == null || !mGoogleApiClient.isConnected() ||
                mGeofenceList == null || mGeofenceList.size() == 0) {
            return;
        }
        try {
            LocationServices.GeofencingApi.addGeofences(
                    mGoogleApiClient,
                    getGeofencingRequest(),
                    getGeofencePendingIntent()
            ).setResultCallback(this);
        } catch (SecurityException securityException) {
            // Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
            Log.e(TAG, securityException.getMessage());
        }
    }

    /***
     * Unregisters all the Geofences created by this app from Google Place Services
     * Uses {@code #mGoogleApiClient} to connect to Google Place Services
     * Uses {@link #getGeofencePendingIntent} to get the pending intent passed when
     * registering the Geofences in the first place
     * Triggers {@link #onResult} when the geofences have been unregistered successfully
     */
    public void unRegisterAllGeofences() {
        if (mGoogleApiClient == null || !mGoogleApiClient.isConnected()) {
            return;
        }
        try {
            LocationServices.GeofencingApi.removeGeofences(
                    mGoogleApiClient,
                    // This is the same pending intent that was used in registerGeofences
                    getGeofencePendingIntent()
            ).setResultCallback(this);
        } catch (SecurityException securityException) {
            // Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission.
            Log.e(TAG, securityException.getMessage());
        }
    }


    /***
     * Updates the local ArrayList of Geofences using data from the passed in list
     * Uses the Place ID defined by the API as the Geofence object Id
     *
     * @param places the PlaceBuffer result of the getPlaceById call
     */
    public void updateGeofencesList(PlaceBuffer places) {
        mGeofenceList = new ArrayList<>();
        if (places == null || places.getCount() == 0) return;
        for (Place place : places) {
            // Read the place information from the DB cursor
            String placeUID = place.getId();
            double placeLat = place.getLatLng().latitude;
            double placeLng = place.getLatLng().longitude;
            // Build a Geofence object
            Geofence geofence = new Geofence.Builder()
                    .setRequestId(placeUID)
                    .setExpirationDuration(GEOFENCE_TIMEOUT)
                    .setCircularRegion(placeLat, placeLng, GEOFENCE_RADIUS)
                    .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                    .build();
            // Add it to the list
            mGeofenceList.add(geofence);
        }
    }

    /***
     * Creates a GeofencingRequest object using the mGeofenceList ArrayList of Geofences
     * Used by {@code #registerGeofences}
     *
     * @return the GeofencingRequest object
     */
    private GeofencingRequest getGeofencingRequest() {
        GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
        builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
        builder.addGeofences(mGeofenceList);
        return builder.build();
    }

    /***
     * Creates a PendingIntent object using the GeofenceTransitionsIntentService class
     * Used by {@code #registerGeofences}
     *
     * @return the PendingIntent object
     */
    private PendingIntent getGeofencePendingIntent() {
        // Reuse the PendingIntent if we already have it.
        if (mGeofencePendingIntent != null) {
            return mGeofencePendingIntent;
        }
        //Intent intent = new Intent(mContext, GeofenceBroadcastReceiver.class);
        Intent intent = new Intent("com.aol.android.geofence.ACTION_RECEIVE_GEOFENCE");
        mGeofencePendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.
                FLAG_UPDATE_CURRENT);
        return mGeofencePendingIntent;
    }

    @Override
    public void onResult(@NonNull Result result) {
        Log.e(TAG, String.format("Error adding/removing geofence : %s",
                result.getStatus().toString()));
    }

}

GeofenceBroadcastReceiver:

public class GeofenceBroadcastReceiver extends BroadcastReceiver {

    public static final String TAG = GeofenceBroadcastReceiver.class.getSimpleName();

    /***
     * Handles the Broadcast message sent when the Geofence Transition is triggered
     * Careful here though, this is running on the main thread so make sure you start an AsyncTask for
     * anything that takes longer than say 10 second to run
     *
     * @param context
     * @param intent
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        // Get the Geofence Event from the Intent sent through

        Log.d("onRecccc","trt");

        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        if (geofencingEvent.hasError()) {
            Log.e(TAG, String.format("Error code : %d", geofencingEvent.getErrorCode()));
            return;
        }

        // Get the transition type.
        int geofenceTransition = geofencingEvent.getGeofenceTransition();
        // Check which transition type has triggered this event

        // Send the notification
        sendNotification(context, geofenceTransition);
    }


    /**
     * Posts a notification in the notification bar when a transition is detected
     * Uses different icon drawables for different transition types
     * If the user clicks the notification, control goes to the MainActivity
     *
     * @param context        The calling context for building a task stack
     * @param transitionType The geofence transition type, can be Geofence.GEOFENCE_TRANSITION_ENTER
     *                       or Geofence.GEOFENCE_TRANSITION_EXIT
     */
    private void sendNotification(Context context, int transitionType) {
        // Create an explicit content Intent that starts the main Activity.
        Intent notificationIntent = new Intent(context, MainActivity.class);

        // Construct a task stack.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);

        // Add the main Activity to the task stack as the parent.
        stackBuilder.addParentStack(MainActivity.class);

        // Push the content Intent onto the stack.
        stackBuilder.addNextIntent(notificationIntent);

        // Get a PendingIntent containing the entire back stack.
        PendingIntent notificationPendingIntent =
                stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        // Get a notification builder
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

        // Check the transition type to display the relevant icon image
        if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER) {
            builder.setSmallIcon(R.drawable.ic_near_me_black_24dp)
                    .setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
                            R.drawable.ic_near_me_black_24dp))
                    .setContentTitle("You have a task nearby")
                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                    //Vibration
                    .setVibrate(new long[]{300,300})
                    .setLights(Color.RED, 3000, 3000);
                    //LED


        } else if (transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {
            builder.setSmallIcon(R.drawable.ic_near_me_black_24dp)
                    .setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
                            R.drawable.ic_near_me_black_24dp))
                    .setContentTitle(context.getString(R.string.back_to_normal));
        }

        // Continue building the notification
        builder.setContentText(context.getString(R.string.touch_to_relaunch));
        builder.setContentIntent(notificationPendingIntent);

        // Dismiss notification once the user touches it.
        builder.setAutoCancel(true);

        // Get an instance of the Notification manager
        NotificationManager mNotificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        // Issue the notification
        mNotificationManager.notify(0, builder.build());
    }

}

编辑:

 @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        //Create geofences from SharedPreferences/network responses
        //Connect to location services


        mClient = new GoogleApiClient.Builder(this)

                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .addApi(Places.GEO_DATA_API)
                .addApi(Places.PLACE_DETECTION_API)
                .build();

        mGeofencing = new Geofencing(this, mClient);
        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        if (geofencingEvent.hasError()) {
            Log.e("dsadsa", String.format("Error code : %d", geofencingEvent.getErrorCode()));
            return;
        }
    }


    public void onConnected(Bundle bundle) {
        //Add geofences
        mGeofencing.registerAllGeofences();

    }

我到目前为止已经尝试了这些方法,但仍然没有成功...


阅读评论可能会有帮助:https://stackoverflow.com/questions/45218070/request-in-android-always-giving-socket-timeout-exception - Pavneet_Singh
我更新了我的回答... - Elior
2个回答

0

当应用程序在后台运行时(用户点击Home按钮或多次返回直到看到主屏幕),我遇到了同样的问题。

我尝试通过在清单中注册BroadcastReceiver来解决它,而不是使用IntentService。但结果并没有太大帮助。

然后,我尝试了这个方法: 打开应用程序,添加一个地理围栏,然后转到主屏幕。 你可能已经明白了,地理围栏没有触发。 但是,当我点击Google Maps而不是我的应用程序时,它被触发了!

因此,如果有任何应用程序请求位置更新(如Google Maps),则似乎在后台工作。

所以我尝试了这种方法: 我创建了一个粘性服务来请求位置更新,使用LocationServices.FusedLocationApi。这个服务包含GoogleApiClient并实现了GoogleApiClient.ConnectionCallbacksGoogleApiClient.OnConnectionFailedListener

但是猜猜?它仍然无法在后台工作 :(

更新: 在我尝试了很多次让它工作后,它终于成功了! 我有一个带有Google Play服务(版本11.3.02)Android 7.0的Android模拟器。 如果你想要一个关于如何使用Geofence以及如何通过模拟器检查它的好的解释,请查看此链接

现在,当应用程序处于前台和后台时,我已经尝试使用这个模拟器进行地理围栏,它运行良好!
当我说它在后台对我不起作用时,那个模拟器上的Android版本是Android 8。 所以,我猜我需要为Android 8找到一个解决方案 ->一个很好的开始是这个文档链接,他们解释了如何处理前台和后台应用程序。


我的甚至在打开地图时都没有触发:'),如果你解决了,请告诉我并发布你的代码。 - devcodes
@Elior,虽然我不明白为什么我们需要请求位置更新,但在Android 7上它完美运行……地理围栏应该由Play Services触发……这很奇怪。不过,在Android 8上要让它正常工作就比较困难了,因为有后台限制。让我们看看我们能取得什么成果。 - Giulio Bider
1
@GiulioBider 关于Android 8,我知道...它让我发疯 :) 他们建议使用前台服务,这样应用程序将保持在前台,然后可能会在应用程序在后台时触发地理围栏。 我看到的另一个解决方案(并首先尝试)是注册BroadcastReceiver,而不是执行PendingIntent.getService,执行PendingIntent.getBroadcast..还必须有一个逻辑来检查Android版本是否大于或等于Android 8,然后使用PendingIntent.getBroadcast。否则使用PendingIntent.getService - Elior
@GiulioBider 请查看此链接 https://codelabs.developers.google.com/codelabs/background-location-updates-android-o/index.html?index=..%2F..%2Fio2017#0 - Elior
1
@Elior 我已经尝试了使用广播而不是服务的方法,看起来效果还可以。前台服务对我来说不是一个有效的选择,因为我必须显示一个永久通知。现在的问题是:在后台持续更新位置以监视地理围栏会消耗多少电池? :D - Giulio Bider
显示剩余6条评论

-1
您所发的代码是关于在应用程序运行时注册地理围栏+处理地理围栏事件。此外,根据文档,有五个事件需要重新注册您的地理围栏:
  1. 设备重新启动。应用程序应监听设备的启动完成操作,然后重新注册所需的地理围栏。
  2. 卸载并重新安装应用程序。
  3. 清除应用程序数据。
  4. 清除Google Play服务数据。
  5. 应用程序收到GEOFENCE_NOT_AVAILABLE警报。这通常发生在NLP(Android的网络位置提供程序)禁用后。

让我们逐一解决它们:

关于 2&3 ,无需做任何事情,如果您的地理围栏分配给您的应用程序中某种经过身份验证的活动,则实际上根本不需要它们。

关于 4 ,就像2&3一样,我没有尝试深入研究这一点,但我不认为有一种方法可以听取此事件。

1 可以通过注册一个 BroadcastReceiver 很容易地解决:

public class BootBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent startServiceIntent = new Intent(context, AddingGeofencesService.class);
        context.startService(startServiceIntent);
    }
}

请注意,创建一个名为AddingGeofencesService的服务,以便在BootBroadcastReceiver接收到意图后添加地理围栏。类似于以下内容:
public class AddingGeofencesService extends IntentService implements GoogleApiClient.ConnectionCallbacks {

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

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
            //Create geofences from SharedPreferences/network responses
            //Connect to location services
        }
    }

    public void onConnected(Bundle bundle) {
        //Add geofences
    }
    ...
}

还有别忘了清单代码:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<service android:name=".AddingGeofencesService"/>

<receiver android:name=".BootBroadcastReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

5 主要是指位置提供者的更改。这种情况的解决方案也是使用 BroadcastReceiver

public class LocationProviderChangedBroadcastReceiver extends BroadcastReceiver {
    boolean isGpsEnabled;
    boolean isNetworkEnabled;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().matches("android.location.PROVIDERS_CHANGED"))
        {
            LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (isGpsEnabled || isNetworkEnabled) {
                Intent startServiceIntent = new Intent(context, AddingGeofencesService.class);
                context.startService(startServiceIntent);
            }
        }
    }
}

清单:

<receiver
    android:name=".LocationProviderChangedBroadcastReceiver"
    android:exported="false" >
    <intent-filter>
        <action android:name="android.location.PROVIDERS_CHANGED" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

编辑:

我在这里提供了我用来管理地理围栏的代码。 它是为了补充上面的答案而提供的。

我排除了不相关于答案的LocationServicesManager子类。

/*
 * This class does not handle permission checks/missing permissions. The context that's containing
 * this class is responsible of that.
 */
public class LocationServicesManager implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = "YOURTAG";

    private GoogleApiClient mGoogleApiClient;
    private Context context;

    public GeofencesManager geofencesManager;

    private OnGoogleServicesConnectedListener onGoogleServicesConnectedListener;

    public LocationServicesManager(Context context,
                                   OnGoogleServicesConnectedListener onGoogleServicesConnectedListener) {
        this.context = context;
        this.onGoogleServicesConnectedListener = onGoogleServicesConnectedListener;
        buildGoogleApiClient(context);
    }

    public void GeofencesManager() {
        geofencesManager = new GeofencesManager();
    }

    //region Definition, handling connection
    private synchronized void buildGoogleApiClient(Context context) {
        mGoogleApiClient = new GoogleApiClient.Builder(context)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    public void connect() {
        mGoogleApiClient.connect();
    }

    public void disconnect() {
        if (mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    public boolean isConnected() {
        return mGoogleApiClient.isConnected();
    }

    @SuppressWarnings({"MissingPermission"})
    @Override
    public void onConnected(Bundle connectionHint) {
        onGoogleServicesConnectedListener.onGoogleServicesConnected();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult result) {
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
    }


    @Override
    public void onConnectionSuspended(int cause) {
        // Trying to re-establish the connection.
        Log.i(TAG, "Connection suspended");
        mGoogleApiClient.connect();
    }
    //endregion

    public class GeofencesManager implements ResultCallback<Status> {

        private ArrayList<Geofence> mGeofenceList = new ArrayList<>();

        private PendingIntent mGeofencePendingIntent = null;

        private GeofencesManager() {

        }

        public void addGeofenceToList(String key, long expirationDuration, Location location, int radius) {
            addGeofenceToList(key, expirationDuration, new LatLng(location.getLatitude(), location.getLongitude()), radius);
        }

        public void addGeofenceToList(String key, long expirationDuration, LatLng location, int radius) {
            if (location != null) {
                mGeofenceList.add(new Geofence.Builder()
                        .setRequestId(key)
                        .setCircularRegion(location.latitude, location.longitude, radius)
                        .setExpirationDuration(expirationDuration)
                        .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_DWELL
                                | Geofence.GEOFENCE_TRANSITION_ENTER
                                | Geofence.GEOFENCE_TRANSITION_EXIT)
                        .setLoiteringDelay(1000 * 30)
                        .build());
            }
        }

        /**
         * Runs when the result of calling addGeofences() and removeGeofences() becomes available.
         * Either method can complete successfully or with an error.
         */
        public void onResult(@NonNull Status status) {
            if (status.isSuccess()) {
                Log.i(TAG, "onResult: " + status.toString());
            } else {
                Log.e(TAG, getGeofenceErrorString(status.getStatusCode()));
            }
        }

        /**
         * Gets a PendingIntent to send with the request to add or remove Geofences. Location Services
         * issues the Intent inside this PendingIntent whenever a geofence transition occurs for the
         * current list of geofences.
         *
         * @return A PendingIntent for the IntentService that handles geofence transitions.
         */
        private PendingIntent getGeofencePendingIntent() {
            if (mGeofencePendingIntent != null) {
                return mGeofencePendingIntent;
            }

            Intent intent = new Intent(context, GeofenceTransitionsIntentService.class);
            // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
            return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }

        /**
         * Builds and returns a GeofencingRequest. Specifies the list of geofences to be monitored.
         * Also specifies how the geofence notifications are initially triggered.
         */
        @NonNull
        private GeofencingRequest getGeofencingRequest() {
            GeofencingRequest.Builder builder = new GeofencingRequest.Builder();

            // The INITIAL_TRIGGER_ENTER flag indicates that geofencing service should trigger a
            // GEOFENCE_TRANSITION_ENTER notification when the geofence is added and if the device
            // is already inside that geofence.
            builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);

            // Add the geofences to be monitored by geofencing service.
            // Empty mGeofenceList leads to crash
            builder.addGeofences(mGeofenceList);

            return builder.build();
        }

        public void addGeofences() {
            if (mGeofenceList.size() > 0) {
                try {
                    LocationServices.GeofencingApi.addGeofences(
                            mGoogleApiClient,
                            getGeofencingRequest(),
                            getGeofencePendingIntent()
                    ).setResultCallback(this);
                } catch (SecurityException securityException) {
                    Crashlytics.logException(securityException);
                    Log.e(TAG, "Missing permission ACCESS_FINE_LOCATION", securityException);
                }
            }
        }

        public void removeGeofences() {
            if (mGeofenceList.size() > 0) {
                LocationServices.GeofencingApi.removeGeofences(
                        mGoogleApiClient,
                        getGeofencePendingIntent()
                ).setResultCallback(this); // Result processed in onResult().
            }
        }
    }

    public static String getGeofenceErrorString(int errorCode) {
        switch (errorCode) {
            case GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE:
                return "Geofence service is not available now";
            case GeofenceStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES:
                return "Your app has registered too many geofences";
            case GeofenceStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS:
                return "You have provided too many PendingIntents to the addGeofences() call";
            default:
                return "Unknown error: the Geofence service is not available now";
        }
    }
}

上述接口:
public interface OnGoogleServicesConnectedListener {
    void onGoogleServicesConnected();
}

GeofenceTransitionsIntentService

/**
 * Listener for geofence transition changes.
 *
 * Receives geofence transition events from Location Services in the form of an Intent containing
 * the transition type and geofence id(s) that triggered the transition. 
 */
public class GeofenceTransitionsIntentService extends IntentService {

    private static final String TAG = "YOURTAG";

    public GeofenceTransitionsIntentService() {
        super(TAG);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    /**
     * Handles incoming intents.
     * @param intent sent by Location Services. This Intent is provided to Location
     *               Services (inside a PendingIntent) when addGeofences() is called.
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        //Do stuff with the geofencing events
    }
}

在清单文件中:

<service android:name=".GeofenceTransitionsIntentService"/>

最后,总结一下AddingGeofencesService
public class AddingGeofencesService extends IntentService implements OnGoogleServicesConnectedListener {

    private static final String TAG = "YOURTAG";

    LocationServicesManager locationServicesManager;

    public AddingGeofencesService() {
        super(TAG);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
            locationServicesManager = new LocationServicesManager(this, this);
            locationServicesManager.GeofencesManager();

            //Fetch your geofences from somewhere
            List<YourGeofenceObject> yourGeofences = ...

            for (YourGeofenceObject geo : yourGeofences) {
                locationServicesManager.geofencesManager.addGeofenceToList(geo.getKey(),
                        geo.getExpirationDuration(), geo.getLocation(), geo.getRadius());
            }

            locationServicesManager.connect();
        }
    }

    @Override
    public void onGoogleServicesConnected() {
        locationServicesManager.geofencesManager.addGeofences();
    }
}

请注意,您应该在应用程序运行时以与您在AddingGeofencesService中添加它们的方式添加地理围栏。

@user3820753,这个服务不应该处理地理围栏事件,所以 GeofencingEvent.fromIntent(intent) 不应该出现在这里。相反,您应该通过从某个地方获取它来注册您的地理围栏,使用 mGoogleApiClient.connect() 连接到服务,最后在 onConnected() 中调用 registerAllGeofences() - Neria Nachum
@NeriaNachum 谢谢! - Elior
@Elior 请确保您已完成以下所有操作:1.在应用程序启动时添加地理围栏。2.在由我的答案中提到的BroadcastReceiver触发的IntentService中添加相同的地理围栏。3.对于6.0+设备,请启用“自启动”。服务实现取决于您喜欢管理位置服务的方式,只要在其中调用LocationServices.GeofencingApi.addGeofences即可。 - Neria Nachum
@user3820753,我发布了额外的代码,应该可以帮助你解决问题。这几乎是所有相关的代码。 - Neria Nachum
有什么原因导致了这些负评吗?回答和提供的代码都非常详尽,并且在我的应用程序中按预期工作。 - Neria Nachum
显示剩余9条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接