Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีรัน Thread ต่อเนื่อง (Continuous Thread) ใน Android


ความรู้พื้นฐาน: Thread ใน Android

Thread เป็นงานประมวลผลทั่วไปที่ทำได้หลายอย่าง แต่มีข้อจำกัด 1 ข้อคือ ไม่สามารถอัปเดต UI ได้โดยตรง

ตัวอย่าง: การรัน Thread ต่อเนื่อง

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio ไปที่ File → New Project แล้วกรอกรายละเอียดที่จำเป็น

ขั้นตอนที่ 2: จัดการ Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Thread ต่อเนื่อง"
        android:textSize="25sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

มี TextView เมื่อคลิกจะเริ่ม Thread ต่อเนื่องและพิมพ์ผลลัพธ์ใน Logcat

ขั้นตอนที่ 3: เขียนโค้ด Java (src/MainActivity.java)

package com.example.andy.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = findViewById(R.id.text);
        text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (true) {
                            Log.d("Continuous Thread", "Tutorialspoint.com");
                        }
                    }
                }).start();
            }
        });
    }
}

การทดสอบแอปพลิเคชัน

เชื่อมต่ออุปกรณ์ Android จริง ใน Android Studio คลิกไอคอน Run เลือกอุปกรณ์ แล้วตรวจสอบหน้าจอ

วิธีรัน Thread ต่อเนื่อง (Continuous Thread) ใน Android

คลิก TextView จะรัน Thread ต่อเนื่อง ตรวจสอบ Logcat จะเห็นข้อความพิมพ์ซ้ำ:

วิธีรัน Thread ต่อเนื่อง (Continuous Thread) ใน Android