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

안드로이드에서 프로그래밍 방식으로 화면 밝기 변경하는 방법

이 튜토리얼에서는 안드로이드에서 프로그래밍 방식으로 화면 밝기를 변경하는 방법을 단계별로 살펴봅니다. 시크바(SeekBar) 위젯을 활용해 사용자가 직접 드래그하여 화면 밝기를 조절할 수 있는 간단한 예제 앱을 만들어 보겠습니다.

1단계: 새 프로젝트 생성

Android Studio를 실행한 뒤 File → New Project를 선택하고, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 프로젝트를 만듭니다.

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

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 중앙에 TextView와 밝기를 조절할 SeekBar를 배치하는 구조입니다.

<?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:padding="8dp"
    android:gravity="center"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Turn Off Screen"/>
    <SeekBar
        android:id="@+id/seekBar"
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

3단계: MainActivity 코드 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다. 핵심 로직은 다음과 같습니다.

  • Settings.System.getInt()로 현재 화면 밝기 값을 읽어옵니다.
  • 읽어온 값으로 SeekBar의 초기 위치를 설정합니다.
  • onProgressChanged() 콜백에서 Settings.System.putInt()를 호출해 밝기를 실시간으로 적용합니다.
import android.content.Context;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.SeekBar;
public class MainActivity extends AppCompatActivity {
    SeekBar lightBar;
    Context context;
    int brightness;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lightBar = findViewById(R.id.seekBar);
        context = getApplicationContext();
        brightness =
            Settings.System.getInt(context.getContentResolver(),
            Settings.System.SCREEN_BRIGHTNESS, 0);
        lightBar.setProgress(brightness);
        lightBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                Settings.System.putInt(context.getContentResolver(),
                    Settings.System.SCREEN_BRIGHTNESS, progress);
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) { }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) { }
        });
    }
}

4단계: 매니페스트에 권한 추가

androidManifest.xml 파일에 아래 코드를 추가합니다. 시스템 설정 값을 변경하려면 WRITE_SETTINGS 권한 선언이 반드시 필요합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    package="app.com.sample">
    <uses-permission
        android:name="android.permission.WRITE_SETTINGS"
        tools:ignore="ProtectedPermissions" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action
                    android:name="android.intent.action.MAIN" />
                <category
                    android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

앱 실행 및 결과 확인

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

안드로이드에서 프로그래밍 방식으로 화면 밝기 변경하는 방법

안드로이드에서 프로그래밍 방식으로 화면 밝기 변경하는 방법

참고 사항

  • 화면 밝기 값은 0~255 범위의 정수로 설정됩니다. 0에 가까울수록 어두워지고 255에 가까울수록 밝아집니다.
  • WRITE_SETTINGS 권한은 일반적인 런타임 권한과 달리, Android 6.0(API 23) 이상에서는 사용자가 시스템 설정 화면에서 직접 허용해야 합니다. 필요하다면 Settings.ACTION_MANAGE_WRITE_SETTINGS 인텐트를 사용해 사용자를 해당 설정 페이지로 안내할 수 있습니다.