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

안드로이드에서 인텐트(Intent)로 브라우저에 특정 URL 열기 – 단계별 완벽 가이드

이 튜토리얼에서는 안드로이드 앱에서 인텐트(Intent)를 사용하여 기기의 기본 브라우저를 통해 특정 URL을 여는 방법을 단계별로 알아봅니다. 인텐트는 안드로이드 컴포넌트 간에 작업을 요청하는 메시지 객체로, 웹페이지 열기와 같은 외부 작업을 수행할 때 가장 널리 사용되는 방식입니다.

1단계: 새 프로젝트 생성

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

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

아래 코드를 activity_main.xml 파일에 추가합니다. 화면 중앙에 버튼 하나를 배치하는 간단한 구조입니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:padding="8dp"
    tools:context=".MainActivity">
    <Button
        android:onClick="GetUrlFromIntent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get URL from Intent"
        android:layout_centerInParent="true"/>
</RelativeLayout>

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

아래 코드를 MainActivity.java에 추가합니다. 버튼이 클릭되면 Intent.ACTION_VIEW 액션과 함께 대상 URL을 설정하여 브라우저를 실행합니다.

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void GetUrlFromIntent(View view) {
        String url = "https://www.google.com";
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(url));
        startActivity(i);
    }
}

코드 핵심 포인트

  • Intent.ACTION_VIEW: 사용자에게 데이터를 보여주는 작업을 요청하는 표준 액션입니다.
  • Uri.parse(url): 문자열 형태의 URL을 Uri 객체로 변환합니다.
  • startActivity(i): 해당 인텐트를 처리할 수 있는 앱(브라우저)을 시스템이 자동으로 찾아 실행합니다.

4단계: 매니페스트 설정 (androidManifest.xml)

인터넷 접근 권한을 추가하기 위해 아래 코드를 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.INTERNET"/>
    <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(실행) 아이콘을 클릭하세요. 목록에서 본인의 모바일 기기를 선택하면 앱이 설치되고 실행됩니다.

앱이 실행되면 아래와 같은 기본 화면이 표시됩니다.

안드로이드에서 인텐트(Intent)로 브라우저에 특정 URL 열기 – 단계별 완벽 가이드


안드로이드에서 인텐트(Intent)로 브라우저에 특정 URL 열기 – 단계별 완벽 가이드

화면 중앙의 버튼을 클릭하면 시스템이 설치된 브라우저를 감지하여 지정한 URL(구글 홈페이지)을 자동으로 열어줍니다. 이처럼 인텐트를 활용하면 몇 줄의 코드만으로 외부 앱과 손쉽게 연동할 수 있습니다.