android - 如何在不出现 "cannot make a static reference to the non static method"编译器错误的情况下使用 runOnUiThread

标签 android multithreading

我有一个主类;

  ClientPlayer extends Activity {

和服务

  LotteryServer extends Service implements Runnable {

尝试在此服务的运行方法中使用 RunOnUiThread 时出现编译器错误,“无法对非静态方法进行静态引用”

如何解决这个问题?这里显示了我如何使用代码;

     @Override
public void run() {
   // I tried both ClientPlayer.runOnUiThread and LotteryServer.runOnUiThread
   // both don't work   
    ClientPlayer.runOnUiThread(new Runnable() {
        public void run() {
           Toast.makeText(getApplicationContext(), "from inside thread", Toast.LENGTH_SHORT).show();
        }
    });
} // end run method

最佳答案

runOnUiThread 不是静态方法。

如果你想在 UIThread 上运行你的 runnable 你可以使用这个

Handler handler = new Handler(Looper.getMainLooper());

这将为 UI 线程创建一个处理程序。

ClientPlayer extends Activity {
.
.
public static Handler UIHandler;

static 
{
    UIHandler = new Handler(Looper.getMainLooper());
}
public static void runOnUI(Runnable runnable) {
    UIHandler.post(runnable);
}
.
.
.
}

现在你可以在任何地方使用它。

@Override
public void run() {
   // I tried both ClientPlayer.runOnUiThread and LotteryServer.runOnUiThread
   // both don't work   
    ClientPlayer.runOnUI(new Runnable() {
        public void run() {
           Toast.makeText(getApplicationContext(), "from inside thread", Toast.LENGTH_SHORT).show();
        }
    });
} // end run method

关于android - 如何在不出现 "cannot make a static reference to the non static method"编译器错误的情况下使用 runOnUiThread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14996560/

相关文章:

Android SQLite 不同的选择?

android - 实现 Parcelable 接口(interface)时如何读/写 bool 值?

android - 如何在编辑模式下扩充布局?

c - C 中的线程安全与原子性

c++ - 用 Poco :Condition 唤醒两个线程

c# - 在另一个线程上创建 WPF 进度窗口

c++ - std::thread 线程什么时候执行?

android - 如何将 appium 与机器人框架集成?

android, NumberPicker 越界

java - 如何让一个线程加入另一个线程但只等待 n 秒的 CPU 时间?