Intent.ACTION_TIME_TICK的正确用法
16lz
2021-01-26
开发守护进程或者天气预报一些定期检查服务是否存在操作时我们需要用到ACTION_TIME_TICK。看看文档里面是怎么说ACTION_TIME_TICK的。
在众多的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()方法注册。
如此我们就知道如何操作了,在xml配置肯定是不行的。只能用过代码动态注册。
1 2 3 | IntentFilter filter= new IntentFilter(); filter.addAction(Intent.ACTION_TIME_TICK); registerReceiver(receiver,filter); |
1 2 3 4 5 6 7 8 9 10 | private final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_TIME_TICK)) { //do what you want to do ...13 } } }; |
检测服务是否在运行中:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public static boolean isServiceRunning(Class<?> serviceClass) { ActivityManager activityManager = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); List serviceList = activityManager .getRunningServices(Integer.MAX_VALUE); if (serviceList == null || serviceList.size() == 0 ) return false ; for (RunningServiceInfo info : serviceList) { if (info.service.getClassName().equals(serviceClass.getName())) return true ; } return false ; } |
现在,你能收到这个广播了!赶紧更新吧~~~
转载地址:http://www.ithtw.com/2276.html
更多相关文章
- android 广播的知识积累
- Android(安卓)App的国际化-代码里实现
- [android] toast解析
- Eclipse快捷键设置(转载)
- Android加载html代码和文件
- android基础知识05:四大组件之Broadcast Receiver
- 一网打尽__Android(安卓)开源代码合集(WebView框架)
- Android(安卓)Studio Mac 快捷键整理分享
- Android多线程研究(1)——线程基础及源代码剖析