1.创建一个AlertService.class,继承Service。
public class AlertService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
public static final int NOTIFICATION_ID=1;
@Override
public void onCreate() {
// 创建通知管理器的实例
final NotificationManager nm=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification n=new Notification(); // 创建通知的实例
//两种设置声音的方法
n.sound=Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "20");
// n.sound=Uri.parse("file:///sdcard/alarm.mp3");
nm.notify(NOTIFICATION_ID, n); // 发布通知以显示在状态栏中
}
public PendingIntent getDefalutIntent(int flags){
PendingIntent pendingIntent= PendingIntent.getActivity(this, 1, new Intent(), flags);
return pendingIntent;
}
}
2.创建AlarmReceiver.class,继承自BroadcastReceiver类。
public class AlarmReceiver extends BroadcastReceiver {
private NotificationManager manager;
//当BroadcastReceiver接收到Intent广播时调用。
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "闹铃响了, 可以做点事情了~~", Toast.LENGTH_LONG).show();
manager = (NotificationManager)context.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
//例如这个id就是你传过来的
String id = intent.getStringExtra("id");
id= "0";
//MainActivity是你点击通知时想要跳转的Activity
Intent playIntent = new Intent(context, MainActivity.class);
playIntent.putExtra("id", id);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, playIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentTitle("title").setContentText("提醒内容").setSmallIcon(R.drawable.ic_launcher).setDefaults(Notification.DEFAULT_ALL).setContentIntent(pendingIntent).setAutoCancel(true).setSubText("二级text");
manager.notify(1, builder.build());
}
}
3.在MainActivity中onCreate()方法外添加方法:
//+_+_+_+_+_+设置提醒+_+_+_+_+
private void setReminder(boolean b) {
mydb=new MyDBAdapter(this);
AlarmManager am= (AlarmManager) getSystemService(ALARM_SERVICE);
// 创建将执行广播的PendingIntent
PendingIntent pi= PendingIntent.getBroadcast(AlarmActivity.this, 0, new Intent(this,AlarmReceiver.class), 0);
if(b){
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),pi);
}
else{
// cancel current alarm
am.cancel(pi);
}
}
其中am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),pi);第二个参数为指定的响铃时间。要把时间先包装到一个Calendar实例中:
Calendar Calendar=Calendar.getInstance();
calendar.set(year, month,day,hour,minute);
其中的year、month…….就是你设置的响铃时间。
4.在OnCreate()方法中调用setReminder(true)就可以了。