基于时间的提醒AlarmManager和Service

作为最贴身的电子移动设备,手机上的提醒功能无疑是最实用的了.Android中Notification简单易用,接下来就是对两种常用用法的介绍.

基于时间的提醒:
Notification本身没有管理时间的能力,所以我们用AlarmManager来触发Notification.

package test.TestNotification;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
/**
* 用AlarmManager来触发Notification
*/
public class TestNotification extends Activity
{
/**
* 初始化
*/
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//得到使用AlarmManager的权限
AlarmManager alarms=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
//AlarmManager要做的事情,打开NotificationService(这是个自定义Service稍后会补充)
Intent intent=new Intent(this,NotificationService.class);
PendingIntent pendingIntent=PendingIntent.getService(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
//设定时间,将System.currentTimeMillis()换成你需要的时间即可,这里是立即触发
alarms.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),pendingIntent);
}
}

在前面我们使用了Service来触发Notification,所以接下来自定义一个Service.

package test.TestNotification;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
/**
* 自定义Service,在其中启动Notification
*/
public class NotificationService extends Service
{
/**
* 继承Service必须实现的方法,这里用不到
*/
public IBinder onBind(Intent intent)
{
return null;
}
/**
* 初始化
*/
public void onCreate()
{
//以下是对Notification的各种参数设定
int icon=R.drawable.icon;
String tickerText=”这是一个提醒”;
long when=(System.currentTimeMillis());
Notification nfc=new Notification(icon,tickerText,when);
Context cxt=getApplicationContext();
String expandedTitle=”基于时间的提醒来了”;
String expandedText=”其实没什么重要的事”;
//intent是非常重要的参数,用来启动你实际想做的事情,设为null后点击状态栏上的Notification就没有任何反应了.
Intent intent=null;
PendingIntent nfcIntent=PendingIntent.getActivity(cxt,0,intent,0);
nfc.setLatestEventInfo(cxt,expandedTitle,expandedText,nfcIntent);
//发送Notification
NotificationManager nfcManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
nfcManager.notify(1,nfc);
}
}

这样,一个简单的定时提醒就完成了.
只要在应用中获得正确的时间,通过AlarmManager在那个时间点触发Service中的Notification,再用Notification启动相应的应用即可.
注意:AndroidManifest.xml中要添加上用到的NotificationService.(以上代码在Android2.2中测试通过)

转:http://www.freeideastudio.com.cn/wordpress/?p=329

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值