嘗試在我的服務中獲取LocationUpdates,但它似乎並未觸發LocationListener。Android服務未收到位置更新
我的服務啓動一個線程,然後循環一個Handler.postDelayed() - 我最初使用睡眠(30000),但我認爲這可能已經阻止了locationUpdates。所有的服務不會是推出這個話題 - 和onStartCommand返回粘保持運行:
public class TST extends Thread {
final int DefaultNetworkTick = 120000; // 2 minutes
final int DefaultLocationTick = 20000; //600000;
boolean CustomLocationUpdateTick = false; // If the network requests faster updates
int CustomLocationUpdateTickMs = 600000; // Default 10 minutes
public boolean kill = false;
public Context context;
Handler handler = new Handler();
Date nextNetworkReadTick;
@Override
public void run() {
Log.i("TST", "Start run() iteration");
// Set the ticks to the appropriate values
// Network gets read every 2 minutes
nextNetworkReadTick = new Date();
nextNetworkReadTick.setTime(nextNetworkReadTick.getTime() + DefaultNetworkTick);
Log.i("TST", "Set next Network tick to " + nextNetworkReadTick.toString());
Looper.prepare();
Log.i("TST", "Performing location update setup...");
SetupLocationListenerDefault();
handler.postDelayed(runFunc, 2000);
Looper.loop();
}
// We do our networking and stuff in here
public Runnable runFunc = new Runnable(){
public void run()
{
Log.i("TST", "run() iteration");
if(new Date().after(nextNetworkReadTick)) {
// Set next tick
nextNetworkReadTick = new Date();
nextNetworkReadTick.setTime(nextNetworkReadTick.getTime() + DefaultNetworkTick);
UpdateNetwork();
}
handler.postDelayed(runFunc, 1000);
}
};
private void UpdateNetwork() {
// TODO Auto-generated method stub
}
LocationManager locMgr;
PendingIntent locationUpdateIntentPending;
Intent locationUpdateIntent;
LocationListener locationListener = new LocationListener()
{
@Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
Log.i("TST", "OnLocationChanged: " + arg0.toString());
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Log.i("TST", "OnProviderDisabled: " + provider);
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.i("TST", "OnProviderEnabled: " + provider);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Log.i("TST", "OnStatusChanged");
}
};
private void SetupLocationListenerDefault() {
// Reset location manager
if(locMgr != null) {
locMgr.removeUpdates(locationListener);
locMgr = null;
}
locMgr = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locMgr.getBestProvider(criteria, true);
locMgr.requestLocationUpdates(provider, DefaultLocationTick, 0, locationListener);
}
}
我知道這聽起來很明顯,但你確定你可以得到位置提升嗎?我已經看過使用返回網絡而不是gps的標準,如果你在裏面,那麼你可能實際上並不依賴於信號。你有沒有在服務之外嘗試過這段代碼,看看是否有這個問題,也許把它放在程序的一個快速存根中,只是爲了驗證服務是否存在問題? – Idistic