Service 動態更新 UI
阿新 • • 發佈:2017-07-25
binder null manager edate nds pda update ive 發送廣播
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 { @Overridepublic 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