이 예제는 안드로이드 애플리케이션 어디에서나 기본 웹 브라우저를 통해 웹사이트를 여는 방법을 보여줍니다. 버튼 하나를 누르면 Intent.ACTION_VIEW 인텐트가 실행되어 지정한 URL이 시스템 기본 브라우저에서 열리는 구조입니다.
1단계 — 새 프로젝트 만들기
Android Studio에서 File → New Project 메뉴로 이동한 뒤, 새 프로젝트 생성에 필요한 정보를 모두 입력하여 프로젝트를 만듭니다.
2단계 — 레이아웃 작성 (res/layout/activity_main.xml)
화면 가운데에 "Amazon" 버튼 하나를 배치하는 단순한 레이아웃입니다.
<?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"
tools:context=".MainActivity">
<Button
android:id="@+id/btnAmazon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Amazon"
android:textStyle="bold" />
</RelativeLayout>
3단계 — MainActivity.java 작성
버튼이 클릭되면 ACTION_VIEW 인텐트를 사용해 아마존 홈페이지를 여는 코드입니다.
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.btnAmazon);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = "https://www.amazon.com";
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
}
});
}
}
핵심 코드 설명
new Intent(Intent.ACTION_VIEW, Uri.parse(url)) 부분이 핵심입니다. ACTION_VIEW는 "이 데이터를 사용자에게 보여달라"는 의미의 액션이며, URL 문자열을 Uri 객체로 변환해 전달하면 시스템이 해당 주소를 처리할 수 있는 앱(기본 웹 브라우저)을 자동으로 찾아 실행합니다. 별도의 인터넷 권한 설정은 필요하지 않습니다.
4단계 — AndroidManifest.xml
매니페스트 파일에는 별도의 권한 추가 없이 기본 구성 그대로 사용합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
<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 아이콘을 클릭하고, 목록에서 자신의 모바일 기기를 선택하세요. 그러면 기기 화면에 아래와 같은 기본 화면이 나타납니다.

