Sun*_*Cho 5 android ios cordova
我想知道是否有适用于iOS BackgroundFetch功能的Android版本.
我希望我的Android应用程序使用Cordova每15分钟左右醒来并检查更新并执行其他一些其他任务.
在iOS中,我可以使用cordova-background-fetch插件完成此操作.
由于该插件没有Android版本,我很乐意自己编写; 但我首先想知道如何在Android中实现这样的功能.有什么建议?
在 Android 中,您可以设置AlarmManger为每 X 毫秒唤醒一次并运行PendingIntent.
这段代码看起来像这样。
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);
Run Code Online (Sandbox Code Playgroud)
Android 默认IntentService 在后台运行有一些限制。
您还可以查看外部库WakefulIntentService(https://github.com/commonsguy/cwac-wakeful)。我用它来AlarmManager运行后台任务。
更新:
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
}
}
Run Code Online (Sandbox Code Playgroud)
你的服务类
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
}
}
Run Code Online (Sandbox Code Playgroud)