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

时间:2014-05-17 07:12:05

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

您好我正在尝试在Android中添加Geo Fence的功能。我使用http://developer.android.com/training/location/geofencing.html来创建和监控Geo Fences。我使用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>

5 个答案:

答案 0 :(得分:15)

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

因此,为了获得Geofencing API的所有响应或准确结果,您必须设置Geofences,然后在一定时间间隔内轮询GPS硬件,甚至不会对收到的结果做任何事情,以便在表面下为操作系统提供有价值的数据。

这可能是您的结果不准确的核心原因。地理围栏出口不会触发,直到操作系统确定您100%在围栏外 - 所以如果位置读数的准确度为500米(使用单元格地理位置时不太可能)并且您的围栏有半径距离你的围栏点至少550米,你必须在50米处才能出现退出事件。

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

答案 1 :(得分:1)

Android的原生地理围栏是令人震惊的不准确和电池密集型。我建议您使用第三方工具,例如Bluedot's Point SDK(精确到10米/ 30英尺)或Gimbal's SDK(精确到50米/ 165英尺),两者都很多电池消耗更少,更可靠。

完全披露:我为Bluedot工作。

答案 2 :(得分:1)

我在sample project on Github called Geofencer中总结了几个关于Android中Geofencing的StackOverflow线程的最佳实践。这可以用作将GeoFencing实现到应用程序中的参考。它还允许动态切换到第三方GeoFencing实施。我希望这对你们中的一些人有所帮助!

答案 3 :(得分:0)

我也遇到了地理围栏系统跳入和跳出地理围栏的问题然后我读了这篇文章(来自官方文档):

  

地理围栏内没有可靠的网络连接。如果   没有可靠的数据连接,可能不会生成警报。   这是因为地理围栏服务取决于网络位置   提供者又需要数据连接。

From the official geofence documentation

答案 4 :(得分:-5)

如果设备未连接到互联网,谷歌播放服务(如地理围栏或活动识别)将无法正常工作。