首页 > 代码库 > Service 动态更新 UI
Service 动态更新 UI
http://blog.csdn.net/u013724061/article/details/38642049
最终效果:
动态显示当前时间和电量
思路:
首先在Activity里用内部类定义两种广播,一种是系统广播(电池),另一种是自定义广播。
private class SimpleBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { int currLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0); //当前电量 int total = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 1); //总电量 int percent = currLevel * 100 / total; updateG(percent); Log.i(TAG, "battery: " + percent + "%"); } } private class UpdateTimeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd"); SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); String dateStr = dateFormat.format(date); String timeStr = timeFormat.format(date); tv_date.setText(dateStr + ":" + timeStr);//显示出日期 } }
在OnResume中注册广播,OnPause中移除 (文章中有为什么不在onStart和onStop中的解释)
@Override protected void onResume() { super.onResume(); IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); simpleBroadcastReceiver = new SimpleBroadcastReceiver(); registerReceiver(simpleBroadcastReceiver, intentFilter); intentFilter = new IntentFilter("ACTION_UPDATE_TIME"); updateTimeReceiver = new UpdateTimeReceiver(); registerReceiver(updateTimeReceiver, intentFilter); Intent intent = new Intent(this,UpdateGService.class); startService(intent); } @Override protected void onPause() { super.onPause(); unregisterReceiver(simpleBroadcastReceiver); unregisterReceiver(updateTimeReceiver); Intent intent = new Intent(this,UpdateGService.class); stopService(intent); }
建立个service来处理动态更新
public class UpdateGService extends Service { @Override public void onCreate() { super.onCreate(); new Timer().scheduleAtFixedRate(new TimerTask() { @Override public void run() { Intent timeIntent = new Intent(); timeIntent.setAction("ACTION_UPDATE_TIME");//自定义Action sendBroadcast(timeIntent); //发送广播 } }, 0, 1000); //每隔1秒 } @Nullable @Override public IBinder onBind(Intent intent) { return null; } }
最终效果:
Service 动态更新 UI
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。