我需要以编程方式使用GPS获取当前位置.我怎样才能实现它?
我有一个以Google的地理围栏示例代码开头的应用.它可以工作几天,我得到了所有过渡意图,正如我预期的那样.然而,经过一段时间,比如3天,应用程序停止了这些意图,我不知道为什么.
当我创建我的围栏时,我将到期时间设置为Geofence.NEVER_EXPIRE
这是我的IntentService,我在它停止工作之前获得转换意图:
public class ReceiveTransitionsIntentService extends IntentService {
@Override
protected void onHandleIntent(Intent intent) {
Intent broadcastIntent = new Intent();
broadcastIntent.addCategory(GeofenceUtils.CATEGORY_LOCATION_SERVICES);
// First check for errors
if (LocationClient.hasError(intent)) {
...handle errors
} else {
// Get the type of transition (entry or exit)
int transition = LocationClient.getGeofenceTransition(intent);
// Test that a valid transition was reported
if ((transition == Geofence.GEOFENCE_TRANSITION_ENTER)
|| (transition == Geofence.GEOFENCE_TRANSITION_EXIT)) {
// Post a notification
NEVER GETS HERE
} else {
...log error
}
}
}
} …Run Code Online (Sandbox Code Playgroud) 我正在编写一个应用程序,当有人在正在安装的应用程序的生命周期内进入/退出多个站点时,需要使用地理围栏.
我的地理围栏实现(非常类似于下面的第二个链接)在我第一次安装应用程序时工作正常,无论是在移入/移出地理围栏时还是在使用模拟位置进行模拟时,都会重新启动设备.
在重新启动时,模拟位置或实际上物理移入和移出地理围栏似乎都会触发事件并将未决意图发送到我的广播接收器.
我已经查看了以下三个链接,并且还阅读了相当多的文档,但我无法找到一个明确的答案,直接说注册地理围栏持续存在或重启后不会持续存在.
这些是我在堆栈溢出时查看的链接: Android地理围栏是否能够在重启时幸存?
Android Geofences是否在删除/过期之前保持活动状态,或者直到我的PendingIntent启动为止
如果有人碰巧知道他们是否坚持重新启动后的答案,或者如果他们没有解决问题,那将非常感谢!我目前的最后一个希望是为BOOT_COMPLETED创建一个监听器,并在启动时重新注册它们,但id更喜欢只在必要时才这样做.
非常感谢提前!
编辑:虽然我没有找到明确的(书面)答案,但我很确定TonyC先生发布的内容是正确的,并选择了解决方案.非常感谢TonyC!
如果有人想看到我的解决方案,我会在设备启动时监听启动完成操作,然后重新注册我需要的所有地理围栏.
这是显而易见的:
<!-- Listen for the device starting up -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name="com.YOUR.PACKAGE.geofence.BootCompleteReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)
然后为它创建一个广播接收器,它将在启动时重新注册地理围栏:
package com.YOUR.PACKAGE.geofence;
import android.app.PendingIntent.CanceledException;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.Geofence;
public class BootCompleteReceiver extends WakefulBroadcastReceiver
{
private static final String TAG = "BootCompleteReceiver";
@Override
public void onReceive(Context context, Intent intent)
{
//Do what you want/Register Geofences
}
}
Run Code Online (Sandbox Code Playgroud)
同样值得注意的是,如果您在启动时处于地理围栏内,那么一旦注册了地理围栏,这通常会触发地理围栏的未决意图.
因此,例如,如果地理围栏启动应用程序,那么当您启动恰好位于地理围栏中的设备时,一旦启动完整广播接收器已注册地理围栏,它也将打开应用程序,并且位置服务已经解决了您的位置是.
希望对某人有所帮助.
android geofencing google-play-services android-geofence location-client