首先在设置提醒之前你需要一个入口,比如说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 );
|
10 |
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, alarmCount, intent, 0 );
|
12 |
AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); |
13 |
am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent); |
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 );
|
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" );
|
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());
|
到这里闹钟提醒的功能就基本完成了。有问题可以留言。