由于公司业务需要,必须需要定时任务,以前从来没用过JAVA写代码,只能先研究了原生代码,再研究了《Android平台通过native.js实现接收系统消息,如监听安装卸载apk事件》,有了以下代码,在android9.0通过测试,代码如下:
var AlarmManager;
var PendingIntent;
var Intent;
var IntentFilter;
var Context;
var Calendar;
var main;
var System;
var receiver;
var ALARM_EVENT = "com.kkaass.alarm";
mui.plusReady(function(){
AlarmManager = plus.android.importClass('android.app.AlarmManager');
PendingIntent = plus.android.importClass('android.app.PendingIntent');
Intent = plus.android.importClass('android.content.Intent');
IntentFilter = plus.android.importClass('android.content.IntentFilter');
Context = plus.android.importClass('android.content.Context');
receiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver',{
onReceive:function(context,intent){
if(intent != null){
console.log('闹铃来了');
SetAlarm();
}
}
});
main = plus.android.runtimeMainActivity();
Calendar = plus.android.importClass('java.util.Calendar');
System = plus.android.importClass('java.lang.System');
var intentfilter = new IntentFilter();
intentfilter.addAction(ALARM_EVENT);
main.registerReceiver(receiver,intentfilter)
});
function SetAlarm(){
var intent = new Intent(ALARM_EVENT);
var pendingintent = PendingIntent.getBroadcast(main,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
var alarmManager =main.getSystemService(Context.ALARM_SERVICE);
var calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND,20);
alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingintent);//setAndAllowWhileIdle方法API>=23才能使用
}
14 个评论
要回复文章请先登录或注册
it_dyh
8***@qq.com (作者)
it_dyh
DCloud_heavensoft