Threading Example in Android

AndroidMultithreading

Android Problem Overview


I want some simple example on thread creation and invoking of threads in android.

Android Solutions


Solution 1 - Android

Solution 2 - Android

One of Androids powerful feature is the AsyncTask class.

To work with it, you have to first extend it and override doInBackground(...). doInBackground automatically executes on a worker thread, and you can add some listeners on the UI Thread to get notified about status update, those functions are called: onPreExecute(), onPostExecute() and onProgressUpdate()

You can find a example here.

Refer to below post for other alternatives:

https://stackoverflow.com/questions/6964011/handler-vs-asynctask-vs-thread

Solution 3 - Android

Here is a simple threading example for Android. It's very basic but it should help you to get a perspective.

Android code - Main.java

package test12.tt;

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

public class Test12Activity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    	final TextView txt1 = (TextView) findViewById(R.id.sm);

        new Thread(new Runnable() { 
        	public void run(){        
		    txt1.setText("Thread!!");
           	}
	    }).start();
        
    }    
}

Android application xml - main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView  
    android:id = "@+id/sm"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"/>

</LinearLayout>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionramView Question on Stackoverflow
Solution 1 - AndroidRoflcoptrExceptionView Answer on Stackoverflow
Solution 2 - AndroidEndian OginoView Answer on Stackoverflow
Solution 3 - AndroidmbejdaView Answer on Stackoverflow