Optimise Way to run youtube video on android - java

Can we have any optimise way to run video.Below mention is my code.This code help in run the youtube video.
if (YouTubeIntents.canResolvePlayVideoIntent(activity)){
//Getting ID of YouTube video out of URL
List<NameValuePair> params = null;
try {
params = URLEncodedUtils.parse(new URI(sourceUrl), "UTF-8");
} catch (URISyntaxException e) {
e.printStackTrace();
}
String videoID = params.get(0).getValue();
Log.v(TAG, "YouTube Video ID:" + videoID);
// createPlayVideoIntentWithOptions only works for first
// video playback. Update to use stand-alone player api instead.
Intent intent = YouTubeStandalonePlayer.createVideoIntent(
activity, g.kGoogleAPIKey,
videoID, 0, true, false);
activity.startActivity(intent);
Log.i(TAG, "Video Playing in YouTube App....");
} else {
Log.v(TAG, "YouTube generic intent");
activity.startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(sourceUrl)));
Log.i(TAG, "Video Playing in whatever user selected....");
}

your question is a bit vague.. if all you want to do is play a youTube video from your app you can easily just call the yourtube intent.. and pass the url of the video as an extra. this would open youTube..
alternatively you can get access to the youTube Player api: https://developers.google.com/youtube/android/player/reference/com/google/android/youtube/player/package-summary
which you will have to get an api key and do something like this:
This example looks to see if the standalone player is available to your user and if it isn't calls youtube directly as stated in the first part of my answer
if (YouTubeIntents.canResolvePlayVideoIntent(activity)){
//Getting ID of YouTube video out of URL
List<NameValuePair> params = null;
try {
params = URLEncodedUtils.parse(new URI(sourceUrl), "UTF-8");
} catch (URISyntaxException e) {
e.printStackTrace();
}
String videoID = params.get(0).getValue();
Log.v(TAG, "YouTube Video ID:" + videoID);
// createPlayVideoIntentWithOptions only works for first
// video playback. Update to use stand-alone player api instead.
Intent intent = YouTubeStandalonePlayer.createVideoIntent(
activity, g.kGoogleAPIKey,
videoID, 0, true, false);
activity.startActivity(intent);
Log.i(TAG, "Video Playing in YouTube App....");
} else {
Log.v(TAG, "YouTube generic intent");
activity.startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(sourceUrl)));
Log.i(TAG, "Video Playing in whatever user selected....");
}

Related

java.net.ProtocalException while using certain URL in VideoView android

I have the below list of test video links which i am am trying to set it on my VideoView. The first two works fine but the third one shows java.net.ProtocalException and I have the same problem when i user the link from my local Spring Web Application Server. How to play such link in videoView?
The list of links
1. VIDEO_SOURCE = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/SubaruOutbackOnStreetAndDirt.mp4";
2. VIDEO_SOURCE = "https://media.geeksforgeeks.org/wp-content/uploads/20201217192146/Screenrecorder-2020-12-17-19-17-36-828.mp4?_=1";
3. VIDEO_SOURCE = "https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4";
VideoView Code
if( URLUtil.isValidUrl(VIDEO_SOURCE)){
try{
videoUri = getMedia(VIDEO_SOURCE);
// Set up the media controller widget and attach it to the video view.
MediaController controller = new MediaController(_CourseContents.this);
// anchor view for the videoView
controller.setAnchorView(mVideoView);
// sets the media player to the videoView
controller.setMediaPlayer(mVideoView);
// sets the media controller to the videoView
mVideoView.setMediaController(controller);
mVideoView.setVideoURI(videoUri);
try {
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
} catch (Exception e) {
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
}
catch(Exception e){
Toast.makeText(getApplicationContext(), "Cannot parse video source:" + e.getMessage(), Toast.LENGTH_LONG).show();
finish();
}}else {
Toast.makeText(getApplicationContext(), "Invalid video source.", Toast.LENGTH_LONG).show();
finish();
}
The Error

open map location on image click but some device having Google Map cant open the intent

currently i am using this but(to open map location on image click but some device having GoogleMap cant open the intent) the issue is even device has apps to handle the map intent it wont execute that part
any better way to do this?
like option to select from available apps and no apps to handle that then go for browser
private void openMap()
{
String Packagename ="com.google.android.apps.maps";
if (appInstalledOrNot(Packagename))
{
Uri uri = Uri.parse("geo:0,0?q=V.V.P.+Engineering+College+Kalavad+Road+Virda+Vajadi,+Rajkot");
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);
}else
{
try {
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://goo.gl/maps/ETVvFWw453CoeBHs9"));
startActivity(myIntent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
Toast.makeText(getContext(), "Map application not found", Toast.LENGTH_SHORT).show();
}
}

How to launch Telegram app from my own android application?

I have an android app that should be able to open a chat in the telegram app by pressing a button.
I want to open an existing robot chat page DIRECTLY from my app. I have a valid token for my robot. How can this be achieved?
Thanks in advance.
robot name : #InfotechAvl_bot
robot token: 179284***********
//-------------
case ContentFragment.lMenuTelegram:
Intent LaunchIntent=getPackageManager().getLaunchIntentForPackage("org.telegram.messenger");
startActivity(LaunchIntent);
break;
To solve this problem you have to open robot id with this :
Intent telegram = new Intent(Intent.ACTION_VIEW , Uri.parse("https://telegram.me/InfotechAvl_bot"));
startActivity(telegram);
for Instagram and Telegram and WhatsApp you can use this methods
void getTelegram(){
try {
Intent telegramIntent = new Intent(Intent.ACTION_VIEW);
telegramIntent.setData(Uri.parse("https://telegram.me/diako099"));
startActivity(telegramIntent);
} catch (Exception e) {
// show error message
}
}
void getInstagram(){
try {
Intent instagramIntent = new Intent(Intent.ACTION_VIEW);
instagramIntent.setData(Uri.parse("https://www.instagram.com/diako_hasani99/"));
startActivity(instagramIntent);
} catch (Exception e) {
// show error message
}
}
void getWhatsApp(){
try{
String trimToNumner = "+989180074693"; //10 digit number
Intent intent = new Intent ( Intent.ACTION_VIEW );
intent.setData ( Uri.parse ( "https://wa.me/" + trimToNumner + "/?text=" + "" ) );
startActivity ( intent );
}catch (Exception e){
}
}

MediaRecorder not saving files

I've had a look through the other people's encounters with this problem and have not found an adequate solution.
Like them, I followed the tutorial on camera functionality at: http://developer.android.com/guide/topics/media/camera.html.
Everything listed below works perfectly to the point where I assume that the program has recorded video as I had intended. However, upon reviewing the video in the gallery, it has not appeared. I'm confused as there are no IOExceptions or other bugs present when connected for USB debugging. Strangely, upon removing the USB and plugging it in again, whenever that may be, either immediately or at some point days in the future, all of the previously recorded videos appear in the gallery. Clearly there something I have missed or some aspect of recording video that I am not aware of. Would appreciate any help or guidance, thank you.
Pertinent code is as follows, I'll post more if someone needs it.
Camera Activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mCamera = MainActivity.getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
button_capture = (Button) findViewById(R.id.button_capture);
button_capture.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isRecording) {
// stop recording and release camera
mMediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object
mCamera.lock(); // take camera access back from MediaRecorder
// inform the user that recording has stopped
button_capture.setText("Capture");
isRecording = false;
} else {
// initialize video camera
if (prepareVideoRecorder()) {
// Camera is available and unlocked, MediaRecorder is prepared,
// now you can start recording
mMediaRecorder.start();
// inform the user that recording has started
button_capture.setText("Stop");
isRecording = true;
} else {
// prepare didn't work, release the camera
releaseMediaRecorder();
// inform user
}
}
}
});
}
private boolean prepareVideoRecorder(){
mMediaRecorder = new MediaRecorder();
// Step 1: Unlock and set camera to MediaRecorder
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
// Step 2: Set sources
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
// Step 4: Set output file
mMediaRecorder.setOutputFile(MediaCapture.getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());
// Step 5: Set the preview output
mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
// Step 6: Prepare configured MediaRecorder
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
Log.d(TAG, "IllegalStateException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
} catch (IOException e) {
Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
}
return true;
}
Media Capture:
public static Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(MEDIA_TYPE_VIDEO));
}
/**
* Create a File for saving an image or video
*/
public static File getOutputMediaFile(int type) {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_MOVIES), "MyApplication");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyApplication", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HH:mm:ss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
I too was very perplexed by this behaviour until I realised unplugging the USB was causing the files to appear. This appears to be a bug in Android, possibly related to this one :
https://code.google.com/p/android/issues/detail?id=195362
Clearly, the file has been written correctly, but for some reason the new file is not visible. In any case, the solution/workaround offered in the link above is to force a media scan of your file. e.g.
MediaScannerConnection.scanFile(getContext(), new String[]{this.mediaFile.getAbsolutePath()}, null, null);
Where 'mediaFile' is the file your mediaRecorder has just finished writing. With this in place I do not need to unplug the USB cable to see the file and it appears immediately after recording has finished.
I am running Android 5.0.2 on a Samsung Galaxy A5. This feels more of a workaround than a fix and I can't be sure it will work on other devices or Android versions, but I hope it helps someone.

upload photo to Facebook from Android

I'm trying to upload photo to Facebook from my Android App and it works fine, photo is uploaded, problem is, Facebook app doesn't open, my App simply uploads photo directly to News Feed, but without option to maybe discard it, or change text or antything, so what i would like is to open facebook post with my image attached but not posted until i click the "post"
here is my code :
Bitmap img = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
Request uploadRequest = Request.newUploadPhotoRequest(
Session.getActiveSession(), img, new Request.Callback() {
#Override
public void onCompleted(Response response) {
Toast.makeText(MyActivity.this,
"Photo uploaded successfully",
Toast.LENGTH_LONG).show();
}
});
uploadRequest.executeAsync();
I googled around for hours, and this facebook sdk is messed up, i can't seem to find any proper answer, if i use shareDialog facebook provides, i can't share local images, if i dont use share dialog i can't open facebook app, and i don't want to use OpenGraph stories .. Any help would be gravely appreciated.
You can post imade or text into facebook by using facebook SDK wich is explaned here
and to post an image
private void postImageToWall(String accessToken,byte[] image, String text){
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, accessToken);
//text with the image
params.putString("message",text);
// The byte array is the data of a picture.
params.putByteArray("picture", image);
try {
facebook.request("me/photos", params, "POST");
uploadSucceed = true;
} catch (FileNotFoundException fileNotFoundException) {
showToast(fileNotFoundException.getMessage());
} catch (MalformedURLException malformedURLException) {
showToast(malformedURLException.getMessage());
} catch (IOException ioException) {
showToast(ioException.getMessage());
}
}

Categories

Resources