我正在使用位置管理器类接收位置更新我的要求是这样我必须听取连续的位置更新,但我面临的问题一旦断开我不知道如何重新建立GPS连接,此外在一些设备一旦设备睡眠我无法接收任何位置更新请提供任何解决方案来实现这一点任何帮助表示赞赏..
public void setup(MainActivity activity) {
if (!setup) {
this.activity = activity;
Intent locationIntent = new Intent(this.activity, LocationIntentService.class);
mLocationPendingIntent = PendingIntent.getService(this.activity, 0, locationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent detectedIntent = new Intent(this.activity, ActivityDetectionIntentService.class);
mDetectedActivityPendingIntent = PendingIntent.getService(this.activity, 0, detectedIntent, PendingIntent.FLAG_UPDATE_CURRENT);
googleApiClient = new GoogleApiClient.Builder(activity)
.addConnectionCallbacks(activity)
.addOnConnectionFailedListener(activity)
.addApi(ActivityRecognition.API)
.build();
setup = true;
}
}
**LocationIntentService.java**
public class LocationIntentService extends IntentService {
public LocationIntentService() {
super("LocationServices");
}
public LocationIntentService(String name) {
super("LocationServices");
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
Location location = intent.getParcelableExtra(LocationManager.KEY_LOCATION_CHANGED);
if (location != null) {
Intent localIntent = new Intent(HWUtil.LOCAL_RECEIVER);
localIntent.addCategory(Intent.CATEGORY_DEFAULT);
localIntent.putExtra(HWUtil.LOCATION, location);
localIntent.putExtra(HWUtil.FROM, HWUtil.LOCATION_SERVICE);
sendBroadcast(localIntent);
}
}
}
}
我将此位置更新发送给Broadcastrecciver
答案 0 :(得分:3)
请注意,在移动设备上持续使用纯GPS作为位置提供商非常耗能。说完之后,我会按如下方式执行你的任务:
startForeground()
功能,以便您的服务几乎不会中断运行,并包括可以链接到您的活动的statusBar通知。)希望它对你有帮助
答案 1 :(得分:0)
AFAIK,wake lock是最简单的方法。 PowerManager.WakeLock
唤醒锁定是一种机制,用于指示您的应用程序需要让设备继续运行。
任何使用WakeLock的应用程序都必须在应用程序清单的元素中请求android.permission.WAKE_LOCK权限。通过致电newWakeLock(int, String)
获取唤醒锁。
调用acquire()获取唤醒锁定并强制设备保持在创建唤醒锁定时请求的级别。
你应该获得一个唤醒锁:
//in onCreate of your service
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
cpuWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"gps_service");
cpuWakeLock.acquire();
// Release in onDestroy of your service
if (cpuWakeLock.isHeld())
cpuWakeLock.release();
and add this to your manifest:
https://developer.android.com/reference/android/Manifest.permission.html 如果您需要连续的位置更新,则上述情况很好。