Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone



Clound SSD Virtual Server

Android Thread and Handler

Android Thread and Handler สำหรับ Thread ในภาษา Java ที่ใช้สำหรับการพัฒนาโปรแกรมบน Android จะเป็นการจัดการกับ Process ที่มีมากกว่า 1 Process โดยการทำงานของแต่ล่ะ Thread นั้นจะแยกการทำงานกันอย่าสิ้นเชิง ทั้งทรัพยากรหรือตัวแปรที่ถูกสร้างในของแต่ล่ะ Thread ก็จะไม่เกี่ยวข้องกันได้ การทำงานของ Thread จะอยู่ในรูปแบบของ Background Process นั่นหมายถึงว่าเมื่อสั่งให้ Thread ทำงาน Process ของ Thread นั้น ๆ จะทำงานจนเสร็จสิ้น แม้ว่า Thread อื่น ๆ จะถุกให้ส่งทำงานพร้อม ๆ กับ Thread นั้น ๆ ก็จะไม่เกี่ยวข้องกัน และแต่ล่ะ Thread ก็จะทำงานของตัวเองจนเสร็จสิ้น

Thread and Android
หลายคนอาจจะสงสัยว่าแล้ว Thread จะมีประโยชน์อย่างไรกับการเขียนโปรแกรมบน Android จะยกตัวอย่างง่าย ๆ ให้เช่น ถ้าเราเคยใช้โปรแกรมพวก LINE ซึ่งเป็นโปรแกรม Chat เราจะเห็นว่าในคราวเดียวกัน เราสามารถคุยกับเพื่อน ๆ ได้หลายหน้าจอ และเมื่อเราคลิกดาวน์โหลดหลาย ๆ ไฟล์ที่ถูกส่งมาให้ จะเห็นว่าเราสามารถคลิกดาวน์โหลดได้หลาย ๆ รายการในคราวเดียวกัน ซึ่ง Process เหล่านี้ล้วนแต่ใช้ Thread เข้ามาจัดการทำงานทั้งสิ้น

Android Thread and Handler


จากภาพตัวอย่างจะเห็นว่าใน ListView จะมีข้อมูลอยู่หลายรายการ และใน ListView สามารถสั่งให้โปรแกรมทำงาน ได้พร้อม ๆ กัน ดูตัวอย่างเพิ่มเติมได้ที่

Android Multiple Download file in ListView and Show Progress unit percentage


และในการเขียนโปรแกรมเพื่อทำงานบน Thread การที่จะเขียนหรือแทรกคำสั่งต่าง ๆ ระหว่างที่ Thread ทำงานอยู่นั้น จะต้องใช้ Handler เข้ามาจัดการเพื่อให้ Thread สามารถเรียก Method อื่น ๆ ได้ (ไม่สามารถแทรกคำสั่งเรียก Method โดยตรงใน Thread ได้)

Thread Syntax
		Runnable runnable = new Runnable() {

			public void run() {

					handler.post(new Runnable() {
						public void run() {
							// Handler thread
							 // Call method()

						}
					});
			}
		};
		new Thread(runnable).start();

ตัวอย่างการสร้าง Method ขื่อว่า runnable ซึ่งทำงานแบบ Thread



Example การสร้าง Thread และแสดง Thread ทำงานในแต่ล่ะ Thread

โครงสร้างของไฟล์ประกอบด้วย 2 ไฟล์คือ MainActivity.java, activity_main.xml

Android Thread and Handler

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="39dp" >
        <RadioButton
            android:id="@+id/rdo1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="Red" />

        <RadioButton
            android:id="@+id/rdo2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Blue" />

        <RadioButton
            android:id="@+id/rdo3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Green" />

    </RadioGroup>

    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/radioGroup1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:text="Run Thread" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:text="Select Thread"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/txtResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button1"
        android:layout_marginTop="14dp"
        android:text="Result" />

</RelativeLayout>









MainActivity.java
package com.myapp;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.text.Html;
import android.view.Menu;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Button;
import android.graphics.*;

public class MainActivity extends Activity {

	private Handler handler = new Handler();
	RadioButton rdo1;
	RadioButton rdo2;
	RadioButton rdo3;
	TextView result;

	String resultOut = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// rdo1 Red
		rdo1 = (RadioButton) findViewById(R.id.rdo1);
		rdo1.setTextColor(Color.RED);
		// rdo2 Blue
		rdo2 = (RadioButton) findViewById(R.id.rdo2);
		rdo2.setTextColor(Color.BLUE);
		// rdo3 Blue
		rdo3 = (RadioButton) findViewById(R.id.rdo3);
		rdo3.setTextColor(Color.GREEN);

		// txtResult
		result = (TextView) findViewById(R.id.txtResult);

		// button1
		Button btn = (Button) findViewById(R.id.button1);
		btn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// Perform action on click
				if (rdo1.isChecked()) {
					startProgress("RED");
				} else if (rdo2.isChecked()) {
					startProgress("BLUE");
				} else if (rdo3.isChecked()) {
					startProgress("GREEN");
				}
			}
		});

	}

	public void startProgress(final String color) {

		Runnable runnable = new Runnable() {

			public void run() {

				final String threadColor = color;

				for (int i = 0; i <= 10; i++) {
					final int value = i;
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					handler.post(new Runnable() {
						public void run() {
							// Handler thread
							String curThread = "<br><font color='"
									+ threadColor.toString() + "'>Thread <b>"
									+ threadColor.toString() + "</b>"
									+ ": Process i=" + value + "</font>";
							resultOut = resultOut + curThread;
							result.setText(Html.fromHtml(resultOut));
						}
					});
				}
			}
		};
		new Thread(runnable).start();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}


Screenshot

Android Thread and Handler

สร้าง Application บน Android ประกอบด้วย Radio 3 ตัว ซึ่งแสดงสี Red, Blue และ Green

Android Thread and Handler

ทดสอบให้คลิกดังนี้
- Red -> Run Thread
- Blue -> Run Thread
- Green -> Run Thread









คำอธิบาย

				for (int i = 0; i <= 10; i++) {
					final int value = i;
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					handler.post(new Runnable() {
						public void run() {
							// Handler thread
							String curThread = "<br><font color='"
									+ threadColor.toString() + "'>Thread <b>"
									+ threadColor.toString() + "</b>"
									+ ": Process i=" + value + "</font>";
							resultOut = resultOut + curThread;
							result.setText(Html.fromHtml(resultOut));
						}
					});
				}

และจาก Code ของ Java จะเห็นว่าในแต่ล่ะ Thread จะ Loop ข้อมูลจาก 0-10 โดยในแต่ล่ะ Loop จะ Sleep หรือหยุดประมาณ 2 วินาที ดังนั้นในข้างต้นเราได้คลิก Thread 3 ครั้ง ซึ่งจะเกิด Thread 3 รายการ จึงได้ผลลัพธ์ดังภาพ ซึ่งแต่ล่ะ Thread จะทงำนของตัวเองจนเสร็จสิ้น

   
Share


ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท


ลองใช้ค้นหาข้อมูล


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2012-07-05 22:44:50 / 2017-03-26 22:59:44
  Download : No files
 Sponsored Links / Related

 
Android and Collections Set
Rating :

 
Android and Timer (Java)
Rating :

 
Android and TimerTask (Java)
Rating :

 
Android and Count Down (CountDownTimer)
Rating :


ThaiCreate.Com Forum


Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   







Load balance : Server 01
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่