Android – playing with separate threads

© shho@sxc.hu

This time, I played a little with Threads and I tried to implement somekind of simple-test separate thread and start it inside main activity and also return results from separate Thread so it can be used to update UI for example.

As you probably know, I am not officialy android nor java developer so, please don’t take this post bad if something is maybe not explained as you expected to be. I am still playing with android source code and trying to transfer my own understanding and opinion here on this blog that will maybe help someone…

This is how my activity looks like:

package com.inchoo.tutorial;
 
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
 
public class AndroidservicetutorialActivity extends Activity {
 
	final Handler mHandler = new Handler();
 
	private String mResult;
 
	// Create runnable for posting
	final Runnable mUpdateResults = new Runnable() {
		public void run() {
			Log.d("Inchoo tutorial", mResult);
		}
	};
 
	protected void startTestThread() {
		Thread t = new Thread() {
			public void run() {
 
				Log.d("Inchoo tutorial", "My thread is running");
				mResult = "This is my new result";
				mHandler.post(mUpdateResults);
			}
		};
 
		t.start();
	}
 
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
 
		startTestThread();
	}
 
}

Let me try to explain this code.

When out activity starts (onCreate), we are starting a new thread with function startTestThread.
That function should execute something and get some results.
When we have results, we are starting our defined mUpdateResults runnable by posting it to message queue of main (activity’s thread). It gets value of mResult variable in order to update something with given data.
This is a simple example of running different threads and comunicating between them.
I hop this post will help someone to better understand given logic.

Cheers. 🙂

You made it all the way down here so you must have enjoyed this post! You may also like:

Aug 29, 2017

Adding gallery tab to a CMS page

/ Leave a comment
Jan 17, 2017

Implementing javascript minifier

/ Leave a comment
Mar 16, 2016

Changing default category sort direction in Magento

/ Leave a comment

5 comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.