0
經過大量有關實施IntentServices和警報的研究,我已經想出了這個。我不知道這段代碼究竟發生了什麼,所以我需要幫助確切知道發生了什麼。Android:警報和意圖服務
public class MainActivity{
//....
public void onNewItemAdded(String[] _entry){
//...
\t Intent intent = new Intent(MainActivity.this, UpdateService.class);
\t startService(intent);
}
//....
}
public class AlarmReceiver extends BroadcastReceiver {
\t @Override
\t public void onReceive(Context context, Intent intent) {
\t \t // TODO Auto-generated method stub
\t \t Intent startIntent = new Intent(context, UpdateService.class);
\t \t context.startService(startIntent);
}
public static final String ACTION_REFRESH_ALARM = "com.a.b.ACTION_REFRESH_ALARM";
}
public class UpdateService extends IntentService{
//...
@Override
\t public void onCreate() {
\t \t super.onCreate();
\t \t alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
\t \t String ALARM_ACTION = AlarmReceiver.ACTION_REFRESH_ALARM;
\t \t Intent intentToFire = new Intent(ALARM_ACTION);
\t \t alarmIntent = PendingIntent.getBroadcast(this, 0, intentToFire, 0);
\t }
\t @Override
\t protected void onHandleIntent(Intent intent) {
\t \t Context context = getApplicationContext();
\t \t SharedPreferences prefs = PreferenceManager
\t \t \t \t .getDefaultSharedPreferences(context);
\t \t int updateFreq = Integer.parseInt(prefs.getString(
\t \t \t \t PreferencesActivity.PREF_UPDATE_FREQ, "60"));
\t \t boolean autoUpdateChecked = prefs.getBoolean(
\t \t \t \t PreferencesActivity.PREF_AUTO_UPDATE, false);
\t \t if (autoUpdateChecked) {
\t \t \t int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
\t \t \t long timeToRefresh = SystemClock.elapsedRealtime() + updateFreq
\t \t \t \t \t * 60 * 1000;
\t \t \t alarmManager.setInexactRepeating(alarmType, timeToRefresh,
\t \t \t \t \t updateFreq * 60 * 1000, alarmIntent);
\t \t }
\t \t else {
\t \t \t alarmManager.cancel(alarmIntent);
\t \t }
\t \t refreshKeywords();
\t }
}
我的目標是讓refreshKeywords()方法被調用的每一分鐘。另外,如果onNewItemAdded()方法被多次調用會發生什麼?
對不起,如果這個問題很蠢,我是一個初學者。
我不沒辦法。在使用此實現時,refreshKeywords()方法在哪裏? 這個函數是用來替代AlarmReceiver類的嗎? – 2014-11-01 21:55:16
是的,你可以使用這個函數爲你的AlarmReceiver – 2014-11-01 21:59:43
好吧,我應該如何修改onHandleIntent()方法?只有在SystemPreferences活動表明它已由用戶啓用時,我才需要將鬧鐘設置爲自動刷新。我已經在onHandleIntent()方法中做了這些。 另外,這個ServiceRunningBackground()方法應該放在哪裏以及應該在哪裏調用? – 2014-11-02 13:24:59