how to use runnable in android

android runnable vs thread
android background thread example
post runnable android
android handler example
runnable java
android thread tutorial
implement runnable android
android ui thread

Hi, I'm newbie in Java Android development and I want to know how to use Runnable in Android. It doesn't seem to be working for me. Here is my source code:

MainTest.java

package com.heeere.androiddnssd.discovery;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainTest extends Activity {

    android.net.wifi.WifiManager.MulticastLock lock;
    private Discovery discovery = new Discovery(this); 
    private TextView textView;

    /** Called when the activity is first created. */
    @SuppressLint("NewApi") @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView = (TextView)this.findViewById(R.id.text);

        android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) getSystemService(android.content.Context.WIFI_SERVICE);
        lock = wifi.createMulticastLock("mylockthereturn");
        lock.setReferenceCounted(true);
        lock.acquire();

    }

    public void updateView () {
        String msg = discovery.getMsg();
        textView.setText(msg);
    }

    @SuppressLint("NewApi") @Override
    protected void onStop() {
        discovery.stop();
        lock.release();
        super.onStop();
    }


}

Discovery.java

package com.heeere.androiddnssd.discovery;

import java.io.IOException;

import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceListener;

public class Discovery {


    private String type = "_ikunet._tcp.local.";
    private String msg="";
    private JmDNS jmdns = null;
    private ServiceListener listener = null;
    private MainTest maintest;
    android.os.Handler handler = new android.os.Handler();

    public Discovery (MainTest maintest) {
        this.maintest = maintest;
        setUp();
    }

    private void setUp() {

        try {
            jmdns = JmDNS.create();
            jmdns.addServiceListener(type, listener = new ServiceListener() {

                public void serviceResolved(ServiceEvent ev) {
                    msg = msg + ev.getInfo().getName()+ "\n";
                    update();
                }

                public void serviceRemoved(ServiceEvent ev) {
                }

                public void serviceAdded(ServiceEvent event) {
                    jmdns.requestServiceInfo(event.getType(), event.getName(), 1);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }

    public String getMsg() {
        return msg;
    }

    private void update() {
        handler.postDelayed(new Runnable() {
            public void run() {
                maintest.updateView();
            }
        }, 1);
    }


    public void stop() {
        if (jmdns != null) {
            if (listener != null) {
                jmdns.removeServiceListener(type, listener);
                listener = null;
            }
            jmdns.unregisterAllServices();
            try {
                jmdns.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            jmdns = null;
        }
    }

}

main.xml

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scroller"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent" 
              android:layout_height="fill_parent" 
              android:orientation="vertical"
              android:scrollbars="vertical"
              android:fadeScrollbars="true"
              android:isScrollContainer="true">
    <TextView  
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:text="Hello World, Android Discovery" />
    <TextView 
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello, I am a TextView" />
    <Button 
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello, I am a Button" />
    </LinearLayout>
</ScrollView>

The serviceResolved is executed from the Discovery class a while after the application starts and should update the textview (from MainTest class). But this does not happen. How do I fix this behaviour? I think it might be a Runnable problem.

You may skip using Runnable as it seems unnecessary in Discovery.java. For example:

private void update() {
    maintest.updateView();
}

However, in case you are using thread to gather search results then what you can do is to make use of runOnUiThread in your activity class (MainTest.java). For example:

public void updateView () {
    this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            String msg = discovery.getMsg();
            textView.setText(msg);
        }
    });
}

Specify the code to run on a thread, The simple fix to your example is : handler = new Handler(); final Runnable r = new Runnable() { public void run() { tv.append("Hello World"); handler. Android Platform. API level 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1. Manifest.permission. Manifest.permission_group. android.accessibilityservice. AccessibilityService.MagnificationController.OnMagnificationChangedListener. AccessibilityService.SoftKeyboardController.OnShowModeChangedListener.

try this

private void update() {
    final Runnable r = new Runnable() {
        public void run() {
            maintest.updateView();
            handler.postDelayed(this, 1000);
        }
    };
    handler.postDelayed(r, 1000);
}

But I would recommend you this:

private void update() {
new Thread() {
    public void run() {
        while (true) {
            runOnUiThread(new Runnable() {
                 @Override
                 public void run() {
                      maintest.updateView();
                 }
            });
            Thread.sleep(1000);
        } 
    }
}.start();
}

How to run a Runnable thread in Android at defined intervals , Being an Android developer, you should know about these basic but important So, the point is that you are only able to use a Message object or a Runnable  This guide shows you how to implement a Runnable class, which runs the code in its Runnable.run() method on a separate thread. You can also pass a Runnable to another object that can then attach it to a thread and run it.

Personally I would use the handler a bit differently.

To me the Handler should be created by the Activity and handed to your discovery class. This is better because you avoid "leaking" the entire Activity.

In the activity you would have

private final Handler mHandler = new Handler() 
{
    @Override
    public void handleMessage(Message msg)
    {
        switch (msg.what) 
        {
            case UPDATE_PROGRESS:                   
                handleUpdateProgress();
                break;               
        }
    }   
};

Then, if you need to post back to the activity you can use something like:

handlerFromActivity.obtainMessage(UPDATE_PROGRESS).sendToTarget();

Understanding of Thread, Handler, Looper, Message, Runnable and , Android handles all the UI operations and input events from one single thread which to perform background task like using the ThreadPools and Executor classes. A Handler allows you to send and process Message and Runnable objects  The Runnable interface is used extensively to execute code in Threads. The Runnable interface has one abstract method called run() : Normally you implement that method whenever your class implements Runnable interface. The method will then get called to start executing the active part of the class’ code.

It works :)

final Handler handler = new Handler();
handler.post(new Runnable() {
     @Override
     public void run() {
     /* ... */
     handler.postDelayed(this, 15000);
     }
});

Handler in Android - Ankit Sinhal, In this example we will take a look into the Runnable interface in Java, and how it can be used in association with the Thread class to create  Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached. So examples provided by @alex2k8, even though are working correctly, are not the same. In case, where Handler.post() is used, no new threads are created. You just post Runnable to the thread with Handler to be executed by EDT.

Java Runnable Example, Here is an example for using the runnable thread in a click event, while clicking the image will be loaded, as it will take time to load the image,  So, In general, You should always use Runnable object to create a thread. This method is more flexible. It allows your class to extend from any other class. Also, you can use anonymous class syntax and Java 8’s lambda expression with Runnable to make your code more concise.

How to run a Runnable thread or UI thread in , Learn how to create threads in Java using Thread class and Runnable interface. How to use Java 8's lambda expressions with Runnable. A Handler allows communicating back with UI thread from other background thread. This is useful in android as android doesn’t allow other threads to communicate directly with UI thread. A Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue.

Java Thread and Runnable Tutorial, What if you'd rather have your thread object extend some other class? In that case, you can create a class that implements the Runnable interface rather than  Android provides many ways of creating and managing threads, and third-party libraries exist to make that even easier. However, with so many options, choosing the right approach can be quite confusing. In this article, Toptal Freelance Software Engineer Eliran Goshen discusses some common scenarios in Android dev

Comments
  • Do you want to execute ur "serviceResolved" as background operation?
  • Just echoing what Ads said, it appears you are doing all work on the UI thread already, so no need to post back to the UI thread. However, it looks like you intended to do background/multithread work
  • the serviceResolved is automatically executed as Background by Jmdns package