タイム スケジューリングを使用して、サーバーからのデータを 15 分ごとに更新したいと考えています。データの背景を更新する方法はありますか?
1066 次
1 に答える
1
アラーム マネージャーを使用してブロードキャストを送信し、intentservice インスタンスを 15 分ごとに起動し、そこから更新を行います。
編集:
便宜上、起動完了の方法を追加しました。アプリを開いたときにアラームを開始することをお勧めします。どちらの方法でも、アラーム マネージャーとインテント サービスがあるコードに従ってください。
まず、ブート完了をリッスンするブロードキャスト レシーバーを作成します。
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 と、関心のある対応するインテント フィルター、およびもちろんインテント サービス コンポーネントを追加します。
<receiver android:name=".BootCompleteReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".CheckUpdateIntentService" ></service>
これは非常に骨格的な実装です。さらにサポートが必要な場合は、まず試してみてください。
于 2012-11-09T01:09:37.780 に答える