在地震例子中,这一次的修改你将使用Alarm来替代Timer,定期执行网络更新。
1. 创建一个新的EarthquakeAlarmReceiver类,扩展BroadcastReceiver。
package com.paad.earthquake;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class EarthquakeAlarmReceiver extends BroadcastReceiver {
}
2. 重写onReceive方法来显式启动EarthquakeService。
@Override
public void onReceive(Context context, Intent intent) {
Intent startIntent = new Intent(context, EarthquakeService.class);
context.startService(startIntent);
}
3. 创建一个新的共通的静态字符串来定义用于触发Broadcast Receiver的动作。
public static final String ACTION_REFRESH_EARTHQUAKE_ALARM =
“com.paad.earthquake.ACTION_REFRESH_EARTHQUAKE_ALARM”;
4. 在manifest中添加新的EarthquakeAlarmReceiver,包含一个intent-filter标签来监听第3步中定义的动作。
<receiver android:name=”.EarthquakeAlarmReceiver”>
<intent-filter>
<action
android:name=”com.paad.earthquake.ACTION_REFRESH_EARTHQUAKE_ALARM”
/>
</intent-filter>
</receiver>
5. 在EarthquakeService中,更新onCreate方法来获得AlarmManager的一个引用,并创建一个新的PendingIntent,当Alarm到达时发送Intent。你还可以移除timerTask的初始化代码。
AlarmManager alarms;
PendingIntent alarmIntent;
@Override
public void onCreate() {
int icon = R.drawable.icon;
String tickerText = “New Earthquake Detected”;
long when = System.currentTimeMillis();
newEarthquakeNotification = new Notification(icon, tickerText, when);
alarms = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
String ALARM_ACTION;
ALARM_ACTION = EarthquakeAlarmReceiver.ACTION_REFRESH_EARTHQUAKE_ALARM;
Intent intentToFire = new Intent(ALARM_ACTION);
alarmIntent = PendingIntent.getBroadcast(this, 0, intentToFire, 0);
}
6. 修改onStart方法设置一个Alarm,而不再使用Timer来定期执行下一次更新操作(如果自动更新是enable的)。设置一个新的具有相同动作的Intent来自动取消前一个Alarm。
@Override
public void onStart(Intent intent, int startId)
{
SharedPreferences prefs = getSharedPreferences(Preferences.USER_PREFERENCE, Activity.MODE_PRIVATE);
int minMagIndex = prefs.getInt(Preferences.PREF_MIN_MAG, 0);
if (minMagIndex < 0)
minMagIndex = 0;
int freqIndex = prefs.getInt(Preferences.PREF_UPDATE_FREQ, 0);
if (freqIndex < 0)
freqIndex = 0;
boolean autoUpdate = prefs.getBoolean(Preferences.PREF_AUTO_UPDATE, false);
Resources r = getResources();
int[] minMagValues = r.getIntArray(R.array.magnitude);
int[] freqValues = r.getIntArray(R.array.update_freq_values);
minimumMagnitude = minMagValues[minMagIndex];
int updateFreq = freqValues[freqIndex];
if (autoUpdate)
{
int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
long timeToRefresh = SystemClock.elapsedRealtime() + updateFreq*60*1000;
alarms.set(alarmType, timeToRefresh, alarmIntent);
}
else
alarms.cancel(alarmIntent);
refreshEarthquakes();
};
7. 你可以移除updateTimer实例变量和TimerTask实例。