오늘이라도
[Android] 25. 동영상 재생 / 유튜브 재생 : API 라이브러리 다운, API키 생성 본문
취업성공패키지 SW 개발자 교육/Android
[Android] 25. 동영상 재생 / 유튜브 재생 : API 라이브러리 다운, API키 생성
upcake_ 2020. 6. 11. 09:30반응형
https://github.com/upcake/Class_Examples
교육 중에 작성한 예제들은 깃허브에 올려두고 있습니다.
gif 파일은 클릭해서 보는 것이 정확합니다.
- 동영상 재생 -
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.my35_videoplayer">
<!--권한 받기-->
<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"
android:usesCleartextTraffic="true">
<!--구글 보안 정책 강화로 https만 제대로 작동되고 http는 제대로 작동이 안되는 경우가 생겼는데-->
<!--usesClearTextTraffic을 true로 하면 http도 사용 가능해진다.-->
<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>
▲AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="재생"
android:textSize="24sp" />
<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
▲activity_main.xml
package com.example.my35_videoplayer;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
public class MainActivity extends AppCompatActivity {
public String VIDEO_URL = "http://sites.google.com/site/ubiaccessmobile/sample_video.mp4";
Button btnStart;
VideoView videoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoView = findViewById(R.id.videoView);
MediaController mc = new MediaController(this);
videoView.setMediaController(mc);
//재생 준비가 되었을 때
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
Toast.makeText(MainActivity.this, "동영상 준비됨", Toast.LENGTH_SHORT).show();
}
});
//재생이 끝났을때
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
Toast.makeText(MainActivity.this, "동영상 재생 완료", Toast.LENGTH_SHORT).show();
}
});
//버튼 기능 추가 : 누르면 URL을 URI로 바꾸고 재생생
btnStart = findViewById(R.id.button1);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
videoView.setVideoURI(Uri.parse(VIDEO_URL));
videoView.requestFocus();
videoView.start();
}
});
}
@Override
protected void onResume() {
super.onResume();
Toast.makeText(MainActivity.this, "동영상 준비중입니다.", Toast.LENGTH_SHORT).show();
}
}
▲MainActivity.java
- 유튜브 재생 : API 라이브러리 다운, API키 생성 -
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.my36_youtube">
<!--권한 부여-->
<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>
▲AndroidMainifest.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="유튜브 재생"
android:textSize="24sp"/>
<com.google.android.youtube.player.YouTubePlayerView
android:id="@+id/playerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
▲activity_main.xml
- https://developers.google.com/youtube/android/player/downloads
- Youtube 플레이어 API 라이브러리를 다운받는다.
- Project > app > libs 에 붙여넣는다.
- https://console.developers.google.com/
- Google APIs 콘솔 페이지에서 API 키를 발급받고 Youtube Data API를 사용 설정한다.
package com.example.my36_youtube;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
//YouTubeBaseActivity를 상속받게끔 설정한다.
public class MainActivity extends YouTubeBaseActivity {
//객체 선언
YouTubePlayerView playerView;
YouTubePlayer player;
//유튜브 API KEY와 동영상 ID 변수 설정
private static String API_KEY = "개인 API KEY";
//https://www.youtube.com/watch?v=6egQkFx7UkM ▶ 유튜브 동영상 v= 다음 부분이 videoId
private static String videoId = "6egQkFx7UkM";
//logcat 사용 설정
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initPlayer();
Button btnPlay = findViewById(R.id.button1);
btnPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
playVideo();
}
});
}
private void playVideo() {
if(player != null) {
if(player.isPlaying()) {
player.pause();
}
player.cueVideo(videoId);
}
}
//유튜브 플레이어 메서드
private void initPlayer() {
playerView = findViewById(R.id.playerView);
playerView.initialize(API_KEY, new YouTubePlayer.OnInitializedListener() {
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
player = youTubePlayer;
player.setPlayerStateChangeListener(new YouTubePlayer.PlayerStateChangeListener() {
@Override
public void onLoading() {
}
@Override
public void onLoaded(String id) {
Log.d(TAG, "onLoaded: " + id);
player.play();
}
@Override
public void onAdStarted() {
}
@Override
public void onVideoStarted() {
}
@Override
public void onVideoEnded() {
}
@Override
public void onError(YouTubePlayer.ErrorReason errorReason) {
Log.d(TAG, "onError: " + errorReason);
}
});
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
});
}
}
▲MainActivity.java
- 현재 위치의 위도, 경도 출력 -
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.my37_location">
<!--권한 설정-->
<!--COARSE : 기지국-->
<!--FINE : 위성-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<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>
▲AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerHorizontal="true"
android:layout_marginStart="5dp"
android:layout_marginTop="0dp"
android:layout_marginEnd="-1dp"
android:layout_marginRight="0dp"
android:text="내 위치 확인하기"
android:textSize="24sp" />
<TextView
android:id="@+id/textView"
android:layout_width="401dp"
android:layout_height="671dp"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="58dp"
android:layout_marginBottom="1dp"
android:text="내 위치"
android:textSize="24sp" />
</RelativeLayout>
▲activity_main.xml
package com.example.my37_location;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
//객체 선언
Button btnMyLocation;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//권한 설정
checkDangerousPermissions();
//객체 초기화
btnMyLocation = findViewById(R.id.button1);
textView = findViewById(R.id.textView);
//버튼 기능 추가
btnMyLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startLocationService();
}
});
}
private void startLocationService() {
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
GPSListener gpsListener = new GPSListener();
long minTime = 1000; //1초마다 갱신
float minDistance = 0; //위치 변화가 없더라도(0) 갱신한다.
try {
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, gpsListener); //위성
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, minTime, minDistance, gpsListener); //기지국
//연결이 끊길 경우 마지막 위치로 표시되게끔 설정 (위성 or 기지국)
Location lastLocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(lastLocation != null) {
Double latitude = lastLocation.getLatitude(); //위도
Double longitude = lastLocation.getLongitude(); //경도
String msg = "Last Latitude : " + latitude + "\nLast Longitude : " + longitude;
textView.setText(msg);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
} catch (SecurityException e) {
e.printStackTrace();
}
}
private class GPSListener implements LocationListener {
//위치가 바뀌었을 때
@Override
public void onLocationChanged(Location location) {
Double latitude = location.getLatitude(); //위도
Double longitude = location.getLongitude(); //경도
String msg = "Latitude : " + latitude + "\nLongitude : " + longitude;
textView.setText(msg);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
}
//------------------권한 설정 시작------------------------
private void checkDangerousPermissions() {
String[] permissions = {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_WIFI_STATE
};
int permissionCheck = PackageManager.PERMISSION_GRANTED;
for (int i = 0; i < permissions.length; i++) {
permissionCheck = ContextCompat.checkSelfPermission(this, permissions[i]);
if (permissionCheck == PackageManager.PERMISSION_DENIED) {
break;
}
}
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "권한 있음", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "권한 없음", Toast.LENGTH_LONG).show();
if (ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[0])) {
Toast.makeText(this, "권한 설명 필요함.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(this, permissions, 1);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 1) {
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, permissions[i] + " 권한이 승인됨.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, permissions[i] + " 권한이 승인되지 않음.", Toast.LENGTH_LONG).show();
}
}
}
}
//------------------권한 설정 끝------------------------
}
▲MainActivity.java
반응형