android - 如何在 Android 中使 Geo Fencing 警报更准确

标签 android google-play-services geofencing android-geofence

您好,我正在尝试在 Android 中添加 Geo Fence 功能。我正在使用 http://developer.android.com/training/location/geofencing.html用于创建和监控地理围栏。我将 IntentService 用于警报(已进入/已退出),但对我来说它不起作用。

但是当我离开并返回区域进行测试时,它对我不起作用。我已打开设备的 GPS,但设备未连接到互联网。

任何人都可以帮助我使它更准确和完美,没有任何问题。

public class MainActivity extends Activity implements GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener,
        LocationClient.OnAddGeofencesResultListener {

    private LocationClient locationClient;

    private String TAG = "MainActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        int resp = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resp == ConnectionResult.SUCCESS) {
            locationClient = new LocationClient(this, this, this);
            locationClient.connect();
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        ArrayList<Store> storeList = getStoreList();
        if (null != storeList && storeList.size() > 0) {
            ArrayList<Geofence> geofenceList = new ArrayList<Geofence>();
            for (Store store : storeList) {
                float radius = (float) store.radius;
                Geofence geofence = new Geofence.Builder()
                        .setRequestId(store.id)
                        .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                        .setCircularRegion(store.latitude, store.longitude, radius)
                        .setExpirationDuration(Geofence.NEVER_EXPIRE)
                        .build();

                geofenceList.add(geofence);
            }

            PendingIntent geoFencePendingIntent = PendingIntent.getService(this, 0,
                    new Intent(this, GeofenceIntentService.class), PendingIntent.FLAG_UPDATE_CURRENT);
            locationClient.addGeofences(geofenceList, geoFencePendingIntent, this);
        }
    }

    @Override
    public void onDisconnected() {
        Log.e(TAG, "Disconnected !");
    }

    @Override
    public void onAddGeofencesResult(int i, String[] strings) {
        if (LocationStatusCodes.SUCCESS == i) {
            //todo check geofence status
        } else {

        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.e(TAG, connectionResult.getErrorCode() + "");
    }

    private ArrayList<Store> getStoreList() {
        ArrayList<Store> storeList = new ArrayList<Store>();
        for (int i = 0; i < 1; i++) {
            Store store = new Store();
            store.id = String.valueOf(i);
            store.address = "India";
            store.latitude = 26.7802187;
            store.longitude = 75.860322;
            store.radius = 100.0;

            storeList.add(store);
        }

        return storeList;
    }

    public class Store {
        String id;
        String address;
        double latitude;
        double longitude;
        double radius;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != locationClient) {
            locationClient.disconnect();
        }
    }
}

GeofenceIntentService.java

public static final String TRANSITION_INTENT_SERVICE = "ReceiveTransitionsIntentService";

public GeofenceIntentService() {
    super(TRANSITION_INTENT_SERVICE);
}

@Override
protected void onHandleIntent(Intent intent) {
    if (LocationClient.hasError(intent)) {
        //todo error process
    } else {
        int transitionType = LocationClient.getGeofenceTransition(intent);
        if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER ||
                transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {
            List<Geofence> triggerList = LocationClient.getTriggeringGeofences(intent);

            for (Geofence geofence : triggerList) {
                generateNotification(geofence.getRequestId(), "address you defined");
            }
        }
    }
}

private void generateNotification(String locationId, String address) {
    long when = System.currentTimeMillis();
    Intent notifyIntent = new Intent(this, MainActivity.class);
    notifyIntent.putExtra("id", locationId);
    notifyIntent.putExtra("address", address);
    notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.dac_logo)
                    .setContentTitle(locationId)
                    .setContentText(address)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true)
                    .setDefaults(Notification.DEFAULT_SOUND)
                    .setWhen(when);    

    NotificationManager notificationManager =   
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify((int) when, builder.build());   
 }
 }

AndroidManifest.xml

  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demo"
android:versionCode="1"    
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />

<application
    android:allowBackup="true"
    android:icon="@drawable/dac_logo"
    android:label="@string/app_name" >
    <activity
        android:name=".MainActivity"
        android:excludeFromRecents="true"
        android:label="@string/app_name"
        android:launchMode="singleTask"
        android:taskAffinity="" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name=".GeofenceIntentService"
        android:exported="false" />

    <receiver android:name="com.location.demo.receivers.BootCompleteReceiver" >    
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />    
        </intent-filter>
    </receiver>

    <meta-data
        android:name="com.google.android.gms.version"    
        android:value="@integer/google_play_services_version" />    
</application>

最佳答案

我发现 GeoFencing 从不智能地从 GPS 硬件检索位置。 GeoFence API 将观察操作系统提供的最准确位置,或者如果没有最近的位置读数可用,它将导致从 Wifi/蜂窝网络计算位置。 (这很糟糕,因为蜂窝网络非常不准确,而且 wifi 经常不可用)

因此,为了从 Geofencing API 中获得完全响应或准确的结果,您必须设置您的地理围栏,然后每隔一段时间轮询 GPS 硬件,甚至不对收到的结果做任何事情,因此在表面之下您是为操作系统提供有值(value)的数据。

这可能是您的结果不准确的核心原因。在操作系统确定您 100% 位于围栏外之前,地理围栏导出不会触发 - 因此,如果位置读数的精度为 500 米(使用小区地理定位时并非不可能)并且您的围栏半径为 50m,则您' d 必须距离您的栅栏点至少 550 米才能产生退出事件。

TLDR;每隔一段时间轮询 GPS 硬件而不对结果做任何事情,您将开始获得更准确的地理围栏。

关于android - 如何在 Android 中使 Geo Fencing 警报更准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23708655/

相关文章:

android - 将 Google Play 服务从 8.4.0 更新到 9.2.1 会破坏一堆涉及 com.google.android.gms.location.places 的代码

android - 错误 : Execution failed for task ': app: processDebugGoogleServices

ios - 如何在Swift 3.0中使用coreLocation框架创建20多个地理围栏

java - java中美国各州的地理定位(纬度/经度)

android - 获取生成的调试 key /证书,用于在不同机器上进行开发

android - 由于 Google 许可政策,应用程序被 Google Play 商店拒绝

Android 主题标签实现

android - 地理围栏和 Lollipop

android - 如何在 Android 中为各种任务编写脚本

android - 如何修复此错误 "A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade"