본문 바로가기

안드로이드

안드로이드 유튜브(youtube) v3 동영상 리스트 검색 , 재생하기

- Edittext에서 검색값을 입력한 후 검색 버튼을 누르면 유튜브에서 검색된 내용이 나오고 리스트를 클릑하면 재생이 되는 예제입니다.





- 유튜브 검색을 사용하려면 서버키가 필요한데 https://cloud.google.com/console 에서 받으시면 됩니다.  ( https://developers.google.com/youtube/registering_an_application?hl=ko 참고하십시오)


- https://www.googleapis.com/youtube/v3/search 에서 파라미터를 넘기면 json으로 필요한 값을 리턴해 줍니다.  필수 파라미터는 part , key 입니다.

(https://developers.google.com/youtube/v3/docs/search/list#try-it 에 파라미터 설명이 잘되어있습니다)


////////////////////////////////////////////////////////////////////////////////////////////////////


동영상 검색후 리스트 뿌려주는 Activity


public class StartActivity extends Activity { static DrawableManager DM = new DrawableManager(); private EditText et; AsyncTask<?, ?, ?> searchTask; ArrayList<SearchData> sdata = new ArrayList<SearchData>(); final String serverKey="서버키를 넣으세요"; //콘솔에서 받아온 서버키를 넣어줍니다 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_start); et = (EditText) findViewById(R.id.eturl); Button search = (Button) findViewById(R.id.search); search.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { searchTask = new searchTask().execute(); } }); } private class searchTask extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... params) { try { paringJsonData(getUtube()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { ListView searchlist = (ListView) findViewById(R.id.searchlist); StoreListAdapter mAdapter = new StoreListAdapter( StartActivity.this, R.layout.listview_start, sdata); //Json파싱해서 가져온 유튜브 데이터를 이용해서 리스트를 만들어줍니다. searchlist.setAdapter(mAdapter); } } public JSONObject getUtube() { HttpGet httpGet = new HttpGet( "https://www.googleapis.com/youtube/v3/search?" + "part=snippet&q=" + et.getText().toString() + "&key="+ serverKey+"&maxResults=50"); //EditText에 입력된 값으로 겁색을 합니다. // part(snippet), q(검색값) , key(서버키) HttpClient client = new DefaultHttpClient(); HttpResponse response; StringBuilder stringBuilder = new StringBuilder(); try { response = client.execute(httpGet); HttpEntity entity = response.getEntity(); InputStream stream = entity.getContent(); int b; while ((b = stream.read()) != -1) { stringBuilder.append((char) b); } } catch (ClientProtocolException e) { } catch (IOException e) { } JSONObject jsonObject = new JSONObject(); try { jsonObject = new JSONObject(stringBuilder.toString()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonObject; } //파싱을 하면 여러가지 값을 얻을 수 있는데 필요한 값들을 세팅하셔서 사용하시면 됩니다. private void paringJsonData(JSONObject jsonObject) throws JSONException { sdata.clear(); JSONArray contacts = jsonObject.getJSONArray("items"); for (int i = 0; i < contacts.length(); i++) { JSONObject c = contacts.getJSONObject(i); String kind = c.getJSONObject("id").getString("kind"); // 종류를 체크하여 playlist도 저장 if(kind.equals("youtube#video")){ vodid = c.getJSONObject("id").getString("videoId"); // 유튜브 // 동영상 // 아이디 // 값입니다. // 재생시 // 필요합니다. }else{ vodid = c.getJSONObject("id").getString("playlistId"); // 유튜브 } String title = c.getJSONObject("snippet").getString("title"); //유튜브 제목을 받아옵니다 String changString = ""; try { changString = new String(title.getBytes("8859_1"), "utf-8"); //한글이 깨져서 인코딩 해주었습니다 } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } String date = c.getJSONObject("snippet").getString("publishedAt") //등록날짜 .substring(0, 10); String imgUrl = c.getJSONObject("snippet").getJSONObject("thumbnails") .getJSONObject("default").getString("url"); //썸내일 이미지 URL값 sdata.add(new SearchData(vodid, changString, imgUrl, date)); } } String vodid = ""; public class StoreListAdapter extends ArrayAdapter<SearchData> { private ArrayList<SearchData> items; SearchData fInfo; public StoreListAdapter(Context context, int textViewResourseId, ArrayList<SearchData> items) { super(context, textViewResourseId, items); this.items = items; } public View getView(int position, View convertView, ViewGroup parent) {// listview // 출력 View v = convertView; fInfo = items.get(position); LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.listview_start, null); ImageView img = (ImageView) v.findViewById(R.id.img); String url = fInfo.getUrl(); String sUrl = ""; String eUrl = ""; sUrl = url.substring(0, url.lastIndexOf("/") + 1); eUrl = url.substring(url.lastIndexOf("/") + 1, url.length()); try { eUrl = URLEncoder.encode(eUrl, "EUC-KR").replace("+", "%20"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } String new_url = sUrl + eUrl; Glide.with(MomMemoDetailActivity.this).load(new_url).into(img); v.setTag(position); v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int pos = (Integer) v.getTag(); Intent intent = new Intent(StartActivity.this, MainActivity.class); intent.putExtra("id", items.get(pos).getVideoId()); startActivity(intent); //리스트 터치시 재생하는 엑티비티로 이동합니다. 동영상 아이디를 넘겨줍니다.. } }); ((TextView) v.findViewById(R.id.title)).setText(fInfo.getTitle()); ((TextView) v.findViewById(R.id.date)).setText(fInfo .getPublishedAt()); return v; } }

이미지 로더 클래스


glide-3.4.0.jar



검색된 데이터 클래스

public class SearchData {
String videoId;
String title;
String url;
String publishedAt;

public SearchData(String videoId, String title, String url,
String publishedAt) {
super();
this.videoId = videoId;
this.title = title;
this.url = url;
this.publishedAt = publishedAt;
}

public String getVideoId() {
return videoId;
}

public void setVideoId(String videoId) {
this.videoId = videoId;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public String getPublishedAt() {
return publishedAt;
}

public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
	}
}



동영상 재생 Activity

YouTubeAndroidPlayerApi.jar 를 다운 받아서 libs 폴더에 놓어줍니다
(https://developers.google.com/youtube/android/player/downloads/)

import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

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.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;

public class MainActivity extends YouTubeBaseActivity implements
		YouTubePlayer.OnInitializedListener {

	private YouTubePlayerView ytpv;
	private YouTubePlayer ytp;
	final String serverKey="서버키를 넣으세요"; //콘솔에서 받아온 서버키를 넣어줍니다	

        @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		 ytpv = (YouTubePlayerView) findViewById(R.id.youtubeplayer);
		 ytpv.initialize(serverKey, this);
		
	}



	@Override
	public void onInitializationFailure(Provider arg0,
			YouTubeInitializationResult arg1) {
		Toast.makeText(this, "Initialization Fail", Toast.LENGTH_LONG).show();
	}

	@Override
	public void onInitializationSuccess(Provider provider,
			YouTubePlayer player, boolean wasrestored) {
		ytp = player;
		
		Intent gt =getIntent();
		ytp.loadVideo(gt.getStringExtra("id"));
	}

}
xml 파일들

activity_start.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="50dip" android:orientation="horizontal" > <EditText android:id="@+id/eturl" android:layout_width="200dip" android:layout_height="50dip" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:hint="검색어를 입력하세요" android:imeOptions="actionGo" android:singleLine="true" > </EditText> <Button android:id="@+id/search" android:layout_width="50dip" android:layout_height="50dip" android:layout_marginLeft="10dip" android:background="#000000" android:gravity="center" android:text="검색" android:textColor="#ffffff" /> </LinearLayout> <ListView android:id="@+id/searchlist" android:layout_width="fill_parent" android:layout_height="500dip" > </ListView> </LinearLayout>



listview_start.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="100dip"
    android:orientation="horizontal" >

    <LinearLayout
        android:layout_width="0dip"
        android:layout_height="100dip"
        android:layout_weight="2"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/img"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
        </ImageView>
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dip"
        android:layout_height="100dip"
        android:layout_weight="4"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/date"
            android:layout_width="match_parent"
            android:layout_height="30dip"
            android:singleLine="true" >
        </TextView>

        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="70dip" >
        </TextView>
    </LinearLayout>

</LinearLayout>


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <com.google.android.youtube.player.YouTubePlayerView android:id="@+id/youtubeplayer" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_below="@+id/eturl" > </com.google.android.youtube.player.YouTubePlayerView> </RelativeLayout>























'안드로이드' 카테고리의 다른 글

android nfc mime type 이용하기  (0) 2014.07.09
구글 인앱결제 v3  (1) 2014.04.28
andrid DB 예제  (0) 2013.11.28
android 주소로 위도,경도얻기  (0) 2013.11.22
[java] 특정일로 부터 7일전 날짜구하기  (0) 2013.10.16