如何在Android的AsyncTask中返回布林值?


介紹

AsyncTask是Android中用於執行一些後臺長時間執行任務的類,例如從網際網路後臺載入影像。如果影像尺寸很大,則可以使用Android中的AsyncTask將影像作為後臺任務從網際網路載入。本文將介紹如何在Android的AsyncTask中返回布林值。

實現

我們將建立一個簡單的應用程式,其中我們將顯示一個用於應用程式標題的TextView。然後,我們建立另一個TextView,用於顯示任務正在執行或已停止。之後,我們將建立一個用於啟動任務的按鈕。

步驟1:在Android Studio中建立一個新專案

導航到Android Studio,如下面的螢幕所示。在下面的螢幕中,單擊“新建專案”以建立一個新的Android Studio專案。

單擊“新建專案”後,您將看到下面的螢幕。

在這個螢幕中,我們只需選擇“空活動”,然後單擊“下一步”。單擊“下一步”後,您將看到下面的螢幕。

在這個螢幕中,我們只需指定專案名稱。然後包名將自動生成。

注意 - 確保選擇Java作為語言。

指定所有詳細資訊後,單擊“完成”以建立一個新的Android Studio專案。

專案建立完成後,我們將看到開啟的兩個檔案,即activity_main.xml和MainActivity.java檔案。

步驟2:使用activity_main.xml

導航到activity_main.xml。如果此檔案不可見,則要開啟此檔案。在左側窗格中,導航到app>res>layout>activity_main.xml以開啟此檔案。開啟此檔案後,向其中新增以下程式碼。程式碼中添加了註釋以詳細瞭解。

<?xml version="1.0" encoding="utf-8"?>
<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"
   android:orientation="vertical"
   tools:context=".MainActivity">

   <!-- on below line creating a text view for heading -->
   <TextView
       android:id="@+id/idTVHeading"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_centerInParent="true"
       android:layout_margin="5dp"
       android:padding="4dp"
       android:text="Returning Boolean from Async Task in Android"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="20sp"
       android:textStyle="bold" />

   <!-- on below line creating a text view for displaying a message -->
   <TextView
       android:id="@+id/idTVMsg"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVHeading"
       android:layout_margin="5dp"
       android:padding="4dp"
       android:text="Message"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="18sp" />

   <!-- on below line creating a button to start out task -->
   <Button
       android:id="@+id/idBtnStartAsyncTask"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVMsg"
       android:layout_margin="20dp"
       android:text="Start Asnync Task"
       android:textAllCaps="false"
       android:textColor="@color/white" />
</RelativeLayout>

說明:在上面的程式碼中,我們建立了一個根佈局作為相對佈局。在這個佈局中,我們建立了一個TextView,用於顯示應用程式的標題。之後,我們建立了另一個TextView,用於顯示我們正在應用程式中執行的當前任務狀態。之後,我們建立了一個按鈕,我們將使用它來啟動任務,任務將執行最多5秒,然後終止。

步驟3:使用MainActivity.java檔案

導航到MainActivity.java。如果此檔案不可見,則要開啟此檔案。在左側窗格中,導航到app>res>layout>MainActivity.java以開啟此檔案。開啟此檔案後,向其中新增以下程式碼。程式碼中添加了註釋以詳細瞭解。

package com.example.java_test_application;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {

   // creating variables for button and text view.
   private TextView msgTV;
   private Button asyncTaskBtn;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       //initializing variable for text view and button on below line.
       msgTV = findViewById(R.id.idTVMsg);
       asyncTaskBtn = findViewById(R.id.idBtnStartAsyncTask);

       //  adding on click listner for button on below line.
       asyncTaskBtn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
        // on below line calling our async task manage class
               AsyncTaskManage asyncTaskManage = new AsyncTaskManage();
               // on below line calling execute method to execute it.
               asyncTaskManage.execute("");
           }
       });
   }
   // on below line creating async task manage class.
   private class AsyncTaskManage extends AsyncTask {

       // on below line creating do in background method.
       @Override
       protected Boolean doInBackground(String... strings) {
           // on below line running try and catch block.
           try {
               // on below line sleeping the app by calling sleep method.
               Thread.sleep(3000);
               // on below line returning as false.
               return false;
               // on below line doing exception handling.
           } catch (Exception e) {
               e.printStackTrace();
           }
           // on below line returning as true.
           return true;
       }
       // on below line creating a post execute method.
       @Override
       protected void onPostExecute(Boolean aBoolean) {
           super.onPostExecute(aBoolean);
           // on below line checking if boolean is true or false.
           if (aBoolean) {
               // on below line setting text message as task running.
               msgTV.setText("Task is running..");
           } else {
               // on below line setting message as task stopped.
               msgTV.setText("Task is stopped..");
           }
       }
   }
}

說明:在上面的程式碼中,我們首先為TextView和按鈕建立變數。現在我們將看到onCreate方法。這是每個Android應用程式的預設方法。當建立應用程式檢視時,將呼叫此方法。在此方法中,我們設定contentView,即名為activity_main.xml的佈局檔案,以設定來自該檔案UI。在onCreate方法中,我們使用我們在activity_main.xml檔案中給出的id來初始化TextView和按鈕變數。之後,我們為按鈕新增一個點選監聽器。在點選監聽器方法中,我們呼叫非同步任務並呼叫execute方法來執行它。之後,我們建立一個名為AsyncTaskManage的類並將其擴充套件為AsyncTask。在這個類中,我們建立一個在後臺執行的方法。在此方法中,我們將任務休眠5秒,在這種情況下,我們返回布林值false,之後對於預設情況,我們返回true。現在,我們建立另一個方法作為onPostExecute。在此方法中,我們檢查從後臺執行方法返回的布林值。如果布林值為true,我們將在TextView中指定訊息為“任務正在執行”,如果布林值為false,則我們在TextView中指定訊息為“任務已停止”。

新增上述程式碼後,我們只需單擊頂部欄中的綠色圖示即可在移動裝置上執行我們的應用程式。

注意 - 確保已連線到您的真實裝置或模擬器。

輸出

結論

在本文中,我們介紹瞭如何在Android的AsyncTask中返回布林值。

更新於:2023年5月8日

469 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告