Android定时发送通知

定时使用到的是AlarmManager类,通知使用到的是NotificationManager类,创建实例的方法如下:

AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
AlarmManager常用到的方法有三个:

(1)set(int type, long triggerAtMillis, PendingIntent operation)

该方法用于设置一次性闹钟

(2)setRepeating(int type, long triggerAtMillis, long intervalMillis, PendingIntent operation)

该方法用于设置重复闹钟

(3)setInexactRepeating(int type, long triggerAtMillis, long intervalMillis, PendingIntent operation)

该方法也用于设置重复闹钟,只是两个闹钟执行的时间间隔不确定而已,这是系统在耗电性方面做得优化,系统会自动检测目前有多少Alarm任务存在,然后将触发时间比较近的几个任务放在一起执行,这样大幅度地减少了CPU被唤醒的次数,从而有效延长了电池的使用时间。

下面对方法中使用到的参数做如下说明:

int type:表示AlarmManager的工作类型,有四种值可选,分别是ELAPSED_REALTIME、ELAPSED_REALTIME_WAKEUP、RTC 和RTC_WAKEUP。其中ELAPSED_REALTIME表示让定时任务的触发时间从系统开机时开始算起,但不会唤醒CPU。ELAPSED_REALTIME_WAKEUP同样表示让定时任务的触发时间从系统开机时开始算起,但会唤醒CPU。RTC表示让定时任务的触发时间从1970年1月1日0点开始算起,但不会唤醒CPU。RTC_WAKEUP同样表示让定时任务的触发时间从1970年1月1日0点开始算起,但会唤醒CPU。使用SystemClock.elapsedRealtime()方法可以获取到系统开机至今所经历时间的毫秒数,使用System.currentTimeMillis()方法可以获取从1970年1月1日至今所经历的毫秒数。

long triggerAtMillis:表示定时任务触发的时间,以毫秒为单位。如果第一个参数使用的是ELAPSED_REALTIME 或ELAPSED_REALTIME_WAKEUP,则这里传入SystemClock.elapsedRealtime()。如果第一个参数使用的是,则这里传入System.currentTimeMillis()。使用第一个方法,此处参数可以加上延迟执行的时间。

long intervalMillis:表示两个闹钟执行的间隔时间。

PendingIntent operation:表示执行的动作。这里我们一般会调用getService()方法或getBroadcast()方法来获取一个能够执行服务或广播的PendingIntent。这样当定时任务被触发时,服务的onStartCommand()方法或广播接收器的onReceive()方法就可以得到执行了。

@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.plan_activity);
		
		Intent intent = new Intent(this, AlarmReceiver.class);
		intent.setAction("NOTIFICATION");
		PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);
		AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		int type = AlarmManager.RTC_WAKEUP;
		//new Date():表示当前日期,可以根据项目需求替换成所求日期
		//getTime():日期的该方法同样可以表示从1970年1月1日0点至今所经历的毫秒数
		long triggerAtMillis = new Date().getTime();
		long intervalMillis = 1000 * 60;
		manager.setInexactRepeating(type, triggerAtMillis, intervalMillis, pi);
	}


通过广播接受起方式发送通知如下:

public class AlarmReceiver extends BroadcastReceiver {
	
	private static final int NOTIFICATION_ID = 1000;

	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals("NOTIFICATION")) {
			NotificationManager manager = (NotificationManager) context  
                    .getSystemService(Context.NOTIFICATION_SERVICE);  
			Intent intent2 = new Intent(context, MainActivity.class);
			PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent2, 0);  
            Notification notify = new NotificationCompat.Builder(context)  
                    .setSmallIcon(R.drawable.alarm_tick)  
                    .setTicker("您的***项目即将到期,请及时处理!")  
                    .setContentTitle("项目到期提醒")  
                    .setStyle(new NotificationCompat.BigTextStyle().bigText("此处注明的是有关需要提醒项目的某些重要内容"))
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true)
                    .setNumber(1).build();   
            manager.notify(NOTIFICATION_ID, notify);  
		}

	}

}
通过服务发送通知如下:

public class AlarmService extends Service {
	
	private static final int NOTIFICATION_ID = 1000;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);  
				Intent intent2 = new Intent(AlarmService.this, MainActivity.class);
				PendingIntent pendingIntent = PendingIntent.getActivity(getApplication(), 0, intent2, 0);  
		        Notification notify = new NotificationCompat.Builder(getApplication())  
		                .setSmallIcon(R.drawable.alarm_tick)  
		                .setTicker("您的***项目即将到期,请及时处理!")  
		                .setContentTitle("项目到期提醒")  
		                .setStyle(new NotificationCompat.BigTextStyle().bigText("此处注明的是有关需要提醒项目的某些重要内容"))
		                .setContentIntent(pendingIntent)
		                .setAutoCancel(true)
		                .build();   
		        manager.notify(NOTIFICATION_ID, notify);
			}
		}).start();
		return super.onStartCommand(intent, flags, startId);
	}
}

  • 6
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值