本篇文章给大家分享的是有关定时任务如何在Android应用中实现,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
首先要在AndroidManifest.xml中进行注册
<receiver android:name=".AlarmReceiver">
<intent-filter>
<action android:name="CLOCK" />
</intent-filter>
</receiver>
自定义一个闹钟接收器,getIntExtra可用于接受发送方putExtra传过来的值,Intent i = new Intent(“CLOCK”)其中的“CLOCK”是注册时使用的seceiver的name。
public class AlarmReceiver extends BroadcastReceiver {
private int _id;
private String str;
@Override
public void onReceive(Context context, Intent intent) {
_id = intent.getIntExtra("ID", -1);
Intent i = new Intent("CLOCK");
i.setClass(context, NoteEditor.class);
i.putExtra("ID", _id);
String str = intent.getStringExtra("NOTE");
Toast.makeText( context, str, Toast.LENGTH_SHORT).show();
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
时间的获取通过DatePickerDialog和TimePickerDialog,需要注意的是DatePickerDialog的月份是从0开始。将获取的数据放在Calendar类中,其中月份的存储也是从0开始。
final AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar alarmCalendar = Calendar.getInstance();
alarmCalendar.set(mYear, mMonth-1, mDay, mHour, mMinute,0);
Intent i = new Intent("CLOCK");
i.setClass(this, AlarmReceiver.class);
i.putExtra("ID", _id);
String note="notes";
i.putExtra("NOTE",note);
设置一个PendingIntent对象作为闹钟响应的对象,发送广播。第二个参数可以为0,但是因为做的是一次性的闹钟,如果为0的话,新设的闹钟会将之前设的闹钟覆盖掉。FLAG_UPDATE_CURRENT: 如果希望获取的PendingIntent对象与已经存在的PendingIntent对象相比,如果只是Intent附加的数据不同, 那么当前存在的PendingIntent对象不会被取消,而是重新加载新的Intent附加的数据。
PendingIntent pi = PendingIntent.getBroadcast(this, _id,i,PendingIntent.FLAG_UPDATE_CURRENT);
发送闹钟请求,设置在alarmCalendar.getTimeInMillis()时间启动由pi指定的组件。
第一个参数用来指定定时服务的类型,主要可选以下值:
AlarmManager.ELAPSED_REALTIME:睡眠状态下不可用,该状态下闹钟使用相对时间。
AlarmManager.ELAPSED_REALTIME_WAKEUP:在睡眠状态下会唤醒系统并执行提示功能,也使用相对时间。
AlarmManager.RTC:该状态睡眠状态下不可用,使用绝对时间,即当前系统时间。
AlarmManager.RTC_WAKEUP:闹钟在睡眠状态下会唤醒系统并执行提示功能,该状态下闹钟也使用绝对时间。
am.set(AlarmManager.RTC_WAKEUP, alarmCalendar.getTimeInMillis(), pi);
以上就是定时任务如何在Android应用中实现,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注天达云行业资讯频道。