行之以诺的专栏

术业有专攻,如是而已!

获取系统时间并随时更新系统时间

<span style="font-family:SimSun;"><span style="font-size:18px;"></span></span><pre name="code" class="java"><pre name="code" class="java"><span style="font-size: 18px; "><span style="font-family:SimSun;">一种:直接使用Handler和Thread去实现</span></span>
<span style="font-size: 18px; "><span style="font-family:SimSun;">Handler:</span></span>

<span style="font-family:SimSun;font-size:18px;">class TimeHander extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				// 获取当前时间是12小时制还是24小时制
				ContentResolver cv = getApplicationContext()
						.getContentResolver();
				String strTimeFormat = android.provider.Settings.System
						.getString(cv,
								android.provider.Settings.System.TIME_12_24);
				// 获取当前系统时间
				c = Calendar.getInstance();
				hour = c.get(Calendar.HOUR_OF_DAY);
				minute = c.get(Calendar.MINUTE);
				if (strTimeFormat.equals("24")) {
					Log.i("activity", "24");
					if (minute < 10)
						tView.setText("时间:" + hour + ":" + "0" + minute);
					else {
						tView.setText("时间:" + hour + ":" + minute);
					}
				}
				if (strTimeFormat.equals("12")) {
					Log.i("activity", "12");
					String amPmValues;
					if (c.get(Calendar.AM_PM) == 0) {
						amPmValues = "AM";
					} else {
						amPmValues = "PM";
					}
					if (minute < 10)
						tView.setText("时间:" + hour + ":" + "0" + minute
								+ amPmValues);
					else {
						tView.setText("时间:" + hour + ":" + minute + amPmValues);
					}
				}
				monitorBatteryState();
				break;
			}
		}
	}
</span>
<span style="font-family:SimSun;font-size:18px;">开启一个线程每隔1S发送一个消息:</span>
<span style="font-family:SimSun;font-size:18px;"></span><pre name="code" class="java"><span style="font-family:SimSun;">class TimeThread extends Thread {
		@Override
		public void run() {
			do {
				try {
					Thread.sleep(1000);
					Message msg = new Message();
					msg.what = 1; // 消息(一个整型值)
					hander.sendMessage(msg);// 每隔1秒发送一个msg给mHandler
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} while (true);
		}
	}</span>
如果只是使用Handler和Thread来实现的话,会存在只发送一个消息到Handler,这个时候我们就得想办法去解决类似于定时发送器的作用:那么使用do{}while

<span style="font-family:SimSun;font-size:18px;">这样就可以实现简单的获取系统时间并随时更新的目的</span>
<span style="font-family:SimSun;font-size:18px;">第二种使用一个BroadcastReceiver和Service来实现</span>
<span style="font-family:SimSun;font-size:18px;">作为Android的四大组件,在做一些东西的时候,用该去多考虑一下,并不是说要效果就好,应该是怎么做最合理化。</span>
<span style="font-family:SimSun;font-size:18px;">在MainActivity中:</span>
<span style="font-family:SimSun;font-size:18px;">首先创建一个广播和服务</span>
<span style="font-family:SimSun;font-size:18px;">然后:在MainActivity中注册广播,当然注册广播的是可以在XML中注册也可以在代码中注册,这个根据情况而定,一般是在Activity中去注册,这个当Activity被销毁时,广播也可以跟随者去被注销:</span>
<span style="font-family:SimSun;font-size:18px;"></span><pre name="code" class="java"><span style="white-space:pre">	</span>@Override
	protected void onResume() {
		super.onResume();
		registerBroadcastReceiver();//注册广播
	}
	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(receiver);//注销广播
	}
	/**
	 * 注册广播
	 */
	private void registerBroadcastReceiver() {
		receiver = new UITimeReceiver();
		IntentFilter filter = new IntentFilter(TIME_CHANGED_ACTION);
		registerReceiver(receiver, filter);
	}
接着去启动一个服务:

<span style="font-family:SimSun;font-size:18px;"></span><pre name="code" class="java"><span style="white-space:pre">	</span>/**
	 * 启动服务
	 */
	private void startTimeService() {
		timeService = new Intent(MainActivity.this, TimeService.class);
		this.startService(timeService);
	}
	@Override  
  <span style="white-space:pre">	</span>  protected void onDestroy() {  
        super.onDestroy();  
        //停止服务   
        stopService(timeService);  
       }  
在Service中:

<span style="font-family:SimSun;font-size:18px;"></span><pre name="code" class="html">public class TimeService extends Service {
	private int hour;
	private int minute;
	private Calendar c;
	private Intent intent;
	private Bundle bundle;
	private Timer timer;

	public void onCreate() {
		c = Calendar.getInstance();
		intent = new Intent();
		bundle = new Bundle();
		timer = new Timer();
		timer.schedule(timerTask, 1000, 3000);//没隔2S发送一个广播
	}
	TimerTask timerTask = new TimerTask() {
		@Override
		public void run() {
			Message message = new Message();
			message.what = 1;
			handler.sendMessage(message);
		}
	};
	Handler handler = new Handler() {
		// 定义处理信息的方法
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				sendTimeChangedBroadcast();
				Log.e("多少次", "123456789");
				break;
			}
			super.handleMessage(msg);
		}

	};

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	/**
	 * 发送广播,通知UI层时间已改变
	 */
	private void sendTimeChangedBroadcast() {
		Calendar c = Calendar.getInstance();
		hour = c.get(Calendar.HOUR_OF_DAY);
		minute = c.get(Calendar.MINUTE);
		bundle.putInt("hour",hour);
		bundle.putInt("minute", minute);
		intent.putExtras(bundle);
		intent.setAction(MainActivity.TIME_CHANGED_ACTION);
		// 发送广播,通知UI层时间改变了
		sendBroadcast(intent);
	}

	/**
	 * 获取最新系统时间
	 * 
	 * @return
	 */
	private int getHour() {
		// 获取当前系统时间xisohi
		hour = c.get(Calendar.HOUR_OF_DAY);
		return hour;
	}

	private int getMinute() {
		// 获取当前系统时间fenzhong
		minute = c.get(Calendar.MINUTE);
		return minute;
	}

	@Override
	public ComponentName startService(Intent service) {
		Log.e("TTTTT", "TimeService->startService");
		return super.startService(service);
	}

	@Override
	public void onDestroy() {
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		super.onDestroy();
		Log.i("TTTTT", "TimeService->onDestroy");
	}

}
在BroadcastReceiver中:
<pre name="code" class="java"><pre name="code" class="html">public class UITimeReceiver extends BroadcastReceiver{
	private MainActivity activity = new MainActivity();
	private int hour;
	private int minute;
	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		if(MainActivity.TIME_CHANGED_ACTION.equals(action)){
			hour=intent.getExtras().getInt("hour");
			minute = intent.getExtras().getInt("minute");
			// 获取当前时间是12小时制还是24小时制
			ContentResolver cv = context
					.getContentResolver();
			String strTimeFormat = android.provider.Settings.System
					.getString(cv,
							android.provider.Settings.System.TIME_12_24);
			if (strTimeFormat.equals("24")) {
				Log.i("activity", "24");
				if (minute < 10)
					activity.tv_time.setText("时间:" + hour + ":" + "0" + minute);
				else {
					activity.tv_time.setText("时间:" + hour + ":" + minute);
				}
			}
			if (strTimeFormat.equals("12")) {
				Log.i("activity", "12");
				String amPmValues;
				Calendar c = Calendar.getInstance();
				if (c.get(Calendar.AM_PM) == 0) {
					amPmValues = "AM";
				} else {
					amPmValues = "PM";
				}
				if (minute < 10)
					activity.tv_time.setText("时间:" + hour + ":" + "0" + minute
							+ amPmValues);
				else {
					activity.tv_time.setText("时间:" + hour + ":" + minute + amPmValues);
				}
			}
		}
		
	}
}
这样简单的时间更新就可以实现了,利用一个定时发送器









<span style="font-family:SimSun;font-size:18px;">

</span>
</pre>
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014400200/article/details/38436451
文章标签: broadcastreceiver
个人分类: 系统
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭