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

วิธีตรวจสอบว่าเธรดปัจจุบันถูก Interrupt หรือไม่ใน Android

ก่อนจะเริ่มตัวอย่าง เราควรเข้าใจก่อนว่า Thread คืออะไร Thread เป็นกระบวนการย่อยที่มีน้ำหนักเบา ทำงานเบื้องหลังโดยไม่รบกวน UI ตัวอย่างนี้สาธิตวิธีการตรวจสอบว่าเธรดปัจจุบันถูก Interrupt หรือไม่ใน Android

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

เปิด Android Studio ไปที่ File → New Project แล้วกรอกรายละเอียดที่จำเป็นเพื่อสร้างโปรเจกต์ใหม่

ขั้นตอนที่ 2: ออกแบบหน้าจอ (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_marginTop="100dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

ในโค้ดด้านบน เราใช้ TextView เพื่อแสดงสถานะการ Interrupt ของเธรดปัจจุบัน

ขั้นตอนที่ 3: เขียนโค้ด MainActivity.java

package com.example.myapplication;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView textView;

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

        textView = findViewById(R.id.text);
        // ตรวจสอบว่าเธรดปัจจุบันถูก interrupt หรือไม่
        textView.setText("Current thread: " + Thread.currentThread().isInterrupted());
    }
}

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

เชื่อมต่ออุปกรณ์ Android จริงกับคอมพิวเตอร์ ใน Android Studio เปิดไฟล์ Activity และคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณ แล้วตรวจสอบหน้าจอเริ่มต้น

วิธีตรวจสอบว่าเธรดปัจจุบันถูก Interrupt หรือไม่ใน Android

ผลลัพธ์จะคืนค่า false เนื่องจากเธรดปัจจุบัน (main thread) ไม่ได้ถูก interrupt