Computer >> 컴퓨터 >  >> 프로그램 작성 >> Android

Android에서 runOnUiThread를 어떻게 사용합니까?

<시간/>

예제를 시작하기 전에 Android에서 runOnUiThread()가 무엇인지 알아야 합니다. 때때로 메인 스레드는 무거운 작업을 수행합니다. 사용자가 UI에 몇 가지 추가 작업을 추가하려는 경우 로드되고 ANR을 제공합니다. runOnUiThread를 사용하면 작업자 스레드에서 백그라운드 작업을 수행하고 메인 스레드에서 결과를 업데이트합니다.

이 예는 Android에서 runOnUiThread를 사용하는 방법을 보여줍니다.

1단계 − Android Studio에서 새 프로젝트를 생성하고 파일 ⇒ 새 프로젝트로 이동하여 필요한 모든 세부 정보를 입력하여 새 프로젝트를 생성합니다.

2단계 − res/layout/activity_main.xml에 다음 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
   android:id="@+id/parent"
   xmlns:tools="https://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity"
   android:gravity="center"
   android:orientation="vertical">
   <Button
      android:id="@+id/runOn"
      android:text="Run"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
   <TextView
      android:id="@+id/text"
      android:textSize="20sp"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
</LinearLayout>

위의 코드에서는 하나의 버튼과 텍스트 보기를 사용했으며 버튼을 클릭하면 텍스트 보기가 업데이트됩니다.

3단계 − src/MainActivity.java

에 다음 코드 추가
package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
   int i = 0;
   @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      final TextView textView = findViewById(R.id.text);
      final Button runOn = findViewById(R.id.runOn);
      runOn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            new Thread() {
               public void run() {
                  while (i++ < 1000) {
                     try {
                        runOnUiThread(new Runnable() {
                           @Override
                           public void run() {
                              textView.setText("#" + i);
                           }
                        });
                        Thread.sleep(300);
                     } catch (InterruptedException e) {
                        e.printStackTrace();
                     }
                  }
               }
            }.start();
         }
      });
   }
}

위의 코드에서 사용자가 버튼을 클릭할 때. 아래와 같이 runOnUiThread()를 사용하여 텍스트 보기를 업데이트합니다. -

new Thread() {
   public void run() {
      while (i++ < 1000) {
         try {
            runOnUiThread(new Runnable() {
               @Override
               public void run() {
                  textView.setText("#" + i);
               }
            });
            Thread.sleep(300);
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
   }
}.start();

응용 프로그램을 실행해 보겠습니다. 실제 Android 모바일 장치를 컴퓨터에 연결했다고 가정합니다. Android 스튜디오에서 앱을 실행하려면 프로젝트의 활동 파일 중 하나를 열고 도구 모음에서 실행 아이콘을 클릭합니다. 모바일 장치를 옵션으로 선택한 다음 기본 화면을 표시할 모바일 장치를 확인하십시오 -

Android에서 runOnUiThread를 어떻게 사용합니까?

위의 결과에서는 초기화면을 보여주었다. 사용자가 실행 버튼을 클릭하면 아래와 같이 텍스트 보기가 업데이트됩니다. -

Android에서 runOnUiThread를 어떻게 사용합니까?