我有一个主类;
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/