当前位置:   article > 正文

Android 刷新时间_android 熄屏发送action_time_tick

android 熄屏发送action_time_tick

数字时钟

一般我们看到需要刷新时间的需求,都会想到使用handler,开启子线程来刷新时间,但用handler发送消息来刷新时间可能会导致内存泄露,不够稳定,所以我们可以直接利用系统的广播来实现功能。

系统每分钟都会发送广播:Intent.ACTION_TIME_TICK

  1. public class NumberActivity extends AppCompatActivity {
  2. private TextView tevtView;
  3. private MyBroadcastReceiver myBroadcastReceiver;
  4. @Override
  5. protected void onCreate(Bundle savedInstanceState) {
  6. super.onCreate(savedInstanceState);
  7. setContentView(R.layout.activity_number);
  8. tevtView=findViewById(R.id.num);
  9. init();
  10. }
  11. // 初始化方法
  12. public void init() {
  13. // 新时间
  14. SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分", Locale.getDefault());
  15. tevtView.setText(sdf.format(new Date()));
  16. // 更新时间的广播
  17. IntentFilter filter=new IntentFilter();
  18. filter.addAction(Intent.ACTION_TIME_TICK);
  19. myBroadcastReceiver=new MyBroadcastReceiver();
  20. registerReceiver(myBroadcastReceiver,filter);
  21. }
  22. class MyBroadcastReceiver extends BroadcastReceiver{
  23. @Override
  24. public void onReceive(Context context, Intent intent) {
  25. String action = intent.getAction();
  26. assert action != null;
  27. if (action.equals(Intent.ACTION_TIME_TICK)) {
  28. SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分", Locale.getDefault());
  29. tevtView.setText(sdf.format(new Date()));
  30. }
  31. }
  32. }
  33. @Override
  34. protected void onDestroy() {
  35. super.onDestroy();
  36. // 注销广播
  37. unregisterReceiver(myBroadcastReceiver);
  38. }
  39. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/235807
推荐阅读
相关标签
  

闽ICP备14008679号