zoukankan      html  css  js  c++  java
  • 使用AlarmManager启动广播、服务、页面(Android定时器) 分类: Android 2015-07-14 17:49 13人阅读 评论(0) 收藏

         AlarmManager是Android中的一种系统级别的提醒服务,它会为我们在特定的时刻广播一个指定的Intent。而使用Intent的时候,我们还需要它执行一个动作,如startActivity,startService,startBroadcast,才能使Intent有用。通常我们使用PendingIntent,它可以理解为对Intent的封装,包含了指定的动作。

    AlarmManager 包含的主要方法:

    <span style="font-size:14px;">// 取消已经注册的与参数匹配的定时器     
    void   cancel(PendingIntent operation)    
    //注册一个新的延迟定时器  
    void   set(int type, long triggerAtTime, PendingIntent operation)    
    //注册一个重复类型的定时器  
    void   setRepeating(int type, long triggerAtTime, long interval, PendingIntent operation)    
    //注册一个非精密的重复类型定时器  
    void setInexactRepeating (int type, long triggerAtTime, long interval, PendingIntent operation)  
    //设置时区    
    void   setTimeZone(String timeZone) </span>

    定时器主要类型:

    public   static   final   int  ELAPSED_REALTIME    
    // 当系统进入睡眠状态时,这种类型的闹铃不会唤醒系统。直到系统下次被唤醒才传递它,该闹铃所用的时间是相对时间,是从系统启动后开始计时的,包括睡眠时 间,可以通过调用SystemClock.elapsedRealtime()获得。系统值是3    (0x00000003)。     
        
    public   static   final   int  ELAPSED_REALTIME_WAKEUP    
    //能唤醒系统,用法同ELAPSED_REALTIME,系统值是2 (0x00000002) 。     
        
    public   static   final   int  RTC    
    //当系统进入睡眠状态时,这种类型的闹铃不会唤醒系统。直到系统下次被唤醒才传递它,该闹铃所用的时间是绝对时间,所用时间是UTC时间,可以通过调用 System.currentTimeMillis()获得。系统值是1 (0x00000001) 。     
        
    public   static   final   int  RTC_WAKEUP    
    //能唤醒系统,用法同RTC类型,系统值为 0 (0x00000000) 。     
        
    Public static   final   int  POWER_OFF_WAKEUP    
    //能唤醒系统,它是一种关机闹铃,就是说设备在关机状态下也可以唤醒系统,所以我们把它称之为关机闹铃。使用方法同RTC类型,系统值为4(0x00000004)。 

    当你的应用不在运行,而此时你仍然需要你的应用去执行一些操作(比如,短信拦截),只有这种时候才使用AlarmManager, 其他正常情况下的,推荐使用Handler。


    AlarmManager 生命周期:

    repeating AlarmManager一旦启动就会一直在后台运行(除非执行cancel方法),可以在“应用管理”中看到这个应用状态是正在运行。 “强行停止”可以让Alarmmanager停掉。

    尝试了几种任务管理器, 都只能重置计数器(确实释放内存了),但都无法关闭定时器,只有系统自带的“强行停止”奏效。

    如果某个AlarmManager已经启动, 程序又再次去启动它,只要PendingIntent是一样,那么之前那个AlarmManager会被release掉。


    如何使用AlarmManager?

    使用AlarmManager共有三种方式, 都是通过PendingIntent。

    getActivity(Context, int, Intent, int)  
      
    getBroadcast(Context, int, Intent, int)  
      
    getService(Context, int, Intent, int)  

        使用PendingIntent的getBroadcast (Context context, int requestCode, Intent intent, int flags)方法可以得到一个发送广播动作的PendingIntent对象。其中getBroadcast的第4个参数可以为以下4个常量或其他支持使用Intent.fillIn()来控制它的变量:

    FLAG_CANCEL_CURRENT:如果描述的PendingIntent对象已经存在时,会先取消当前的PendingIntent对象再生成新的。

    FLAG_NO_CREATE:如果描述的PendingIntent对象不存在,它会返回null而不是去创建它。

    FLAG_ONE_SHOT:创建的PendingIntent对象只使用一次。

    FLAG_UPDATE_CURRENT:如果描述的PendingIntent对象存在,则保留它,并将新的PendingIntent对象的数据替换进去。

    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),同样是用于设置重复闹钟,但是它是不准确的,相对于第二个方法,也更加节能。因为系统会将差不多的闹钟进行合并,以避免在不必要地唤醒设备。

    在上面的三个方法中,type为闹钟的类型,它可以使用以下四个常量:

    ELAPSED_REALTIME:闹钟在睡眠状态下不可用,使用的是相对系统启动时间。

    ELAPSED_REALTIME_WAKEUP:闹钟在睡眠状态下可用,使用的是相对系统启动时间。

    RTC:闹钟在睡眠状态下不可用,使用的是真实时间。

    RTC_WAKEUP:闹钟在睡眠状态下可用,使用的是真实时间。

    startTime为闹钟开始时间。

    intervalTime为闹钟间隔,在第三个方法中,内置的几个变量如下:

    INTERVAL_FIFTEEN_MINUTES 
    INTERVAL_HALF_HOUR 
    INTERVAL_HOUR 
    INTERVAL_HALF_DAY 
    INTERVAL_DAY

    如果我们设定的是发送广播的闹钟,我们还需要写一个广播接收器,并对其进行注册,它才会在闹钟开始的时候接收到广播。

    如果要设定启动Activity或Service的闹钟,则在创建PendingIntent的时候,首先Intent对象需设定指定的Activity或Service的class对象,然后对应的调用PendingIntent.getActivity()或PendingIntent.getService()方法。


    这边就举一个使用BroadCast的例子。

    首先是创建一个BroadCast类,需要继承BroadCastReceiver, 如下:

    /* 
     *  Copyright (c) 2011, Yulong Information Technologies 
     *  All rights reserved. 
     *   
     *  @Project: AlarmTest 
     *  @author: Robot   
     */  
    package com.yfz;  
      
    import android.content.BroadcastReceiver;  
    import android.content.Context;  
    import android.content.Intent;  
    import android.util.Log;  
      
    /** 
     * @author Robot 
     * @weibo http://weibo.com/feng88724 
     * @date Nov 18, 2011    
     */  
    public class ActionBroadCast extends BroadcastReceiver {  
          
        private static int num = 0;  
        /* (non-Javadoc) 
         * @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent) 
         */  
        @Override  
        public void onReceive(Context context, Intent intent) {  
            // TODO Auto-generated method stub  
            Log.e("ActionBroadCast", "New Message !" + num++);  
        }  
      
    }  
    下面就让我们启动AlarmManager, 这边就直接在Activity中启动了, 如下:

    package com.yfz;  
      
    import android.app.Activity;  
    import android.app.AlarmManager;  
    import android.app.PendingIntent;  
    import android.content.Intent;  
    import android.os.Bundle;  
      
    public class AlarmTestActivity extends Activity {  
        /** Called when the activity is first created. */  
        @Override  
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.main);  
              
            AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);  
              
            PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(this, ActionBroadCast.class), Intent.FLAG_ACTIVITY_NEW_TASK);  
            long now = System.currentTimeMillis();  
            am.setInexactRepeating(AlarmManager.RTC_WAKEUP, now, 3000, pi);  
        }  
    }  

    这边用Repeating的方式。 每隔3秒发一条广播消息过去。RTC_WAKEUP的方式,保证即使手机休眠了,也依然会发广播消息。

    最后看一下AndroidManifest文件,主要是注册一下Activity和BroadCast。  (实际使用中最好再加个filter,自己定义一个Action比较好)

    <?xml version="1.0" encoding="utf-8"?>  
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
        package="com.yfz"  
        android:versionCode="1"  
        android:versionName="1.0" >  
      
        <uses-sdk android:minSdkVersion="7" />  
      
        <application  
            android:icon="@drawable/ic_launcher"  
            android:label="@string/app_name" >  
            <activity  
                android:label="@string/app_name"  
                android:name=".AlarmTestActivity" >  
                <intent-filter >  
                    <action android:name="android.intent.action.MAIN" />  
      
                    <category android:name="android.intent.category.LAUNCHER" />  
                </intent-filter>  
            </activity>  
            <receiver  
                android:name="ActionBroadCast">  
                  
            </receiver>  
        </application>  
      
    </manifest>  

    Service的其实也差不多,只要在OnStart()方法中写需要执行的操作即可。

    参考博客:http://blog.csdn.net/feng88724/article/details/6989227


    做了一个例子,包含了使用AlarmManager的所有三种方式。已经上传至CSDN。

    下载地址: http://download.csdn.net/detail/u010963246/8900429

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    SASS搭建流程
    Javascript模块化编程(一)
    Javascript模块化编程发展历史
    jQuery文档处理
    jQuery事件对象
    软件开发中的11个系统思维定律
    Silverlight实例教程 理解Navigation导航框架Frame类
    eclipse自动关闭的原因
    你应该知道的15个Silverlight诀窍
    Eclipse 启动不起来异常:JVM terminated. Exit code=1
  • 原文地址:https://www.cnblogs.com/xieping/p/4666291.html
Copyright © 2011-2022 走看看