地理围栏没有触发(待处理用户和广播接收者)

时间:2014-09-09 19:32:12

标签: android geolocation android-pendingintent android-geofence

我使用了Geofences的Android教程,显然,当应用关闭时,它不起作用。因此,在搜索之后,我注意到SO上的用户b-ryce使用了BroadcastReceiver,因此即使应用程序未处于活动状态(link for his SO question)也会触发地理围栏。

当我移动到外部/内部注册位置时,我无法强制地理围栏触发。这是我的程序:

    /**
     * GeoLocation library
     */
    mGeoLocation = new GeoLocation(sInstance);


    /**
     * mReceiver init
     */
    mReceiver = new Receiver();
    sInstance.registerReceiver(mReceiver, mReceiver.createIntentFilter());

在GeoLocation类中:

/*
 * Create a PendingIntent that triggers an IntentService in your
 * app when a geofence transition occurs.
 */
protected PendingIntent getTransitionPendingIntent() {
    if (mGeoPendingIntent != null) {
        return mGeoPendingIntent;
    }

    else {

        // Create an explicit Intent
        //  Intent intent = new Intent(mContext,
        //          ReceiveTransitionsIntentService.class);

        Intent intent = new Intent(getClass().getPackage().getName() + ".GEOFENCE_RECEIVE");

        /**
         * Return the PendingIntent
         */
        return PendingIntent.getBroadcast(
                mContext,
                0,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

    }
}

以下是我创建新地理围栏的方法:

                        Geofence fence = new Geofence.Builder()
                                .setRequestId(hashCode)
                                        // when entering this geofence
                                .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
                                .setCircularRegion(
                                        Double.parseDouble(single.getSetting("latitude")),
                                        Double.parseDouble(single.getSetting("longitude")),
                                        Float.parseFloat(single.getSetting("radius")) // radius in meters
                                )
                                .setExpirationDuration(Geofence.NEVER_EXPIRE)
                                .build();

                        mGeofences.add(fence);

数组被填充,我们在Geofence类

中调用AddGeofences方法
mGeoLocation.AddGeofences(mGeofences);

接收类的AndroidManifest.xml:

    <!-- RECEIVER -->
    <receiver android:name=".Receiver" >
    </receiver>

接收器类应该只在地理围栏触发时记录

public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    Log.d("sfen", "Broadcast recieved "+ action +" but not needed.");
}

问题是,只有当我在我的应用程序中打开地图并选择位置时,Geofence才会触发。关闭应用程序(在后台运行它)不会触发任何操作,地理围栏转换不会触发任何内容。

有人能告诉我我做错了什么吗?

1 个答案:

答案 0 :(得分:1)

你应该使用IntentService接收地理围栏事件(不是接收者)。我在https://github.com/chenjishi/android_location_demo写了一个演示。

1.首先定义LocationClient

    private LocationClient locationClient;

2.init it

@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();
    }
}

3.连接成功时,注册地理围栏

@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);
    }
}

4.最终定义IntentService以接收地理围栏事件

public class GeofenceIntentService extends IntentService {
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 | Intent.FLAG_ACTIVITY_CLEAR_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());
}

}