1
我已經完成構建一個Android天氣應用。它使用AsyncTask從API獲取天氣,並通過調用適配器上的notifyDataSetChanged()更新onPostExecute()中的UI。的AsyncTask意圖服務(W AlarmManager)
現在我也想創建一個後臺服務/任務等我知道AlarmManager的。我想知道,應該與AlarmManager結合使用以觸發AsyncTask。我對這個問題的關注和理由是我的AsyncTask也在更新UI。但是,如果任何後臺服務調用AsyncTask,則前臺沒有UI,因爲當前應用程序未運行。它會導致崩潰嗎?
UPDATE 在我的主要活動我把這種方法來啓動我的鬧鐘經理
public void scheduleAlarm() {
// Construct an intent that will execute the AlarmReceiver
Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(this, AlarmReceiver.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every 5 seconds
long firstMillis = System.currentTimeMillis(); // first run of alarm is immediate
int intervalMillis = 10000; // 5 seconds
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis, intervalMillis, pIntent);
}
報警管理器實現:
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, WeatherIntentService.class);
i.putExtra("foo", "bar");
context.startService(i);
}
意向服務實現
@Override
protected void onHandleIntent(Intent intent) {
// Do the task here
Log.i("MyTestService", "Service running");
}
我很困惑如何啓動異步任務。由於我的異步任務取決於共享首選項以及從gms等接收的位置,請引導我走向正確的路徑。
能否共享偏好的目的服務訪問?我想我將不得不做出很多改變。我正在考慮或切換到內容提供商。這是更好的方法嗎?因爲在上述流程中,如果數據庫有一些數據,應用程序甚至會後手動(非意圖的服務,的AsyncTask)刷新 – GauravPandey
我不是,如果你真的能接入優選的是完全肯定,但我認爲是顯示過時的數據,如果打算使用SQL,一定要在打開應用程序時清除它們,以便刪除舊數據,並且可以在SQL中添加Date以比較數據是否舊。我希望這清楚的事情:) – neferpitou