定时任务如何在Android应用中实现

发布时间:2020-12-07 16:52:20 作者:Leah
来源:亿速云 阅读:183

本篇文章给大家分享的是有关定时任务如何在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应用中实现,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

推荐阅读:
  1. 如何在python中实现BlockingScheduler定时任务
  2. 如何在SpringBoot中实现一个定时任务

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

android roi

上一篇:怎么在Android中利用videoview对抢占的焦点进行处理

下一篇:Android应用中实现图片压缩的方法有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》