How to use runOnUiThread without getting a compiler error "I can not make a static link to a non-stationary method"

I have a main class;

ClientPlayer extends Activity { 

and services

  LotteryServer extends Service implements Runnable { 

when I try to use RunOnUiThread in the method of starting this service, I get a compiler error, "I can not statically refer to the non-stationary method"

how to fix it ?, how i use the code 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 
+7
source share
4 answers

runOnUiThread is not a static method.

If you want to run runnable in UIThread, you can use this

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

This will create a handler for the user interface thread.

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

Now you can use it 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 
+14
source

There is a very simple solution to this problem, just make a static link to your activity before your onCreat() method

 MainActivity mn; 

then initialize it in your onCreat() method like this

 mn=MainActivity.this; 

and after that you just need to use it to call runOnUiThread

 mn.runOnUiThread(new Runnable() { public void run() { tv.setText(fns);///do what } }); 

hope this works.

+12
source

You can get a copy of your activity, pass it to the service, and use it instead of the class name.

then you can use:

 yourActivity.runOnUiThread( ... 
+5
source

We usually use this method (RunOnUiThread) when we try to update our user interface from a workflow. but since you use the Service here, runOnMainThread seems inappropriate according to your situation.

Better use Handler here. A handler is an element associated with the created thread, you can send a runnable with your code to the handler, and this runnable will be executed in the thread where the Handler was created.

Create a handler on your service in your MainThread and publish Runnables on he / sends him messages.

0
source

All Articles