Service 动态更新 UI

Posted qlky

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

Activity和Service交互之bindService(回调更新UI)

4. Building a Dynamic UI with Fragments 使用片段构建动态UI

如何在使用片段和计时器的选项卡式活动上更新 UI

Android service 可以直接更新UI吗

动态 TextView 未在片段中更新

wpf 动态更新 UI 而不会冻结 UI