数字时钟
一般我们看到需要刷新时间的需求,都会想到使用handler,开启子线程来刷新时间,但用handler发送消息来刷新时间可能会导致内存泄露,不够稳定,所以我们可以直接利用系统的广播来实现功能。
系统每分钟都会发送广播:Intent.ACTION_TIME_TICK
public class NumberActivity extends AppCompatActivity {
private TextView tevtView;
private MyBroadcastReceiver myBroadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_number);
tevtView=findViewById(R.id.num);
init();
}
// 初始化方法
public void init() {
// 新时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分", Locale.getDefault());
tevtView.setText(sdf.format(new Date()));
// 更新时间的广播
IntentFilter filter=new IntentFilter();
filter.addAction(Intent.ACTION_TIME_TICK);
myBroadcastReceiver=new MyBroadcastReceiver();
registerReceiver(myBroadcastReceiver,filter);
}
class MyBroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
assert action != null;
if (action.equals(Intent.ACTION_TIME_TICK)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分", Locale.getDefault());
tevtView.setText(sdf.format(new Date()));
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// 注销广播
unregisterReceiver(myBroadcastReceiver);
}
}
|