gpt4 book ai didi

android - 屏幕关闭后无法接收 LocationClient 的位置更新

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:05:35 25 4
gpt4 key购买 nike

我正在尝试编写一个在后台运行并从 LocationClient (Google Map API Android V2) 接收位置更新的简单 Android 服务。问题是当屏幕关闭时,我的服务不再接收位置更新。我试图检查该服务是否处于 Activity 状态,即使屏幕关闭也是如此(我有一个 TimerTask 计划日志)。当屏幕打开时,我可以接收位置更新,但当屏幕关闭时,我只能看到 TimerTask 的日志,我不会收到任何位置更新。唤醒屏幕再次打开位置更新。如何解决?

这是我的简单服务:

public class LocationService extends Service implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, LocationListener{

private static final String TAG = LocationService.class.getSimpleName();

private LocationClient mLocationClient;

private Timer timer;
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(5*1000) // 5 seconds
.setFastestInterval(3*1000) // 3 seconds
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);


@Override
public void onCreate() {
Log.d(TAG, "Creating..");
mLocationClient = new LocationClient(this, this, this);
timer = new Timer();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Starting..");
if(!mLocationClient.isConnected() || !mLocationClient.isConnecting()) {
Log.d(TAG, "Connecting location client..");
mLocationClient.connect();
}
timer.scheduleAtFixedRate(new TimerTask(){
@Override
public void run() {
Log.d(TAG, "TimerTask executing");
}}, 0, 3*1000);
return START_STICKY;
}

@Override
public void onConnectionFailed(ConnectionResult result) {
Log.d(TAG, "Connection failed..");
stopSelf();
}

@Override
public void onConnected(Bundle bundle) {
System.out.println("Connected ...");
mLocationClient.requestLocationUpdates(REQUEST, this);
}

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

@Override
public IBinder onBind(Intent arg0) {
throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Received location update");
}

@Override
public void onDestroy() {
Log.d(TAG, "Destroying..");
timer.cancel();
mLocationClient.removeLocationUpdates(this);
}
}

最佳答案

使用WakeLock

在onStartCommand

wl = ((PowerManager)getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, yourTAG);
wl.acquire();

在onDestroy中

if (wl != null && wl.isHeld()) {
wl.release();
}

关于android - 屏幕关闭后无法接收 LocationClient 的位置更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17703902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com