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

안드로이드에서 인텐트(Intent)로 YouTube 앱을 열어 동영상 재생하는 방법

앱을 개발하다 보면 자신의 애플리케이션 안에서 특정 동영상을 보여주기 위해 YouTube 앱을 직접 실행해야 하는 경우가 있습니다. 이번 글에서는 인텐트(Intent)를 활용해 안드로이드 기기에 설치된 YouTube 앱을 호출하고 원하는 동영상을 재생하는 방법을 단계별로 살펴보겠습니다.

1단계: 새 프로젝트 생성

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

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

다음 코드를 res/layout/activity_main.xml에 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/parent"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/openYoutube"
android:text="Open youtube application"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

위 코드는 화면 중앙에 하나의 TextView를 배치한 레이아웃입니다. 사용자가 이 텍스트뷰를 클릭하면 YouTube 앱이 실행되도록 만들 것입니다.

3단계: MainActivity 코드 작성

이어서 다음 코드를 src/MainActivity.java에 추가합니다.

package com.example.andy.myapplication;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView openYoutube = findViewById(R.id.openYoutube);
openYoutube.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent webIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.youtube.com/watch?v=5X7WWVTrBvM"));
try {
MainActivity.this.startActivity(webIntent);
} catch (ActivityNotFoundException ex) {
}
}
});
}
}

핵심 코드 분석

YouTube 앱을 여는 핵심 로직은 아래와 같습니다.

Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/watch?v=5X7WWVTrBvM"));
try {
MainActivity.this.startActivity(webIntent);
} catch (ActivityNotFoundException ex) {
}

ACTION_VIEW 인텐트에 YouTube 동영상 URL을 담아 전달하면, 안드로이드 시스템은 해당 URL을 처리할 수 있는 앱, 즉 YouTube 앱을 자동으로 찾아 실행합니다. 만약 기기에 YouTube 앱이 설치되어 있지 않다면 ActivityNotFoundException이 발생할 수 있으므로 try-catch 문으로 감싸 예외를 처리해 주는 것이 좋습니다.

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결한 상태라고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run(실행) 아이콘을 클릭하고, 목록에서 본인의 모바일 기기를 선택하면 됩니다.

앱이 실행되면 아래와 같은 초기 화면이 나타납니다.

안드로이드에서 인텐트(Intent)로 YouTube 앱을 열어 동영상 재생하는 방법

이 화면에서 텍스트뷰를 클릭하면 지정한 동영상과 함께 YouTube 앱이 자동으로 실행되는 것을 확인할 수 있습니다.

안드로이드에서 인텐트(Intent)로 YouTube 앱을 열어 동영상 재생하는 방법