2012-11-09 38 views

回答

1

使用警報管理器將其設置爲每15分鐘發送一次廣播以喚醒您的intentservice實例並從那裏執行更新。

編輯:

我說這樣做是爲了您的方便的啓動完成的方式,您可能希望在打開你的app啓動報警的事。無論哪種方式只需遵循警報管理器和意向服務的代碼。

首先創建一個用於啓動完成

import android.app.AlarmManager; 
import android.app.PendingIntent; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 

import com.example.CheckUpdateIntentService; 

public class BootCompleteReceiver extends BroadcastReceiver 
{ 
    @Override 
    public void onReceive(Context context, Intent intent) 
    { 
     //Create pending intent to trigger when alarm goes off 
     Intent i = new Intent(context, CheckUpdateIntentService.class); 
     PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT); 

     //Set an alarm to trigger the pending intent in intervals of 15 minutes 
     AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); 
     //Trigger the alarm starting 1 second from now 
     long triggerAtMillis = Calendar.getInstance().getTimeInMillis() + 1000; 
     am.setInexactRepeating(AlarmManager.RTC_WAKEUP, triggerAtMillis, AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent); 
    } 
} 

聽現在的意圖服務做實際的更新

import android.content.Context; 
import android.content.Intent; 
import android.app.IntentService; 

public class CheckUpdateIntentService extends IntentService { 

    public CheckUpdateIntentService() 
    { 
     super(CheckUpdateIntentService.class.getName()); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) 
    { 
     //Actual update logic goes here 
     //Intent service itself is already a also a Context so you can get the context from this class itself 
     Context context = CheckUpdateIntentService.this; 
     //After updates are done the intent service will shutdown itself and wait for the next interval to run again 
    } 
} 

在AndroidManifest.xml中添加以下項目的廣播接收器:

接收啓動完成廣播的權限

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 

然後在應用程序代碼添加您與相應的意圖過濾您有興趣創建BootCompleteReceiver,當然還有intentservice組件

<receiver android:name=".BootCompleteReceiver" > 
    <intent-filter> 
     <action android:name="android.intent.action.BOOT_COMPLETED" /> 
    </intent-filter> 
</receiver> 
<service android:name=".CheckUpdateIntentService" ></service> 

這是一個非常框架實現,你可以試一下首先,如果您需要更多幫助,請告訴我們。

+0

我可以得到一些教程或任何源代碼如何設置每15分鐘的報警管理器,並將其發送到接收器和更新服務器的數據? – user1810931

+0

好吧..當我在筆記本電腦上時,會回到你 – Rejinderi

+0

是的,謝謝! – user1810931

相關問題