[英]iOS BackgroundFetch equivalent in Android
I would like to know if there is an Android counterpart for iOS BackgroundFetch
feature. 我想知道是否有适用于iOS BackgroundFetch
功能的Android版本。
I would like my Android app using Cordova to wake up every 15 minutes or so and check for updates and perform some other miscellaneous tasks. 我希望我的Android应用程序使用Cordova每15分钟左右醒来并检查更新并执行其他一些其他任务。
In iOS, I was able to do this by using cordova-background-fetch plugin. 在iOS中,我可以使用cordova-background-fetch插件完成此操作。
Since there is no Android version of that plugin, I am happy to write it myself; 由于该插件没有Android版本,我很乐意自己编写; but I would first like to know how I would go about implementing such feature in Android. 但我首先想知道如何在Android中实现这样的功能。 Any suggestions? 有什么建议?
You can use AlarmManager . 您可以使用AlarmManager 。 Besides that you can also use AccountManager . 除此之外,您还可以使用AccountManager 。
In Android you can set AlarmManger
to wakes up every X milliseconds and run a PendingIntent
. 在Android中,您可以将AlarmManger
设置为每X毫秒唤醒并运行PendingIntent
。
This code looks something like this. 这段代码看起来像这样。
AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime()+60000,
PERIOD,
pi);
Android's default IntentService
that runs in the background has some limitations. Android在后台运行的默认IntentService
有一些限制。
You can also take a look at external libary WakefulIntentService
( https://github.com/commonsguy/cwac-wakeful ). 您还可以查看外部WakefulIntentService
( WakefulIntentService
( https://github.com/commonsguy/cwac-wakeful )。 I use that along with AlarmManager
to run background tasks. 我将它与AlarmManager
用于运行后台任务。
Updated : 更新 :
OnAlarmReceiver class OnAlarmReceiver类
public class OnAlarmReceiver extends BroadcastReceiver {
public static String TAG = "OnAlarmReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Waking up alarm");
WakefulIntentService.sendWakefulWork(context, YourService.class); // do work in the service class
}
}
YourService class YourService类
public class YourService extends WakefulIntentService {
public static String TAG = "YourService";
public YourService() {
super("YourService");
}
@Override
protected void doWakefulWork(Intent intent) {
Log.d(TAG, "Waking up service");
// do your background task here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.