如何在不获取“无法对非静态方法进行静态引用"的情况下使用runOnUiThread;编译器错误 [英] how to use runOnUiThread without getting "cannot make a static reference to the non static method" compiler error
问题描述
我有一个主要班级;
ClientPlayer extends Activity {
和一项服务
LotteryServer extends Service implements Runnable {
当尝试在此服务的run方法中使用RunOnUiThread时,出现编译器错误,无法对非静态方法进行静态引用"
when trying to use the RunOnUiThread in the run method of this service I am getting compiler error of, "cannot make a static reference to the non static method"
如何解决此问题?,此处显示了我如何使用代码;
how to fix this?, how I am using the code is shown here;
@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不是静态方法.
runOnUiThread is not a static method.
如果您想在UIThread上运行您的可运行对象,则可以使用此
If u want to run your runnable on UIThread You can use this
Handler handler = new Handler(Looper.getMainLooper());
Handler handler = new Handler(Looper.getMainLooper());
这将为UI线程创建一个处理程序.
This will create a handler for UI Thread.
ClientPlayer extends Activity {
.
.
public static Handler UIHandler;
static
{
UIHandler = new Handler(Looper.getMainLooper());
}
public static void runOnUI(Runnable runnable) {
UIHandler.post(runnable);
}
.
.
.
}
现在您可以在任何地方使用它了.
Now u can use this anywhere.
@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
这篇关于如何在不获取“无法对非静态方法进行静态引用"的情况下使用runOnUiThread;编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!