首先在設定提醒之前你需要一個入口,比如說onclick事件中,在此不做贅述。
android中使用鬧鐘進行提醒其實非常簡單,你只需要告知系統你想在什麼時候被提醒,然後需要一個鬧鐘的廣播接收器,當到你設定的時間時,系統會給你發送一條廣播,當你接收到廣播後你就可以做一些操作,比如啟動你的app,或者跳轉到你app中的任何一個介面。廢話不多少,直接上代碼。
02 |
Intent intent = new Intent(mContext, AlarmReceiver.class); |
03 |
intent.setAction("something"); |
04 |
intent.setType("something"); |
05 |
intent.setData(Uri.EMPTY); |
06 |
intent.addCategory(“something”); |
07 |
intent.setClass(context, AlarmReceiver.class); |
08 |
// 以上給intent設定的四個屬性是用來區分你發給系統的鬧鐘請求的,當你想取消掉之前發的鬧鐘請求,這四個屬性,必須嚴格相等,所以你需要一些比較獨特的屬性,比如伺服器返回給你的json中某些特定欄位。 |
09 |
//當然intent中也可以放一些你要傳遞的訊息。 |
10 |
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, alarmCount, intent, 0); |
11 |
//alarmCount是你需要記錄的鬧鐘數量,必須保證你所發的alarmCount不能相同,最後一個參數填0就可以。 |
12 |
AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); |
13 |
am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent); |
14 |
//這樣鬧鐘的請求就發送出去了。time是你要被提醒的時間,單位毫秒,注意不是時間差。第一個參數提醒的需求用我給出的就可以,感興趣的朋友,可以去google一下,這方面的資料非常多,一共有種,看一下就知道區別了。 |
16 |
Intent intent = new Intent(mContext, AlarmReceiver.class); |
17 |
intent.setAction("something"); |
18 |
intent.setType(something); |
19 |
intent.setData(Uri.EMPTY); |
20 |
intent.addCategory(something); |
21 |
intent.setClass(context, AlarmReceiver.class); |
22 |
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, alarmCount, intent, 0); |
23 |
//alarmCount對應到你設定時的alarmCount, |
24 |
AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); |
25 |
am.cancel(pendingIntent); |
27 |
public class AlarmReceiver extends BroadcastReceiver{ |
29 |
private NotificationManager manager; |
32 |
public void onReceive(Context context, Intent intent) { |
33 |
manager = (NotificationManager)context.getSystemService(android.content.Context.NOTIFICATION_SERVICE); |
35 |
String id = intent.getStringExtra("id"); |
36 |
//MainActivity是你點擊通知時想要跳轉的Activity |
37 |
Intent playIntent = new Intent(context, MainActivity.class); |
38 |
playIntent.putExtra("id", id); |
39 |
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, playIntent, PendingIntent.FLAG_UPDATE_CURRENT); |
40 |
NotificationCompat.Builder builder = new NotificationCompat.Builder(context); |
41 |
builder.setContentTitle("title").setContentText("提醒內容").setSmallIcon(R.drawable.app_icon).setDefaults(Notification.DEFAULT_ALL).setContentIntent(pendingIntent).setAutoCancel(true).setSubText("二級text"); |
42 |
manager.notify(1, builder.build()); |
到這裡鬧鐘提醒的功能就基本完成了。有問題可以留言。