android BroadcastReceiver ACTION_TIME_TICK 每分钟系统时间监听

来源:互联网 发布:linux mv 编辑:程序博客网 时间:2024/05/10 23:59

在众多的Intent的action动作中,Intent.ACTION_TIME_TICK是比较特殊的一个,根据SDK描述:

Broadcast Action: The current time has changed. Sent every minute. You can not receive this through components declared in manifests, only by exlicitly registering for it withContext.registerReceiver()

意思是说这个广播动作是以每分钟一次的形式发送。但你不能通过在manifest.xml里注册的方式接收到这个广播,只能在代码里通过registerReceiver()方法注册。


今天做android上的消息推送,启动了一个独立service,然后在里面监听系统的ACTION_TIME_TICK消息,即tick就是以分钟为单位,每分钟都会监听到一次,

按照网上说的在androidmanifast.xml里加入了

 

复制代码
 <receiverandroid:name="com.xxx.xxx.TimeChangeReceiver">        <intent-filterandroid:name="android.intent.action.ACTION_TIME_TICK"></intent-filter>    </receiver>
复制代码

然后也写了个继承自BroadcastReceiver的类叫做TimeChangeReceiver与上面对应,结果就是无法监听到这个事件,

花了半个小时无果,google的api页面又被墙了,于是尝试使用动态添加的方式,即在程序里需要的地方直接new一个receiver出来 ,果断删掉这个类,和xml里的上面那一段,直接在service的onCreate里写如下代码:

1 IntentFilter filter=new IntentFilter();2         filter.addAction(Intent.ACTION_TIME_TICK);3         registerReceiver(receiver,filter);
复制代码
 1 private final BroadcastReceiver receiver = new BroadcastReceiver() { 2         @Override 3           public void onReceive(Context context, Intent intent) { 4               String action = intent.getAction(); 5                 if (action.equals(Intent.ACTION_TIME_TICK)) { 6  7                   //do what you want to do ...13                     14                 }15           }16     };
复制代码

成功了。


1 0
原创粉丝点击