如果您将 PhoneStateListener 作为服务的一部分,那么您的应用程序组件就会始终知道当前的信号强度。然后,应用程序的 UI 部分可以按需查询服务的状态,或者在强度变化超过某个限制时发布更新。例如,信号强度变化很快 - 所以只有在变化超过 10% 时才发布更新或按时间限制更新。
例如(这里更新只发送感兴趣的对象被更改(mSms 或 mMins)并且只有每 5 次信号强度更改。应用程序的 Activity 将接收此 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();
}