闹钟管理器AlarmManager基本用法

闹钟管理器可以在指定的时间触发事件,这样就可以做一些周期性的任务,比如定时更新数据,实现闹铃等。

The steps we follow for this exercise are 
1.   Get access to the alarm manager. 
2.   Come up with a time to set the alarm. 
3.   Create a receiver to be invoked. 
4.   Create a pending intent that can be passed to the alarm manager to invoke the 
receiver. 
5.   Use the time from step 2 and the pending intent from step 4 to set the alarm. 
6.   Watch the logcat for messages coming from the invoked receiver from step 3. 

获得AlarmManager的方法

AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); 

在Activity中获取AlarmManager然后设置触发时间

package com.xiyang.android.alarm;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;

public class LSN_ALARMTestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //创建一个广播接收者
        Intent broadcastIntent = new Intent("com.xiyang.alarm.test");
        broadcastIntent.putExtra("message", "Hello world");
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, broadcastIntent,    0);
        
        //获取闹钟管理器
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        //当前时间5秒后发送广播
        am.set(AlarmManager.RTC_WAKEUP, Utils.getTimeAfterInSecs(5).getTimeInMillis(), pi);

        // 时间到时,执行PendingIntent,只执行一次
        // AlarmManager.RTC_WAKEUP休眠时会运行,如果是AlarmManager.RTC,在休眠时不会运行
        am.setRepeating(AlarmManager.RTC_WAKEUP, Utils.getTimeAfterInSecs(5).getTimeInMillis(), 1000 * 6, pi);
        // 如果需要重复执行,使用上面一行的setRepeating方法,倒数第二参数为间隔时间,单位为毫秒
    }
}

定义一个BroadcastReceiver,处理触发事件

package com.xiyang.android.alarm;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class TestReceiver extends BroadcastReceiver  
{ 
    private static final String tag = "TestReceiver";  
    @Override 
    public void onReceive(Context context, Intent intent)  
    { 
        Log.d("TestReceiver", "intent=" + intent); 
        String message = intent.getStringExtra("message"); 
        Log.d(tag, message); 
    } 
} 

将应用安装到模拟器上,观察控制台,可以看到打印的日志信息,根据设置,每隔6秒会执行一次

posted on 2012-04-29 10:35  lepfinder  阅读(742)  评论(0编辑  收藏  举报