您的位置:首页 > 其它

一个简单的定时任务

2017-06-16 09:52 302 查看

一个简单的定时任务

使用AlarmManager来实现定时提醒,它提供了一种访问系统闹钟服务的方式。在全局中,达到设定的时间,

在它上面注册的一个Intent将会被广播,接着启动相应的应用程序,可以通过自定义Receiver来实现。

首先要在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);


作者:魏超凡:原文地址
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: