I would like to interact with YouTube app on android.
My app is basically a service that is running all the time.
I wanna detect if user was watching YouTube and then lock the phone, when he come back the last watched video should continue playing.
Any suggestions? Where to start?
I am thinking to implement a software touch on play button. Is there any other way to do it?
Here is how you can force a video:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://" + id));
startActivity(intent);
Obtaining the Android API Key
First we need to get the SHA-1 fingerprint on your machine using java keytool. Execute the below command in cmd/terminal to get the SHA-1 fingerprint.
Go to Google Developer Console and select or create a new project.
On the left sidebar, select APIs under APIs & auth and turn the status ON for YouTube Data API v3.
On the left sidebar, select Credentials and Create new key under Public API acess.
When popup comes asking you to choose platform, select Android Key.
Paste the SHA-1 key and your project’s package name separated by semicolon(;).
Click on create. Now you should see the API KEY on the dashboard.
public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_DIALOG_REQUEST = 1;
// YouTube player view
private YouTubePlayerView youTubeView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
// Initializing video player with developer key
youTubeView.initialize(Config.DEVELOPER_KEY, this);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format(
getString(R.string.error_player), errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
// loadVideo() will auto play video
// Use cueVideo() method, if you don't want to play it automatically
player.loadVideo(Config.YOUTUBE_VIDEO_CODE);
// Hiding player controls
player.setPlayerStyle(PlayerStyle.CHROMELESS);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(Config.DEVELOPER_KEY, this);
}
}
private YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.youtube_view);
}
}
Related
When I pass youtube ID from recycleview onClick then it shows "This video is unavailable". But same video id works fine when I hard code it. I tried every possible way but could not find any solution. Please, help if anyone can.
This is the code for sending video key,
intent.putExtra("vUrl", adListModel.getUrl());
Getting the video key,
vUrl = getIntent().getStringExtra("vUrl");
Here, I am trying to load video from the video key,
youTubePlayerView.initialize(getResources().getString(R.string.google_api_key), new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
String videoId = vUrl;
Log.e("YOUTUBE_KEYS", videoId);
youTubePlayer.cueVideo(videoId);
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
youTubePlayer.play();
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
});
I'm trying to embed a live stream to android app. This code works perfect for other videos but when I put the URL code of live stream channel it is unable to load. It just keeps on loading. Suggest me something or is there any other API which I need to use for embedding live stream.
onInitializedListener = new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.("5kbU-C0FxqA");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
};
First video id out-of-date so you need to replace another one and check agein
Also i think your code should be like below
onCreate
YouTubePlayerView youTubePlayerView = findViewById(R.id.youtube_player);
youTubePlayerView.initialize(getString(R.string.google_developer_api_key), this);
OnInitializedListener
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo(""); // your video id
youTubePlayer.play();
}
If you can't make it work with the YouTubePlayer API, you may consider using this alternative player: android-youtube-player.
This is all you need to do to play a live video:
Add the player to your XML:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.pierfrancescosoffritti.androidyoutubeplayer.player.YouTubePlayerView
android:id="#+id/youtube_player_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Initialize the player and play a video:
YouTubePlayerView youtubePlayerView = findViewById(R.id.youtube_player_view);
getLifecycle().addObserver(youtubePlayerView);
youtubePlayerView.getPlayerUIController().enableLiveVideoUI(true);
youtubePlayerView.initialize(new YouTubePlayerInitListener() {
#Override
public void onInitSuccess(#NonNull final YouTubePlayer initializedYouTubePlayer) {
initializedYouTubePlayer.addListener(new AbstractYouTubePlayerListener() {
#Override
public void onReady() {
String videoId = "2ccaHpy5Ewo";
initializedYouTubePlayer.loadVideo(videoId, 0);
}
});
}
}, true);
You can see a working example in the sample app.
I'm trying to implement WeChat InApp payments in our app. But we are struggling to make it work.
I will try to sum it up real quick.
Given user is not logged in, WeChat login screen show up every time.
Given user is logged in, when clicked on pay button for a first time, WeChat order info screen shows up, but when clicked back, and clicked on pay button again (in our app), WeChat screen doesn’t show up.
We did implemented WXPayEntryActivity but neither onCreate, onNewIntent nor onResp are called. And yes, this activity is sending broadcast but neither toast nor log shows up.
I tried call registerApp on application started, I tried it just before creating payment req.
Did anybody come across this issue?
Can WeChat help me directly?
Want to see some code?
This is my payment class
public class WXInAppPayment {
public void startPayment(AppCompatActivity activity, PaymentDataResponse data) {
IWXAPI api = getApi(activity);
if (api.isWXAppInstalled()) {
api.sendReq(getPayRequest(data));
} else {
// Showing toast
}
}
public WXReceiver getReceiver() {
// returning BR for wechat payments
return new WXReceiver();
}
public IntentFilter getIntentFilter() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Constants.WE_CHAT_BR_ID);
return intentFilter;
}
private IWXAPI getApi(AppCompatActivity activity) {
final IWXAPI api = WXAPIFactory.createWXAPI(activity, null);
api.registerApp(Constants.WE_CHAT_APP_ID);
return api;
}
private PayReq getPayRequest(PaymentDataResponse data) {
PayReq request = new PayReq();
request.appId = dataFromAPI.appId;
request.partnerId = dataFromAPI.partnerId;
request.prepayId = dataFromAPI.prepayId;
request.packageValue = dataFromAPI.packageValue;
request.nonceStr = dataFromAPI.nonceStr;
request.timeStamp = dataFromAPI.timestimeStampamp;
request.sign = dataFromAPI.sign;
return request;
}
}
And this is WXPayEntryActivity. In manifest:
<activity android:name=".wxapi.WXPayEntryActivity"
android:label="#string/app_name"
android:exported="true"/>
And class:
public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
private final String TAG = getClass().getSimpleName();
private IWXAPI api;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
api = WXAPIFactory.createWXAPI(this, Constants.WE_CHAT_APP_ID);
api.handleIntent(getIntent(), this);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
api.handleIntent(intent, this);
}
#Override
public void onReq(BaseReq baseReq) {
Log.e(TAG, "onReq: " + baseReq.transaction);
}
#Override
public void onResp(BaseResp baseResp) {
Log.e(TAG, "onResp: " + baseResp.errStr + " " + baseResp.errCode);
Intent intent = new Intent(Constants.WE_CHAT_BR_ID);
intent.putExtra("error_code", baseResp.errCode);
intent.putExtra("error_string", baseResp.errStr);
sendBroadcast(intent);
finish();
}
}
I went through same issue... Your code look fine.
lets cover the scenario:
This is normal ... if user is not logged in.. Wechat App will
redirect to login screen
"Only first time payment passed" happened due to wrong packageName. consider these checks:
You need to use ApplicationId not packageName
WhiteSpace
Debug buildType by default has suffix: .debug to applicatonId
Check AppSign which is MD5 of cert you sign with.. Be careful not to use the default one for debug buildType.
Try to reassign ApplicationId and AppSign it again.(that was our issue 😞) due to hidden WS not visible.
Contact Wechat team support.. they have logs to payment.
I am beginner in android and developing an app in which i am using YouTubePlayer API in order to show Youtube Videos of specific Playlist. I'm succeed in doing so. But what I want is that whenever the user selects any video from that playlist; the video should be played in Full Screen. Here is my code:
public class Main4Activity extends AppCompatActivity
{
Toolbar main_toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
main_toolbar=(Toolbar) findViewById(R.id.my_thirdtoolbar);
setSupportActionBar(main_toolbar);
getSupportActionBar().setTitle(R.string.my_tb_title);
getSupportActionBar().setIcon(R.drawable.tblogo);
OnClickButtonListener();
}
public void OnClickButtonListener()
{
Button youtubebtn = (Button) findViewById(R.id.button8);
youtubebtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String PLAYLIST_ID = "PLXRActLQ03oY_6AQb-5EMuKFYQA_fDE40";
Intent intent=YouTubeIntents.createOpenPlaylistIntent(Main4Activity.this,PLAYLIST_ID);
startActivity(intent);
}
}
);
}
}
You can use methods from YouTubeIntents. Here are some methods that you can use:
canResolvePlayVideoIntentWithOptions (Context context)
Checks if the YouTube application installed on the user's device supports the fullscreen and finishOnEnd optional parameters when resolving a play video intent.
If this method returns true, then your application can call the createPlayVideoIntentWithOptions(Context context, String videoId, boolean fullscreen, boolean finishOnEnd) method which creates an Intent that, when resolved, will start playing the video specified by videoId, within the YouTube application.
If this method returns false, then your application should call the createPlayVideoIntent(Context context, String videoId) method instead.
Additionally, please also check other implementations and try the suggested solutions in this SO post. Hope it helps!
Few days back I asked question Youtube API v2 not supported So as per youtube they have deprecated and all application and websites using this v2 api wont work at all. As they told to migrate to v3 there are any good example or documents for android. I have youtube url with video id. I just want to play videos using this api
You can use Video ID to play video...
Use YouTubePlayerView for that...
Let me show you a example which will makes everything clear....
below is a class which contains a YouTubePlayerView..
public class Play_youtube_video extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener
{
YouTubePlayerView video_player;
public static String VIDEO_ID = "";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// HIDE THE KEYBOARD
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
// TITLE BAR DISABLES AND FULL SCREEN IMPLEMENTATION
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_play_youtube_video);
try
{
System.out.println("youtube----VIDEO_ID---->" + VIDEO_ID);
video_player = (YouTubePlayerView) findViewById(R.id.youtubeplayerview_full_screen);
video_player.initialize(GlobalConstant.YOUTUBE_APIKEY, Play_youtube_video.this);
}
catch(Exception e)
{
e.printStackTrace();
}
catch(OutOfMemoryError e)
{
e.printStackTrace();
}
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult result)
{
GlobalUtills.showToast("Youtube player not found.", Play_youtube_video.this);
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored)
{
if( !wasRestored )
{
player.loadVideo(Youtube_VIDEO_ID);
// player.setFullscreen(true);
// player.play();
}
}
public void closeYoutube(View v)
{
Play_youtube_video.this.finish();
}
}
I am answering this question because after some frustration it was not on android api related issue but Gdata youtube api i was using was returning wrong results.
Now its fixed.