2015-06-27 48 views
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等接收的位置,請引導我走向正確的路徑。

回答

1

由於沒有用戶界面,請將您的Asynctask置於Service中,然後將您的數據存儲在SQLite中,以便在打開應用程序>>時,您只需從數據庫中獲取它。

下面是一個例子流量

  • 報警經理會告訴服務來執行的AsyncTask
  • 的AsyncTask將會從服務器或信息的API
  • 所收集的信息/數據應該存儲在SQL
  • 當打開應用程序,先詢問了數據的數據庫和更新用戶界面。
  • 做你的常用應用程序
+0

能否共享偏好的目的服務訪問?我想我將不得不做出很多改變。我正在考慮或切換到內容提供商。這是更好的方法嗎?因爲在上述流程中,如果數據庫有一些數據,應用程序甚至會後手動(非意圖的服務,的AsyncTask)刷新 – GauravPandey

+0

我不是,如果你真的能接入優選的是完全肯定,但我認爲是顯示過時的數據,如果打算使用SQL,一定要在打開應用程序時清除它們,以便刪除舊數據,並且可以在SQL中添加Date以比較數據是否舊。我希望這清楚的事情:) – neferpitou