Intent.ACTION_TIME_TICK的正确用法

Home / Android MrLee 2015-4-21 16133

开发守护进程或者天气预报一些定期检查服务是否存在操作时我们需要用到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配置肯定是不行的。只能用过代码动态注册。
IntentFilter filter=new IntentFilter();
filter.addAction(Intent.ACTION_TIME_TICK);
registerReceiver(receiver,filter);
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                     
                }
          }
    };
检测服务是否在运行中:
	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;
	}

现在,你能收到这个广播了!赶紧更新吧~~~

本文链接:https://www.it72.com/2276.htm

推荐阅读
最新回复 (0)
返回