我的意圖是在應用第一次運行時創建下載服務,並每24小時檢查一次更新。我原本一切都運行着我的主要活動,但似乎要在一個線程和一個類上運行一切。所以這是我的嘗試,將其轉移到另一個班級並投入使用。它假設在24小時內運行並檢查更新,如果在4小時內沒有互聯網再次嘗試。我特別想涉及任何遞歸問題,有兩個或三個相同的服務檢查更新,每24小時只有一個。但是將我的代碼整合到服務中有問題,我做錯了什麼?Android IntentService更新循環
public class DownloadService extends IntentService {
// TODO 0 - Define your Download Service as Android component in
// AndroidManifest.xml
private int result = Activity.RESULT_CANCELED;
public DownloadService() {
super("DownloadService");
}
// Will be called asynchronously be Android
@Override
protected void onHandleIntent(Intent intent) {
private final Runnable mUpdateUi = new Runnable(){
public void run(){
check();
}
};
private void start(){
new Thread(
new Runnable(){
public void run(){
Log.d(TAG, "inside start");
Looper.prepare();
mHandler = new Handler();
check();
Looper.loop();
}
}
).run();
}
private void check(){
if (isNetworkAvailable()== true){
try {
new checkupdate().execute();
delayTime = 86400000;
Toast.makeText(DownloadService.this, "Daily update check!", Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
e.printStackTrace();
delayTime = 21600000;
}
}else{
delayTime = 21600000;
Toast.makeText(DownloadService.this, "No internet for Daily update check, try again in little!", Toast.LENGTH_SHORT).show();
}
reCheck();
}
private void reCheck(){
mHandler.postDelayed(mUpdateUi, delayTime);
}
}
這非常有趣,並感謝您的迴應!我目前正在將我的下載內容發送到下載管理器,那麼您還會使用意向服務的兄弟嗎?我無法廢除意圖服務的想法,只需使用警報管理器在24小時內觸發檢查更新,然後像往常一樣將下載文件發送到下載管理器? – MAXGEN
如果你使用'android.app。DownloadManager'然後不,你不需要使用IntentService。關於使用自己的IntentService的唯一原因是在調用DownloadManager之前立即執行一些其他任務 - 因爲IntentService實現了一個工作隊列,所以它可以是鏈接任務的便捷方式。根據你所描述的內容,雖然在這種情況下我沒有看到任何需要。 DownloadManager已經以更健壯和靈活的方式做了你自定義的IntentService需要做的事情。 –
「...除了通常的onHandleIntent之外,您還需要實現onStartCommand ...」 - 謝謝。我一直在努力更新我的'IntentService'行動。 –