如果你犯了一個服務的PhoneStateListener部分,那麼你有你的應用程序的一個組件,它總是知道當前的信號強度。然後,應用的用戶界面部分可以根據需要查詢服務的狀態,或者在強度變化超出某個限制時發佈更新。例如,信號強度變化很快 - 所以只有在更新超過10%或更新時間限制時才發佈更新。例如(這裏更新只發送感興趣的對象被改變(mSms或mMins),並且只有每第5個信號強度發生改變,應用程序的活動會吸收這個Intent,這由服務的PhoneStateListener重寫方法調用。
/* called from the phone state listener to check for any changes in the number of sms/calls since last time
* and to raise a suitable intent if required. Check the time to avoid calling too fast.
*/
private void update()
{
final String key = getString(R.string.pref_periodstart_key);
final String defVal = getString(R.string.periodstart_defaultValue);
Thread thread = new Thread(null, new Runnable() {
public void run() {
Context context = getApplicationContext();
int start = Integer.valueOf(mPrefs.getString(key, defVal));
Date date = PhoneUsageInfo.getLastContractDate(start);
int mins = PhoneUsageInfo.getMinutesUsedSince(context, date);
int sms = PhoneUsageInfo.getSMSCountSince(context, date);
boolean changed = (mins != mMins || sms != mSms);
if (changed || mCount % 5 == 0) {
mMins = mins;
mSms = sms;
Intent intent = new Intent(Constants.INTENT_USAGE_UPDATE);
intent.putExtra(Constants.EXTRA_SMS_COUNT, sms);
intent.putExtra(Constants.EXTRA_MIN_COUNT, mins);
intent.putExtra(Constants.EXTRA_START_DATE, date);
Log.d(TAG, String.format("service sending broadcast intent sms %d, mins %d (%s)", sms, mins, changed?"changed":"unchanged"));
sendBroadcast(intent);
}
mCount += 1;
}
}, "PhoneUsageServiceUpdate");
thread.start();
}
嗨,我想刷新signalStrength只有當我真正需要這些信息,就像如果一個新的連接。到目前爲止,我只知道onSignalStrengthsChanged(SignalStrength signalStrength)來讀取這些信息。我沒有想法如何直接訪問SignalStrength。 – Wolfen 2012-08-05 19:42:11