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

안드로이드에서 코드로 배경화면 이미지 설정하는 방법 (단계별 가이드)

개요

이 튜토리얼에서는 안드로이드 앱 내부에서 프로그래밍 방식으로 배경화면(Wallpaper) 이미지를 설정하는 방법을 단계별로 살펴봅니다. WallpaperManager 클래스를 활용하면 버튼 클릭 한 번으로 기기의 배경화면을 손쉽게 변경할 수 있습니다.

1단계: 새 프로젝트 생성

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

2단계: 레이아웃 파일 작성 (res/layout/activity_main.xml)

아래 코드를 res/layout/activity_main.xml에 추가합니다. 배경화면을 설정할 버튼 하나를 배치합니다.

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:text="배경화면 설정"
        android:layout_gravity="center_vertical"
        android:layout_centerInParent="true"
        android:layout_marginLeft="135dp"/>
</LinearLayout>

3단계: 메인 액티비티 작성 (src/MainActivity.java)

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

  • BitmapFactory.decodeResource()로 drawable 리소스를 비트맵으로 변환
  • WallpaperManager.getInstance()로 배경화면 관리자 인스턴스 획득
  • setBitmap() 호출로 배경화면 적용 및 결과 토스트 출력
import android.app.WallpaperManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setWallpaper();
            }
        });
    }

    private void setWallpaper() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.wallpaper);
        WallpaperManager manager = WallpaperManager.getInstance(getApplicationContext());
        try {
            manager.setBitmap(bitmap);
            Toast.makeText(this, "배경화면이 설정되었습니다!", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            Toast.makeText(this, "오류가 발생했습니다!", Toast.LENGTH_SHORT).show();
        }
    }
}

4단계: 권한 추가 (androidManifest.xml)

배경화면을 변경하려면 반드시 SET_WALLPAPER 권한이 필요합니다. 아래와 같이 androidManifest.xml에 권한을 선언합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <uses-permission android:name="android.permission.SET_WALLPAPER"/>
    <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(실행) 아이콘을 클릭하세요. 실행 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

안드로이드에서 코드로 배경화면 이미지 설정하는 방법 (단계별 가이드)

안드로이드에서 코드로 배경화면 이미지 설정하는 방법 (단계별 가이드)

안드로이드에서 코드로 배경화면 이미지 설정하는 방법 (단계별 가이드)

마무리

버튼을 누르면 setBitmap() 메서드가 실행되어 지정한 이미지가 즉시 배경화면으로 적용됩니다. 이 방식은 갤러리 앱이나 배경화면 추천 앱 등에서 실제로 널리 사용되는 패턴이므로, 응용하여 홈 화면과 잠금 화면을 각각 설정하거나 사용자가 선택한 이미지를 적용하는 기능으로 확장해 볼 수도 있습니다.