我在寫一個位置服務,並使用更新間隔向服務器發送位置更新。 但我試圖通過用戶輸入(AlertDialog
)在服務中更新此間隔變量。硬編碼時它工作得很好。位置服務的更新時間間隔Android
我使用此代碼從服務的onCreate()
中的AlertDialog
類中獲取間隔變量。
public void onCreate() {
super.onCreate();
final boolean tr=true;
new Thread(new Runnable() {
public void run() {
while (tr) {
//check your static variable here
updateInterval=ShowCurInterval.loadCurInterval(getApplicationContext());//ShowCur Interval is the Alert Dialog calss
Log.d(" INTERVAL ","Interval "+ updateInterval);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}}
).start();
startLocationListener(updateInterval);
}
而且我還可以在日誌中看到新的updateInterval值(它是從Alert對話框中添加的)。但requestLocationUpdates()
仍使用預定義的updateInterval值。
這裏是startLocationListener()方法:
public void startLocationListener(int updateInterval) {
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locManager.removeUpdates(locListener);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, updateInterval, updateDistance, locListener);
Log.d(getClass().getSimpleName(), "Loclistener started, Updatetime: " + updateInterval);
Toast.makeText(getApplicationContext(), "UPDATE INTERVAL"+updateInterval,Toast.LENGTH_SHORT);
preInterval = updateInterval;
}
沒有人有任何建議,我怎麼可以更新這個變量?
@binW 編輯部分,出現異常:
Handler mhandler = new Handler();
mhandler.postDelayed(new Runnable(){
public void run(){
Looper.prepare();
updateInterval=SingletonManager.getInstance().loadCurInterval(getApplicationContext());
SingletonManager.getInstance().saveCurInterval(getApplicationContext(), updateInterval);
startLocationListener(updateInterval);
Log.d(" INTERVAL ","Interval "+ updateInterval);
//startChecking();
}
}, 2000);
例外:
04-17 03:18:55.250: E/AndroidRuntime(2146): java.lang.RuntimeException: Only one Looper may be created per thread
預先感謝您。
發生了什麼事?它只與以前的更新率有關嗎? – 5hssba 2012-04-16 10:07:49
@raju Hello..Yes它只適用於以前的更新率。 updateInterval是一個值爲10000(毫秒)的全局變量。 – crtn 2012-04-16 10:56:32