如何在Android中获取当前线程是否中断?
在进入示例之前,我们应该了解什么是线程。线程是一个轻量级的子进程,它将在后台执行操作,而不会中断UI。本示例演示如何在Android中获取当前线程是否中断。
步骤1 − 在Android Studio中创建一个新项目,转到文件 ⇒ 新建项目,并填写所有必需的详细信息以创建一个新项目。
步骤2 − 将以下代码添加到res/layout/activity_main.xml。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" 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。它包含有关当前线程是否中断的信息。
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);
textView.setText("Current thread: " + Thread.currentThread().isInterrupted());
}
}让我们尝试运行您的应用程序。我假设您已将您的实际Android移动设备连接到您的计算机。要从Android Studio运行应用程序,请打开您的项目中的一个activity文件,然后点击运行
工具栏中的图标。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕 −

在上面的结果中,它返回false,因为当前线程未中断。
点击 这里 下载项目代码
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP