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

3
我建立了一个应用程序,可以在我设定的位置弹出通知。一切都运行顺利,即使在我重新启动设备后也没有问题。但是我注意到,如果我关闭GPS,然后重新启动设备,广播接收器可能会尝试登录Geofence API,并因为没有GPS而出现错误。直到我以GPS开启模式重新启动设备,Geofence通知才会再次弹出。我需要使用AlarmManager吗?每隔x时间推送一些刷新来验证GPS模式是否开启?
2个回答

6

假设您已经以一种持久化的方式存储了要使用的地理围栏信息,此解决方案将在此基础上展开。

首先,在处理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!
        }
    }
}

它运行了!非常感谢你。 - Anna
我必须使用这个吗:"context.registerReceiver(this, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION)); 或者是 mContext.unregisterReceiver(this)? - Anna
你只需要使用“context”变量注销即可。 - Pablo Baxter

2
您可以将以下内容添加到您的清单文件中。假设您拥有一个名为com.example.MyBroadcastReceiver的广播接收器,请更换为您自己的接收器。这个接收器将在GPS打开或关闭时接收广播意图。
<receiver android:name="com.example.MyBroadcastReceiver">
    <intent-filter>
        <action android:name="android.location.PROVIDERS_CHANGED" />
    </intent-filter>
</receiver>

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