android - Upload video via Youtube App and return video link to activity -
i'm trying share youtube link within app using following flow:
1) select video within app using gallery pick intent.
2) send video youtube app using intent, , upload youtube there.
3) newly uploaded video link youtube app , return activity via activity result.
unfortunately stuck @ step 3 couldn't find way launch youtube upload activity result or link it, , far have seen far there doesn't seem way return upload result calling app.
i aware youtube api exists, trying avoid using due associated costs may appear on usage.
if has insight how done appreciated.
create class preferencemanager.java
public class preferencemanager { static string accountnamem; public static string getaccountname() { return accountnamem; } public static void setaccountname (string accountname) { accountnamem = accountname; } }
create fragment newupload.java
import android.accounts.accountmanager; import android.app.activity; import android.app.dialog; import android.content.context; import android.content.intent; import android.database.cursor; import android.net.uri; import android.os.asynctask; import android.os.bundle; import android.os.environment; import android.provider.mediastore; import android.support.annotation.nullable; import android.support.v4.app.fragment; import android.util.log; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.widget.button; import android.widget.toast; import com.google.android.gms.common.connectionresult; import com.google.android.gms.common.googleapiavailability; import com.google.android.gms.common.googleplayservicesutil; import com.google.android.gms.common.api.result; import com.google.api.client.extensions.android.http.androidhttp; import com.google.api.client.googleapis.extensions.android.gms.auth.googleaccountcredential; import com.google.api.client.googleapis.extensions.android.gms.auth.googleplayservicesavailabilityioexception; import com.google.api.client.googleapis.extensions.android.gms.auth.userrecoverableauthioexception; import com.google.api.client.googleapis.media.mediahttpuploader; import com.google.api.client.googleapis.media.mediahttpuploaderprogresslistener; import com.google.api.client.http.httptransport; import com.google.api.client.http.inputstreamcontent; import com.google.api.client.json.jsonfactory; import com.google.api.client.json.gson.gsonfactory; import com.google.api.services.youtube.youtube; import com.google.api.services.youtube.youtubescopes; import com.google.api.services.youtube.model.video; import com.google.api.services.youtube.model.videosnippet; import com.google.api.services.youtube.model.videostatus; import com.google.common.collect.lists; import java.io.bufferedinputstream; import java.io.file; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.ioexception; import java.util.arraylist; import java.util.list; import in.eightfolds.youtubeupload.utils.preferencemanager; /** * created sagar on 21/08/2017. */ public class newupload extends fragment{ private static googleaccountcredential credential; private static final httptransport transport = androidhttp.newcompatibletransport(); private static final jsonfactory jsonfactory = new gsonfactory(); public youtube youtube; list<string> scopes = lists.newarraylist(youtubescopes.youtube_upload); private static string video_file_format = "video/*"; static final int request_google_play_services = 0; static final int request_authorization = 1; static final int request_account_picker = 2; static context context; button btn_upload; private string tag = "tag"; private int play_services_resolution_request = 1037; @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { context = getactivity(); return inflater.inflate(r.layout.fragment_upload, container, false); } @override public void onviewcreated(view view, @nullable bundle savedinstancestate) { super.onviewcreated(view, savedinstancestate); btn_upload = view.findviewbyid(r.id.btn_upload); } @override public void onactivitycreated(@nullable bundle savedinstancestate) { super.onactivitycreated(savedinstancestate); try { credential = googleaccountcredential(scopes); } catch (exception e) { e.printstacktrace(); } youtube = new youtube.builder(transport, jsonfactory, credential) .setapplicationname("myappname") .build(); btn_upload.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { if (hasplayservices()) { uploadyoutubevideos(); toast.maketext(getactivity(), "clicked", toast.length_short).show(); } else { toast.maketext(getactivity(), "no play services", toast.length_short).show(); } } }); } private static googleaccountcredential googleaccountcredential(list<string> scopes) throws exception { credential = googleaccountcredential.usingoauth2(context, scopes) .setselectedaccountname(preferencemanager.getaccountname()); return credential; } private void chooseaccount() { startactivityforresult(credential.newchooseaccountintent(), request_account_picker); } public void uploadyoutubevideos() { if (credential.getselectedaccountname() == null) { chooseaccount(); } else { file videofile = new file(environment.getexternalstoragedirectory().getabsolutepath() + "/video.mp4"); youtube.videos.insert videoinsert = prepareupload(videofile); new videouploadasynctask().execute(videoinsert); } } @override public void onactivityresult(int requestcode, int resultcode, intent data) { super.onactivityresult(requestcode, resultcode, data); switch (requestcode) { case request_authorization: if (resultcode == activity.result_ok) { uploadyoutubevideos(); } else { chooseaccount(); } break; case request_account_picker: if (resultcode == activity.result_ok && data != null && data.getextras() != null) { string accountname = data.getextras().getstring(accountmanager.key_account_name); if (accountname != null) { credential.setselectedaccountname(accountname); preferencemanager.setaccountname(accountname); uploadyoutubevideos(); } } break; } } public youtube.videos.insert prepareupload(file videofile) { try { // add information video before uploading. video videoobjectdefiningmetadata = new video(); // set video public (default). videostatus status = new videostatus(); status.setprivacystatus("public"); videoobjectdefiningmetadata.setstatus(status); // set majority of metadata videosnippet object. videosnippet snippet = new videosnippet(); // video file name. snippet.settitle(videofile.getname()); snippet.setdescription("test description"); // set keywords. list<string> tags = new arraylist<string>(); tags.add("test"); snippet.settags(tags); // set completed snippet video object. videoobjectdefiningmetadata.setsnippet(snippet); inputstreamcontent mediacontent = new inputstreamcontent( video_file_format, new bufferedinputstream(new fileinputstream(videofile))); mediacontent.setlength(videofile.length()); /* * upload command includes: 1. information want returned after file * uploaded. 2. metadata want associated uploaded video. 3. video file itself. */ youtube.videos.insert videoinsert = youtube.videos() .insert("snippet,statistics,status", videoobjectdefiningmetadata, mediacontent); // set upload type , add event listener. mediahttpuploader uploader = videoinsert.getmediahttpuploader(); /* * sets whether direct media upload enabled or disabled. true = whole media content * uploaded in single request. false (default) = resumable media upload protocol upload * in data chunks. */ uploader.setdirectuploadenabled(false); mediahttpuploaderprogresslistener progresslistener = new mediahttpuploaderprogresslistener() { public void progresschanged(mediahttpuploader uploader) throws ioexception { switch (uploader.getuploadstate()) { case initiation_started: log.d(tag, "upload file: initiation started"); break; case initiation_complete: log.d(tag, "upload file: initiation completed"); break; case media_in_progress: log.d(tag, "upload file: upload in progress"); log.d(tag, "upload file: upload percentage: " + uploader.getprogress()); break; case media_complete: log.d(tag, "upload file: upload completed!"); break; case not_started: log.d(tag, "upload file: upload not started!"); break; } } }; uploader.setprogresslistener(progresslistener); return videoinsert; } catch (filenotfoundexception e) { log.e(tag, "file not found: " + e.getmessage()); return null; } catch (ioexception e) { log.e(tag, "ioexception: " + e.getmessage()); return null; } } void showgoogleplayservicesavailabilityerrordialog(final int connectionstatuscode) { getactivity().runonuithread(new runnable() { public void run() { dialog dialog = googleplayservicesutil.geterrordialog(connectionstatuscode, getactivity(), request_google_play_services); dialog.show(); } }); } public class videouploadasynctask extends asynctask<youtube.videos.insert, void, void> { @override protected void doinbackground(youtube.videos.insert... inserts) { youtube.videos.insert videoinsert = inserts[0]; try { video returnvideo = videoinsert.execute(); returnvideo.getid(); log.i("video id", "" + returnvideo.getid()); // ----> video id . toast.maketext(getactivity(), ""+"https://www.youtube.com/watch?v="+returnvideo.getid(), toast.length_short).show(); log.i("video id1", "" + returnvideo.getfiledetails()); log.i("video url", "" + "https://www.youtube.com/watch?v="+returnvideo.getid()); } catch (final googleplayservicesavailabilityioexception availabilityexception) { showgoogleplayservicesavailabilityerrordialog( availabilityexception.getconnectionstatuscode()); } catch (userrecoverableauthioexception userrecoverableexception) { startactivityforresult( userrecoverableexception.getintent(), newupload.request_authorization); } catch (ioexception e) { log.e(tag, "ioexception: " + e.getmessage()); } return null; } } private boolean hasplayservices() { googleapiavailability apiavailability = googleapiavailability.getinstance(); int resultcode = apiavailability.isgoogleplayservicesavailable(getactivity()); if (resultcode != connectionresult.success) { if (apiavailability.isuserresolvableerror(resultcode)) { apiavailability.geterrordialog(getactivity(), resultcode, play_services_resolution_request) .show(); } else { log.i(tag, "this device not supported."); // finish(); toast.maketext(getactivity(), "play services not available", toast.length_short).show(); } return false; } return true; } }
call fragment activity using
newupload upload=new newupload(); getsupportfragmentmanager() .begintransaction() .add(r.id.relative_main,upload) // give container id here .commit();
for above example work add read storage permission . keep video in internal memory name "video.mp4" -->this video uploaded choosen account
you can change logic in uploadyoutubevideos()
method inside fragment
for layout keep 1 button id btn_upload
inside fragment_upload
use dependency gsonfactory
compile 'com.google.http-client:google-http-client-gson:1.19.0'
Comments
Post a Comment