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; } }
最终效果: