首先在設置提醒之前你需要一個入口,比如說onclick事件中,在此不做贅述。
android中使用鬧鍾進行提醒其實非常簡單,你只需要告知系統你想在什么時候被提醒,然后需要一個鬧鍾的廣播接收器,當到你設置的時間時,系統會給你發送一條廣播,當你接收到廣播后你就可以做一些操作,比如啟動你的app,或者跳轉到你app中的任何一個界面。廢話不多少,直接上代碼。
01 |
//發送鬧鍾請求 |
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一下,這方面的資料非常多,一共有種,看一下就知道區別了。 |
15 |
//取消鬧鍾請求 |
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); |
26 |
//接着,你需要一個廣播接收的類: |
27 |
public class AlarmReceiver extends BroadcastReceiver{ |
28 |
29 |
private NotificationManager manager; |
30 |
|
31 |
@Override |
32 |
public void onReceive(Context context, Intent intent) { |
33 |
manager = (NotificationManager)context.getSystemService(android.content.Context.NOTIFICATION_SERVICE); |
34 |
//例如這個id就是你傳過來的 |
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()); |
43 |
} |
44 |
} |
到這里鬧鍾提醒的功能就基本完成了。有問題可以留言。