如何从我的Application类在UI线程上运行某些东西

时间:2014-12-12 18:22:05

标签: android

我需要在UI线程

上的扩展Application类中运行一些东西
Handler h = new Handler();
    h.postDelayed(new Runnable() {

    @Override
    public void run() {
        //I need to run code here on the main thread
    }
}, 1000);

我需要通过活动吗?因为我从多个活动中调用它,所以很难。

2 个答案:

答案 0 :(得分:0)

Android在Application类中调用的方法已经在UI线程上运行(a.k.a'main'线程)。

如有疑问,可以使用Thread.currentThread()查找。

请记住避免在主线程上进行昂贵的操作。

答案 1 :(得分:-2)

您需要调用runOnUiThread

MainActivity.this.runOnUiThread(new Runnable() {
    public void run() {
        Log.d("UI thread", "I am the UI thread");
    }
});