Vous êtes sur la page 1sur 14

News

Knowledge Base

ANDROID

Deals

CORE JAVA

Job Board

About

DESKTOP JAVA

ENTERPRISE JAVA

JAVA BASICS

JVM LANGUAGES

SOFTWARE DEVELOPMENT

Home Android core Thread Android Thread Example

ABOUT NIKOS MARAVITSAS


Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens.
During his studies he discovered his interests about software development and he has successfully completed numerous assignments in
a variety of fields. Currently, his main interests are systems security, parallel systems, artificial intelligence, operating systems, system
programming, telecommunications, web applications, human machine interaction and mobile development.

Android Thread Example


Posted by: Nikos Maravitsas in Thread May 19th, 2013

In this example we are going to see how to use Android


Thread

. As we read from the official documentation:


A
Thread

is a concurrent unit of execution. It has its own call stack for methods being invoked, their arguments and local variables. Each virtual
machine instance has at least one main

Search...

NEWSLETTER

DEVOPS

Thread

running when it is started; typically, there are several others for housekeeping. The
application might decide to launch additional
Thread

s for specific purposes.


Thread

s in the same VM interact and synchronize by the use of shared objects and monitors
associated with these objects. Synchronized methods and part of the API in
Object

also allow

NEWSLETTER

162030 insiders are already enjoying


weekly updates and complimentary
whitepapers!

Join them now to gain exclusive


access to the latest news in the Java

world, as well as insights about Android,


Scala, Groovy and other related technologies.

Email address:
Your email address

Sign up

Thread

s to cooperate.
There are basically two main ways of having a
Thread

execute application code. One is providing a new class that extends


Thread

and overriding its


run()

method. The other is providing a new


Thread

instance with a
Runnable

object during its creation. In both cases, the


start()

method must be called to actually execute the new


Thread

JOIN US
With 1,240,600 monthly
unique visitors and over
500 authors we are
placed among the top Java
related sites around.
Constantly being on the
lookout for partners; we
encourage you to join us.
So If you have a blog with
unique and interesting
content then you should check out our JCG
partners program. You can also be a guest writer
for Java Code Geeks and hone your writing skills!

.
Each
Thread

has an integer priority that basically determines the amount of CPU time the
Thread

gets. It can be set using the


setPriority(int)

method. A
Thread

can also be made a daemon, which makes it run in the background. The latter also affects VM termination behavior: the VM does not
terminate automatically as long as there are non-daemon threads running.
For this tutorial, we will use the following tools in a Windows 64-bit platform:
JDK 1.7
Eclipse 4.2 Juno
Android SKD 4.2

1. Create a new Android Project


Open Eclipse IDE and go to File -> New -> Project -> Android -> Android Application Project.You have to specify the Application Name, the
Project Name and the Package name in the appropriate text fields and then click Next.

CAREER OPPORTUNITIES
REMOTE Senior Java DeveloperABC Financial
Services Inc
Remote
Apr, 04
Software Engineer - Java Developer - Entry
LevelFICO
San Jose, CA
Apr, 18
Programmer/Analyst IIIUCLA
Los Angeles, CA
Apr, 22
Software Development EngineerIntel

Hillsboro, OR
Apr, 14
Software Development EngineerIntel
Plano, TX
Apr, 20
Software Development EngineerIntel
Santa Clara, CA
Apr, 12
Google for Work, Software EngineerGoogle
Mountain View, CA
Apr, 21
Programmer Analyst, SeniorPacific Gas & Electric
San Ramon, CA
Apr, 15
Senior/Lead Backend Developer - Boston,
MARaizlabs Corporation
Boston, MA
Apr, 21
Senior Data Platform Site Reliability EngineerTesla
Motors
Palo Alto, CA
Apr, 20
1
2
...
7025

Freelance

In the next window make sure the Create activity option is selected in order to create a new activity for your project, and click Next. This is
optional as you can create a new activity after creating the project, but you can do it all in one step.

Keyword ...

Full-time

Location ...

Intership

Country ...

Part-time
All

Filter Results
jobs by

Select BlankActivity and click Next.

You will be asked to specify some information about the new activity. In the Layout Name text field you have to specify the name of the file
that will contain the layout description of your app. In our case the file
res/layout/main.xml

will be created. Then, click Finish.

2. Create the main layout of the Application


Open
res/layout/main.xml

file :

And paste the following code :


01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:max="10"
android:padding="4dip" >
</ProgressBar>

<Button
android:id="@+id/button1"
android:layout_width="match_parent"

19
20
21
22
23
24

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="startProgress"
android:text="Start" />

</LinearLayout>

Now you may open the Graphical layout editor to preview the User Interface you created:

3. Code
Now we have to write the code of the application. Use the Package Explorer to navigate to the Java file of the Activity youve created:

The code of this tutorial is pretty much selfexplanatory. The interesting part is how to update the value of the Progress bar. We are going to
use a
Thread

to run the backgroud process that updates tha value of the progress bar. Although this example works fine, it is strongly advised to use a
Handler or an AsyncTask to explicity bind the backroud thread with the UI thread.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

package com.javacodegeeks.android.androidthreadexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;

public class MainActivity extends Activity {


private ProgressBar bar;

/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bar = (ProgressBar) findViewById(R.id.progressBar1);

public void startProgress(View view) {

bar.setProgress(0);
new Thread(new Task()).start();
}

26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

class Task implements Runnable {


@Override
public void run() {
for (int i = 0; i <= 10; i++) {
final int value = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
bar.setProgress(value);

}
}

4. Run the application


This is the main screen of our Application.

Now, when you press the Start button,the thread that updates the bars value :

Download Eclipse Project


This was an Android Thread Example. Download the Eclipse Project of this tutorial:AndroidThreadExample

Do you want to know how to develop your skillset to become a Java


Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide


3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design

and many more ....

Email address:
Your email address

Sign up

KNOWLEDGE BASE

HALL OF FAME

Courses

Android Alert Dialog Example

News

Android OnClickListener Example

Resources

How to convert Character to String and a


String to Character Array in Java

Tutorials
Whitepapers

Java Inheritance example


Java write to File Example

ABOUT JAVA CODE GEEKS


JCGs (Java Code Geeks) is an independent online community focused on creating the
ultimate Java to Java developers resource center; targeted at the technical architect,
technical team lead (senior developer), project manager and junior developers alike.
JCGs serve the Java, SOA, Agile and Telecom communities with daily news written by
domain experts, articles, tutorials, reviews, announcements, code snippets and open
source projects.

DISCLAIMER
All trademarks and registered trademarks appearing on Java Code Geeks are the
property of their respective owners. Java is a trademark or registered trademark of

THE CODE GEEKS NETWORK


.NET Code Geeks
Java Code Geeks
System Code Geeks

java.io.FileNotFoundException How to
solve File Not Found Exception

property of their respective owners. Java is a trademark or registered trademark of


Oracle Corporation in the United States and other countries. Examples Java Code Geeks
is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

java.lang.arrayindexoutofboundsexception
How to handle Array Index Out Of
Bounds Exception
java.lang.NoClassDefFoundError How
to solve No Class Def Found Error

Web Code Geeks


JSON Example With Jersey + Jackson
Spring JdbcTemplate Example

Examples Java Code Geeks and all content copyright 2010-2016, Exelixis Media P.C. | Terms of Use | Privacy Policy | Contact