我建立了一个应用程序,可以在我设定的位置弹出通知。一切都运行顺利,即使在我重新启动设备后也没有问题。但是我注意到,如果我关闭GPS,然后重新启动设备,广播接收器可能会尝试登录Geofence API,并因为没有GPS而出现错误。直到我以GPS开启模式重新启动设备,Geofence通知才会再次弹出。我需要使用AlarmManager吗?每隔x时间推送一些刷新来验证GPS模式是否开启?
假设您已经以一种持久化的方式存储了要使用的地理围栏信息,此解决方案将在此基础上展开。
首先,在处理RECEIVE_BOOT_COMPLETED
的广播接收器中,检查GPS 是否已启用。如果已启用,则继续正常操作,否则请将以下内容添加到接收器中:
@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!
}
}
}
<receiver android:name="com.example.MyBroadcastReceiver">
<intent-filter>
<action android:name="android.location.PROVIDERS_CHANGED" />
</intent-filter>
</receiver>