Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách kiểm tra thread hiện tại có bị ngắt (interrupted) trong Android

Giới thiệu

Phương thức isInterrupted() kiểm tra cờ ngắt của thread. Ví dụ này kiểm tra thread chính.

Bước 1: Tạo project mới

Android Studio → File → New Project.

Bước 2: Giao diện (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>

Bước 3: MainActivity.java

package com.example.myapplication;

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);
        // Kiểm tra thread hiện tại có bị interrupt không
        textView.setText("Thread bị ngắt? " + Thread.currentThread().isInterrupted());
    }
}

Chạy ứng dụng

Kết quả: "false" vì thread chính không bị ngắt.

Cách kiểm tra thread hiện tại có bị ngắt (interrupted) trong Android