设备重启后如何注册地理围栏?

How to register Geofence after device restarted?

我构建了一个在我设置的位置弹出通知的应用程序。 一切顺利。即使在我重新启动我的设备之后。没有问题。但我注意到,如果我关闭 GPS 然后重新启动我的设备,BroadcastReceiver 可能会尝试登录 Geofence api 并出现错误,因为没有 GPS。并且地理围栏通知不再弹出,直到我在 gps 模式下重新启动我的设备。 我必须使用 AlarmManager 吗?每 x 次推送一些刷新?验证 GPS 模式是否打开?

此解决方案假设您已经存储了要使用的地理围栏信息,其方式将在设备重启后持续存在。

第一次启动时,在处理 RECEIVE_BOOT_COMPLETED 的 BroadcastReceiver 中检查是否有 GPS is enabled。如果是,请正常继续,但如果不是,请将此添加到您的接收器:

@Override
public void onReceive(Context context, Intent intent) {

    //Or whatever action your receiver accepts
    if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
        LocationManager locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
        if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER){
            context.registerReceiver(this, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));
        }
        else{
            //We are good, continue with adding geofences!
        }
    }

    if(intent.getAction().equals(LocationManager.PROVIDERS_CHANGED_ACTION)){
        if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER){
            context.unregisterReceiver(this);
            //We got our GPS stuff up, add our geofences!
        }
    }
}

您可以将其添加到清单中。此示例假设您有一个 BroadcastReceiver com.example.MyBroadcastReceiver,将其替换为您自己的。每当 GPS 打开或关闭时,此接收器都会收到广播意图。

<receiver android:name="com.example.MyBroadcastReceiver">
    <intent-filter>
        <action android:name="android.location.PROVIDERS_CHANGED" />
    </intent-filter>
</receiver>