Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드에서 LocalTime API 클래스를 활용해 현지 시간을 가져오는 방법

이 튜토리얼에서는 자바의 LocalTime API 클래스를 사용해 안드로이드 앱에서 기기의 현지 시간(현재 시각)을 가져와 화면에 표시하는 방법을 단계별로 알아봅니다.

1단계: 새 프로젝트 생성

Android Studio를 실행하고 File → New Project 메뉴로 이동한 뒤, 새 프로젝트 생성에 필요한 모든 정보를 입력해 프로젝트를 만듭니다.

2단계: 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Local Date"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

위 코드에서는 시간을 화면에 표시하기 위해 TextView 하나를 배치했습니다. ConstraintLayout의 중앙에 위치하도록 제약 조건을 설정했습니다.

3단계: MainActivity 코드 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다.

package com.example.myapplication;

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

import java.time.LocalTime;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = findViewById(R.id.date);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            LocalTime time = LocalTime.now();
            textView.setText(String.valueOf("Time " + time));
        }
    }
}

핵심 코드를 살펴보면, LocalTime.now() 메서드를 호출하면 기기의 현재 현지 시간을 손쉽게 얻을 수 있습니다. 다만 java.time 패키지는 Android 8.0(Oreo, API 26)부터 지원되므로, 하위 버전 호환성을 위해 Build.VERSION.SDK_INT로 OS 버전을 확인하는 조건문을 추가하는 것이 좋습니다.

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 스마트폰을 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 옵션 목록에서 본인의 모바일 기기를 선택하면, 연결된 기기 화면에 아래와 같은 결과가 표시됩니다.

안드로이드에서 LocalTime API 클래스를 활용해 현지 시간을 가져오는 방법

실행 결과를 보면 현재 시간이 시:분:초 단위까지 정확하게 표시되는 것을 확인할 수 있습니다. 이처럼 LocalTime 클래스를 활용하면 별도의 포맷 변환 없이도 간단하게 현지 시간을 가져올 수 있습니다.