在Android 8及更高版本上,背景地理围栏的确是有效的。背景地理围栏可以在应用程序未运行或在后台运行时触发特定的操作或提供相关的信息。
下面是一个示例代码,演示如何在Android 8+上使用背景地理围栏:
public class GeofenceBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
Log.e(TAG, "GeofencingEvent error: " + geofencingEvent.getErrorCode());
return;
}
// 处理地理围栏的触发事件
int transition = geofencingEvent.getGeofenceTransition();
if (transition == Geofence.GEOFENCE_TRANSITION_ENTER) {
// 进入地理围栏
Log.d(TAG, "Entered geofence");
// 执行你的操作
} else if (transition == Geofence.GEOFENCE_TRANSITION_EXIT) {
// 离开地理围栏
Log.d(TAG, "Exited geofence");
// 执行你的操作
}
}
}
public class MainActivity extends AppCompatActivity {
private GeofenceBroadcastReceiver geofenceReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
geofenceReceiver = new GeofenceBroadcastReceiver();
// 注册广播接收器
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("your_package_name.ACTION_GEOFENCE");
registerReceiver(geofenceReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
// 取消注册广播接收器
unregisterReceiver(geofenceReceiver);
}
}
private void addGeofence() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
// 创建地理围栏
Geofence geofence = new Geofence.Builder()
.setRequestId("your_geofence_id")
.setCircularRegion(latitude, longitude, radius)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build();
// 添加地理围栏到请求中
builder.addGeofence(geofence);
// 构建地理围栏请求
GeofencingRequest geofencingRequest = builder.build();
// 创建PendingIntent,用于触发地理围栏的广播
Intent intent = new Intent("your_package_name.ACTION_GEOFENCE");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 请求地理围栏
LocationServices.getGeofencingClient(this)
.addGeofences(geofencingRequest, pendingIntent)
.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "Geofence added successfully");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, "Failed to add geofence: " + e.getMessage());
}
});
}
请确保将代码中的your_package_name
替换为你的应用程序的包名。
通过以上步骤,你可以在Android 8+上实现背景地理围栏,并在进入或离开地理围栏时执行相应的操作。