Android每秒都会从处理程序更新ui

前端之家收集整理的这篇文章主要介绍了Android每秒都会从处理程序更新ui前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要一点帮助,每秒从Runnable / Handler更新我的UI.我正在使用此代码
Runnable runnable = new Runnable() {
        @Override
        public void run() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {

                        prBar.setProgress(myProgress);
                        y = (double) ( (double) myProgress/ (double) RPCCommunicator.totalPackets)*100;
                        txtInfoSync1.setText(Integer.toString((int)y) + "%");
                        prBar.setMax(RPCCommunicator.totalPackets);

                        int tmp = totalBytesReceived - timerSaved;
                        Log.w("","totalBytesReceived : "+totalBytesReceived + " timerSaved : "+timerSaved );
                        Log.w("","tmp : "+tmp);

                        if (avgSpeedCalc.size() > 10)
                        {
                            avgSpeedCalc.remove(0);
                        }

                        avgSpeedCalc.add(tmp);

                        int x = 0;

                        for (int y=0;y<avgSpeedCalc.size();y++)
                        {
                            x += avgSpeedCalc.get(y);
                            Log.d("","x : "+x);
                        }

                        x = Math.round(x/avgSpeedCalc.size());
                        Log.e("","x : "+x);

                        timerSaved = totalBytesReceived;
                        txtSpeed.setText(Integer.toString(x));

                    }
                });
        }
    };

我尝试使用handler.postDelayed(runnable,1000);在onCreate()中,但是runnable永远不会启动.或者即使我尝试使用runnable.run();,它仍然无法正常工作.

任何想法我怎么能开始runnable / handler并每秒更新一次ui?

解决方法

为什么要在runnable中创建runnable?

试试这个:

// flag that should be set true if handler should stop
boolean mStopHandler = false;

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // do your stuff - don't create a new runnable here!
        if (!mStopHandler) {
            mHandler.postDelayed(this,1000);
        }
    }
};

// start it with:
mHandler.post(runnable);
原文链接:https://www.f2er.com/android/318468.html

猜你在找的Android相关文章