Android 如何让程序定时进行消息通知到通知栏

来源:互联网 发布:同步带轮生成软件 编辑:程序博客网 时间:2024/06/05 14:49

实现定时推送信息到通知栏

MainActivity.class

public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Intent intent = new Intent(this, AutoReceiver.class);intent.setAction("VIDEO_TIMER");                // PendingIntent这个类用于处理即将发生的事情                               PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);                // AlarmManager.ELAPSED_REALTIME_WAKEUP表示闹钟在睡眠状态下会唤醒系统并执行提示功能,该状态下闹钟使用相对时间                // SystemClock.elapsedRealtime()表示手机开始到现在经过的时间                am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime(), 10 * 1000, sender);}}

AlarmManager的常用方法有三个:
(1)set(int type,long startTime,PendingIntent pi);
        该方法用于设置一次性闹钟,第一个参数表示闹钟类型,第二个参数表示闹钟执行时间,第三个参数表示闹钟响应动作。
(2)setRepeating(int type,long startTime,long intervalTime,PendingIntent pi);
        该方法用于设置重复闹钟,第一个参数表示闹钟类型,第二个参数表示闹钟首次执行时间,第三个参数表示闹钟两次执行的间隔时间,第四个参数表示闹钟响应动作。

(3)setInexactRepeating(int type,long startTime,long intervalTime,PendingIntent pi);
        该方法也用于设置重复闹钟,与第二个方法相似,不过其两个闹钟执行的间隔时间不是固定的而已。从长远来看,执行的频率将正好是指定周期的倒数。

第一个参数是一个整型参数,用于指定AlarmManager 的工作类型,有四种值可选,分别是ELAPSED_REALTIME、ELAPSED_REALTIME_WAKEUP、RTC 和RTC_WAKEUP。其中ELAPSED_REALTIME 表示让定时任务的触发时间从系统开机开始算起,但不会唤醒CPU。ELAPSED_REALTIME_WAKEUP 同样表示让定时任务的触发时间从系统开机开始算起,但会唤醒CPU。RTC 表示让定时任务的触发时间从1970 年1月1 日0 点开始算起,但不会唤醒CPU。RTC_WAKEUP 同样表示让定时任务的触发时间从1970 年1 月1 日0 点开始算起,但会唤醒CPU。使用SystemClock.elapsedRealtime()方法可以获取到系统开机至今所经历时间的毫秒数,使用System.currentTimeMillis()方法可以获取到1970 年1 月1 日0 点至今所经历时间的毫秒数。

然后看一下第二个参数,这个参数就好理解多了,就是定时任务触发的时间,以毫秒为单位。如果第一个参数使用的是ELAPSED_REALTIME 或ELAPSED_REALTIME_WAKEUP,则这里传入开机至今的时间再加上延迟执行的时间。如果第一个参数使用的是RTC 或RTC_WAKEUP,则这里传入1970 年1 月1 日0 点至今的时间再加上延迟执行的时间。

第三个参数是一个PendingIntent,对于它你应该已经不会陌生了吧。这里我们一般会调用getBroadcast()方法来获取一个能够执行广播的PendingIntent。这样当定时任务被触发的时候,广播接收器的onReceive()方法就可以得到执行。了解了set()方法的每个参数之后,设定一个任务在10 秒钟后执行还可以写成:
long triggerAtTime = System.currentTimeMillis() + 10 * 1000;
manager.set(AlarmManager.RTC_WAKEUP, triggerAtTime, pendingIntent);


AutoReceiver.class

public class AutoReceiver extends BroadcastReceiver {private static final int NOTIFICATION_FLAG = 1;@SuppressLint("NewApi")@Overridepublic void onReceive(Context context, Intent intent) {if (intent.getAction().equals("VIDEO_TIMER")) {PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,new Intent(context, MainActivity.class), 0);// 通过Notification.Builder来创建通知,注意API Level// API16之后才支持Notification notify = new Notification.Builder(context).setSmallIcon(R.drawable.ic_launcher).setTicker("TickerText:" + "您有新短消息,请注意查收!").setContentTitle("Notification Title").setContentText("This is the notification message").setContentIntent(pendingIntent).setNumber(1).build(); // 需要注意build()是在API       // level16及之后增加的,API11可以使用getNotificatin()来替代notify.flags |= Notification.FLAG_AUTO_CANCEL; // FLAG_AUTO_CANCEL表明当通知被用户点击时,通知将被清除。// 在Android进行通知处理,首先需要重系统哪里获得通知管理器NotificationManager,它是一个系统Service。NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);manager.notify(NOTIFICATION_FLAG, notify);// 步骤4:通过通知管理器来发起通知。如果id不同,则每click,在status哪里增加一个提示}}}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.alarmtest"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="19" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.alarmtest.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <receiver            android:name=".AutoReceiver"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.BOOT_COMPLETED" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </receiver>    </application></manifest>


1 0
原创粉丝点击