无法更新textview以显示当前可用的主内存

时间:2014-04-26 16:49:19

标签: android multithreading textview

我正在尝试编写一个应用程序,每秒更新当前可用的主内存,我编写了下面的代码,但应用程序崩溃了。没有使用线程,当我添加线程时应用程序崩溃

,它工作正常
public class MainActivity extends Activity {
    Thread t;
    ActivityManager activityManager ;
    MemoryInfo mi;
    TextView MainMem_avail;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MainMem_avail=new TextView(this);
    setContentView(MainMem_avail);        
}
public void onResume()
{
    t=new Thread()
    {
        public void run()
        {
            try
            {
                while(true)
                {                       
                    mi = new MemoryInfo();
                    activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
                    activityManager.getMemoryInfo(mi);
                    runOnUiThread(new Runnable() {
                          @Override
                          public void run() {
                              MainMem_avail.setText("Available Main memory="+mi.availMem/(1024*1024)+"MB");
                          }
                        });
                    sleep(1000);
                }
            }
            catch(Exception e)
            {
                System.out.println("something went wrong");
            }
        }
    };
    t.start();
}
public void onPause()
{
    t.destroy();
}}

2 个答案:

答案 0 :(得分:1)

您无法从主线程外部触摸UI。而是每秒将延迟的runnable发布到主线程处理程序。

如何执行此操作的示例如下:

final Handler h = new Handler();
Runnable r = new Runnable() {
@Override
public void run() {
*Update Text View Here*
h.postDelayed(this, 1000);
    }
};
r.run();

要停止正常运行,请致电

h.removeCallbacks(r);

如果你创建了h和r全局变量,那么你可以为它们创建一个启动和停止功能,允许你通过删除它的回调或再次调用run()来切换它的操作

答案 1 :(得分:-1)

我编辑,因为它错了,现在它更好

final int delay = 0;
final int period = 1000;
final Runnable r = new Runnable() {
    public void run() {
        runOnUiThread(new Runnable() {
            mi = new MemoryInfo();
            activityManager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
            activityManager.getMemoryInfo(mi);
            MainMem_avail.setText("Available Main memory="+mi.availMem/(1024*1024)+"MB");
        }
        postDelayed(this, period);
    }
};

postDelayed(r, delay);