Saturday, 20 December 2014

How to Deploy HTTPS Correctly

How to Deploy HTTPS Correctly


Internet technologists have always known that HTTP is insecure, causing many risks to users. Because HTTP traffic is unencrypted, any data sent over HTTP can be read and modified by anyone who has access to the network. As revealed by the Snowden NSA surveillance documents, HTTP traffic can also be collected and searched by government agencies without notice to users or webmasters. Given these risks, EFF believes that every website should support HTTPS on all pages as soon as possible.
While HTTPS has long existed as the bare minimum for web security, some websites have been slow to adopt it. In part, this is because correctly and completely serving an application over HTTPS takes some care.
This article is designed to encourage and assist website operators in implementing and improving HTTPS support. Although no precaution will defend against all threats, supporting HTTPS will protect users from a wide range of common attacks.

Background

HTTPS provides three security guarantees:
  1. Server authentication allows users to have some confidence that they are talking to the true application server. Without this guarantee, there can be no guarantee of confidentiality or integrity.
  2. Data confidentiality means that eavesdroppers cannot understand the content of the communications between the user's browser and the web server, because the data is encrypted.
  3. Data integrity means that a network attacker cannot damage or alter the content of the communications between the user's browser and the web server, because they are validated with a cryptographic message authentication code.
HTTP provides no security guarantees, and applications that use it cannot possibly provide users any security. When using a web application hosted via HTTP, people have no way of knowing whether they are talking to the true application server, nor can they be sure attackers have not read or modified communications between the user's computer and the server.

Modes of Attack and Defense

However users connect to the Internet, there are a variety of people who can attack them--whether spying on them, impersonating them, tampering with their communications, or all three of these. The wifi network operator can do this; any ISP in the path between client and server can do it; anyone who can reconfigure the wifi router or another router can do it; and often, anyone else using the same network can do it, too.
Firesheep is an example of a passive network attack: it eavesdrops on the contents of network communications between browser and server, but does not re-route or modify them. Government surveillance programs such as XKeyscore also use passive attacks on HTTP traffic to collect massive amounts of online communication data.
By contrast, other freely-available tools perform active network attacks, in which the attacker does modify the contents of and/or re-route communications. These tools range from serious, such as sslstrip, to silly, like the Upside-Down-Ternet. Although Upside-Down-Ternet is a funny prank, it is technically identical to potentially more damaging attacks such as an attack that injects malicious code or incorrect information into web pages; at the same time, it shows that such attacks are easy enough to be jokes. Free wifi hotspots have been known to inject advertisements dynamically into web pages that users read--indicating that active network attacks are a viable business model. Tools like Cain and Abel enable a range of attacks, including re-routing local network traffic through the attacker's system. (Also see Arpspoof and dsniff.)
Only a mechanism that provides (at least) authentication, confidentiality, and integrity can defend against a range of attacks. HTTPS is currently our best option for web applications.
However, there are some potential pitfalls that site operators must avoid in order to deploy HTTPS securely.

Mixed Content

When hosting an application over HTTPS, there can be no mixed content; that is, all content in the page must be fetched via HTTPS. It is common to see partial HTTPS support on sites, in which the main pages are fetched via HTTPS but some or all of the media elements, stylesheets, and JavaScript in the page are fetched via HTTP.
This is unsafe because although the main page load is protected against active and passive network attack, none of the other resources are. If a page loads some JavaScript or CSS code via HTTP, an attacker can provide a false, malicious code file and take over the page's DOM once it loads. Then, the user would be back to a situation of having no security. This is why all mainstream browsers warn users about pages that load mixed content. Nor is it safe to reference images via HTTP: What if the attacker swapped the Save Message and Delete Message icons in a webmail app?
You must serve the entire application domain over HTTPS. Redirect HTTP requests with HTTP 301 or 302 responses to the equivalent HTTPS resource.
Some site operators provide only the login page over HTTPS, on the theory that only the user's password is sensitive. These sites' users are vulnerable to passive and active attacks.
Unfortunately, many sites today load content from external sites and CDN's that do not support HTTPS. If it's not possible to serve these resources from your own host or another one that supports HTTPS, you should urge these other sites to start supporting HTTPS immediately.

Security and Cookies

As Chris Palmer described in a paper on secure session management for web applications, site operators must scope sensitive cookies (such as cookies used for user authentication) to the secure origin. If a cookie is broadly scoped (with the Domain attribute in the Set-Cookie: header), it may "leak" to other hosts or applications in the same domain--potentially less-secure hosts or applications.
Similarly, the application must set the Secure attribute on the cookie when setting it. This attribute instructs the browser to send the cookie only over secure (HTTPS) transport, never insecure (HTTP).

Use HTTP Strict Transport Security

HTTP Strict Transport Security (HSTS) is an HTTP protocol extension that enables site operators to instruct browsers to expect the site to use HTTPS.
Although not all browsers yet support HSTS, EFF urges those that don't--we're looking especially at you, Apple and Microsoft--to follow the lead Google, Opera, and Mozilla have set by adopting this useful security mechanism. Indeed, ultimately we expect HTTPS (and possibly newer protocols such as SPDY and QUIC) to replace HTTP entirely, the way SSH replaced Telnet and rsh.
As an extra precaution, your site should support HSTS preloading, which prevents interception of an HTTP request if the browser hasn't yet received a valid HSTS header from the server. HSTS preloading is implemented via an opt-in list of domains that is included in Chromium, Google Chrome, and Firefox. See Chromium's page for instructions on getting your site added to this list. Note that you must also send an HSTS header with a max-age greater value than 18 weeks for Firefox to include your site in their HSTS preload list.
We recently enabled HSTS and HSTS preloading for eff.org. It took less than an hour to set up, and we found a way to do it without forcibly redirecting users to HTTPS, so we can state an unequivocal preference for HTTPS access while still making the site available in HTTP. It worked like a charm and a significant fraction of our users are now automatically accessing our site in HTTPS, perhaps without even knowing it.

Choose Strong Protocols and Cipher Suites

Here is a brief list of recommendations for choosing secure protocols and cipher suites in an SSL deployment:
  • Disable support for SSLv2, SSLv3, and TLS 1.0.
  • Support TLS 1.1 and 1.2.
  • Disable NULL, aNULL, and eNULL ciphersuites, which do not offer both encryption and authentication.
  • Use private keys that are at least as secure as a 2048-bit RSA key.
  • Prefer ciphersuites that include ephemeral Diffie-Hellman key exchange. These offer the important property of Perfect Forward Secrecy, which prevents decryption of past web traffic if your SSL private key is compromised in the future.
  • Disable ciphersuites with keys sizes smaller than 128 bits for encryption.
  • Disable ciphersuites that use MD5 for hashing. SHA-1 is also discouraged but may be required for compatibility with TLS 1.0 and SSLv3.
  • Disable ciphersuites that use RC4 for encryption. AES-CBC is preferable to RC4 but vulnerable to the BEAST attack. Thus, AES-GCM is often recommended.
  • Disable TLS compression in order to prevent the CRIME attack.
  • Only support secure TLS renegotiations compliant with RFC 5746, or disable TLS renegotiations entirely.
A useful tool for testing for well-known weaknesses in an existing HTTPS deployment is Qualys's SSL Server Test.

Performance Concerns

Many site operators report that they can't move to HTTPS for performance reasons. However, most people who say this have not actually measured any performance loss, may not have measured performance at all, and have not profiled and optimized their site's behavior. Usually, sites have latency far higher and/or throughput far lower than necessary even when hosting over HTTP--indicating HTTPS is not the problem.
The crux of the performance problem is usually at the content layer, and also often at the database layer. Web applications are fundamentally I/O-bound, after all. Consider this wisdom from the Gmail developers:
First, we listed every transaction between the web browser and Google's servers, starting with the moment the "Sign in" button is pressed. To do this, we used a lot of different web development tools, like Httpwatch, WireShark, and Fiddler, plus our own performance measuring systems. [...]
We spent hours poring over these traces to see exactly what was happening between the browser and Gmail during the sign-in sequence, and we found that there were between fourteen and twenty-four HTTP requests required to load an inbox and display it. To put these numbers in perspective, a popular network news site's home page required about a 180 requests to fully load when I checked it yesterday. But when we examined our requests, we realized that we could do better. We decided to attack the problem from several directions at once: reduce the number of overall requests, make more of the requests cacheable by the browser, and reduce the overhead of each request.
We made good progress on every front. We reduced the weight of each request itself by eliminating or narrowing the scope of some of our cookies. We made sure that all our images were cacheable by the browser, and we consolidated small icon images into single meta-images, a technique known as spriting. We combined several requests into a single combined request and response. The result is that it now takes as few as four requests from the click of the "Sign in" button to the display of your inbox.
Google's Adam Langley provides additional detail:
In order to do this we had to deploy no additional machines and no special hardware. On our production frontend machines, SSL/TLS accounts for less than 1% of the CPU load, less than 10KB of memory per connection and less than 2% of network overhead. Many people believe that SSL takes a lot of CPU time and we hope the above numbers (public for the first time) will help to dispel that. [emphasis in original]
Is it any wonder Gmail performs well, even when using HTTPS exclusively? Site operators can realize incremental improvement by gradually tuning their web applications. Chris gave a presentation to this effect at Web 2.0 Expo 2009.

Conclusion

HTTPS provides the baseline of safety for web application users, and there is no performance- or cost-based reason to stick with HTTP. Web application providers undermine their business models when, by continuing to use HTTP, they enable a wide range of attackers anywhere on the internet to compromise users' information.

Free SSL Certificate


Ideally, every time you visit a website, that connection should happen over a secure HTTPS connection so nobody can snoop on your surfing habits when you are using a public network at a coffee shop or at the airport. But in reality, most smaller websites don’t offer these kind of secure connections because getting the kind of digital public-key certificate that makes HTTPS connections work involves a rather annoying and manual process. They also typically don’t come cheap.
It doesn’t have to be like that, though. Starting soon, Mozilla, Cisco, Akamai, the Electronic Frontier Foundation, IdenTrust and researchers at the University of Michigan are working through the Internet Security Research Group to create a new certificate authority to offer these digital certificates for free to anybody who owns a web domain. The “Let’s Encrypt” group will launch this service next summer.
encrypt-2
Currently, the EFF writes today, “HTTPS (and other uses of TLS/SSL) is dependent on a horrifyingly complex and often structurally dysfunctional bureaucracy for authentication.”
The Let’s Encrypt project aims to make getting certificates not just free, but also as easy as possible. It will take two simple shell commands to enable HTTPS for any given site that wants to use it. All of the certificates that are issues or revoked will be public and the team aims to make its protocols an open standard that other certificate authorities can adopt.
Developers who want to test the service can head over to GitHub to take a look at the code, but this is definitely not meant for production servers yet and if you decide to ignore that warning, chances are your users will see lots of warnings about your certificate that will keep them from ever seeing your site.

Friday, 19 December 2014

Apps Develop








































Monday, 8 December 2014

https://www.fluidui.com/demos

https://www.fluidui.com/demos
http://blogs.telerik.com/kendoui/posts/13-10-01/creating-your-first-hybrid-mobile-application-with-visual-studio

http://www.outsystems.com/forums/discussion/8372/creating-android-hybrid-apps-step-by-step/
http://jaydata.org/tutorials/hybrid-mobile-development-with-jaydata

https://developer.salesforce.com/page/Building_a_Mobile_SDK_Hybrid_App_for_Android
https://doc.ez.no/Tutorials/Building-mobile-browser-and-hybrid-applications-with-eZ-Publish/Creating-a-sample-Hybrid-Mobile-Application

http://xinyustudio.wordpress.com/2014/03/17/android-development-play-youtube-video-in-your-app-cant-play-this-video-and-troubleshooting/

http://www.jayway.com/2013/01/11/understanding-android-hybrid-applications-part-1/


Ready to get started on your own prototype?

jayway

MoSync Reload
Windows 7AndroidApple

Introducing MoSync Reload - native mobile app development using HTML5/JavaScript


Web developers can now easily create apps for all the major platforms in one go, with access to all the advanced features of modern smartphones. Creating compelling apps that work offline and can make use of camera, contacts, location, advanced graphics and much more a has never been easier and faster! 

With MoSync Reload, you develop native mobile apps for iOS, Android and Windows Phone 7 using familiar HTML5/JavaScript technologies, and you can see the effect of your changes instantly on multiple devices, comfortably developing on your desktop platform of choice.

Develop in three easy steps:
Use your favorite editor to create app for iOS, Android and Windows Phone in HTML5
Edit your code
Edit your code using your favorite text editor or IDE, using familiar web HTML, JavaScript and CSS.
transfer your app to your device instantly by just one click
Hit Reload
Instantly transfer your updated code and resources to any number of devices and simulators.
See how you app behaves on multiple devices (iOs, Android, and Windows Phone) at the same time.
Run
See how your application looks and behaves on iOS, Android and Windows Phone7.
See video
Watch the Reload Video
Discover what Reload is and how you can use it to speed up your development process. 
Get the Reload Client from
Develop Native Mobile Apps using HTML5/JavaScript
No need to learn Objective-C, Java or C#. Use your existing web skills, and a set of intuitive APIs to access device features, such as sensors, camera, file system, GPS and more. Debug your app using the new remote debugging features.   
Use Real Native User Interface
Tired of JavaScript frameworks which try to fake a native look and feel, but fail? Use familiar HTML markup to create actual native UI elements with all the responsiveness and polish of a real native app.
Pure Web Development Experience
Used to doing web development by editing some code, then hitting "reload" in a browser? That's exactly what it's like to develop using MoSync Reload, only your code is running on real devices. No build step, no packaging.
Platform Independent Mobile App Development
With MoSync Reload, you can for the first time develop for iOS, Android and WP7 in your desktop environment of choice - Windows, PC or Linux! 

>>>>>>>>>>>>>>>>>>>>>>>>>



Understanding Android Hybrid Applications – Part 1

Introduction

A while ago, me and my friend Martin were invited to speak at the excellent Devoxx Conference in Antwerpen, where we were to give a presentation about hybrid applications in Android. We were delighted to get the chance to explain how hybrid applications really works, for we’ve noticed that it’s a topic that people really don’t know much about? The subject has been lively debated for the past couple of years and there’s an abundance of articles listing the pros and cons of hybrid apps, but, except for a couple of articles explaining the basics, that’s about it. What we really think is missing is a deep dive into the technical details of hybrid applications, where more advanced concepts are discussed. Be aware, that this is not a general, good to know, introduction to hybrid applications in general; it’s an Android centric tutorial that focuses solely on how you can take advantage of web content in Android. 

What we’ll do

This article is based on a simple hybrid application, that we wrote for the Devoxx conference. The goal of this tutorial is to go through the entire application and show you how it’s done. I’ll describe the application with screenshots and simple drawings, and break it down into smaller digestible pieces that we’ll examine and implement. I’ll cover everything from loading web pages and communicating between Android and the web content, to creating a consistent theme and adding css transformations to make the user interface look slick.

The application

The application is a simple image viewer that displays seven images at the same time. Image 1 and Image 2 shows screenshots of what the application’s main screen look like.
Image1. Seven, differently sized, images are displayed. The images are loaded from the device storage and different web pages
Image 2. No action no fun. The application changes the images by rotating them a 180 degrees, along the x-axis. Here, the middle image is being rotated.
Image 3. The full image being displayed together with some clickable icons at the bottom. Clicking one of the icons will bring up a dialog showing additional information about the image, like comments, a map, or wikipedia information.
There are a few things, not obvious at first glance, that are at the core of this application. First of all, the rotating images; have you noticed that the rotation is done in 3D. OK, so what? 3D isn’t exactly rocket science, and it could easily be done using OpenGL. Sure but, assuming that you know OpenGL, isn’t it a bit overkill for a simple application like this to use a technique like OpenGL? That’s where the web can help us. I’m going to do the image rotation using css transformations, which is a simple, hardware accelerated, and well known web technique. Below is an overview of how the css rotation works.
Image 4. One card dissembled into smaller parts. The ‘Card’ is the container, made-up from a simple ‘div‘ tag in html. The Card contains two images, a back- and a front image. Using css, the two images are arranged on top of each other, with the back image turned upside down. When it’s time to rotate the card we simple apply a transformation that will rotate the div tag a 180 degrees. We will discuss the implementation more deeply in part 3.
Secondly, and this is impossible to see from the screenshot, the application is structured using the MVC pattern, where the controller and model is implemented in Android and the view is HTML. For a regular application this is nothing new, but for a web application it will be a bit different.

Application Architecture

As I said, the application is built using the MVC pattern, where the web is the view, and Android represents the controller and model.
Image 5. The application uses the MVC pattern.
This means that all ui operations are implemented in HTML, Javascript, and CSS, while the logic (what picture to show, when to rotate them, etc.) is implemented in Android. When it’s time to change an image, a “command” is sent from Android to the Web component, telling it to update a specific image. This is a simplified description of how it works, but as we progress (part 2 focuses on communication), you will get a better understanding of it.
That’s it, we know enough about the application to get started. Now you know what we are going to do, what it will look like, and how we are going to structure our application. Let’s go on and take a closer look at the Android web component.

Android Web Component

The web component contains four important classes that we will use.
Image 6. The web component consists of four important classes. The WebView is the class that you’ll be working most with, the other three classes are merely customisation points, where you can change the behaviour of the WebView.

WebView

The WebView is a regular Android view, capable of showing web content. The web view contains a wide range of methods, everything from telling the WebView to go back or forward, to capturing pictures of the web content and clearing the cache. The description of the web view might fool you into thinking that it’s a full blown web browser with navigation buttons, history and a reload button. It’s not. The WebView contains the logic for doing all of these things, but there is no user interface, at least not anything resembling what we think of as a browser. The WebView is, simply put, a rectangle containing web content; by default javascript isn’t even enabled and some of the functionality, like alerts, doesn’t work. To remedy this shortcoming, we need to add our own custom WebChromeClient and  WebViewClient. Image 7 shows what a plain vanilla WebView looks like.
Image 7. WebView with our company page loaded.
Below is the code for this masterpiece.
Loading a web page is straight forward, just create a WebView and load a URL. What you don’t see in the above image is that there’s something missing on the page.

WebSettings

Compare the web page, loaded in the previous section, with what it looks like in a real browser.
Image 8. On the right side: what the page looks like in a standard WebView. On the right side: what it should look like.
The two images looks similar but there is one component missing in the image to the left; a javascript image switcher is missing, because a WebView doesn’t support JavaScript out of the box. To remedy this shortcoming we can change our implementation to something like the code below, where we’re using the WebSettings object to turn on JavaScript.
WebSettings contains a large set of methods that you can use to change the behaviour of the WbView; it contains methods that disables all network loading (effectively making sure that your page is only loading local content), adding build in zoom controls, and setting the path to the local web database, just to mention a few of them. For a complete list of WebSettings methods see API

WebViewClient

WebViewClient handles everything that, in some way, is related to the rendering of a page. It lets you add callback methods that is invoked to inform you of changes in the rendering. Start and stop loading, loading specific resources, errors, login, and form resubmissions are typical examples of things that you will be notified of in the WebViewClient.
To add a task for execution, when the page has finished loading, add this:
What if you want to handle errors? Let’s say that you’re trying to connect to a server, how can you know that everything went alright? The code below listens for errors and prints some simple log statements.
The error codes are described in the WebViewClient; you’ll find errors like “ERROR_BAD_URL”, “ERROR_CONNECT”, and “ERROR_TIMEOUT”.
The WebView contains a bunch of other methods that you can implement to get callbacks from the WebView when something happens. Check out the API for more information.

WebChromeClient

It can be difficult to separate the WebViewClient from the WebChromeClient since they both, at least when you start to learn about them, seems to cover the same responsibilities. To keep them apart, think of the WebChromeClient as the class responsible for everything browser UI specific while WebViewClient is responsible for everything that is related to the rendering of the web content.
The WebChromeClient let’s you handle the browser’s visited history, create new windows, take care of alerts, prompts, and console messages. Let’s add some code to handle alerts:
https://gist.github.com/4335589
WebChromeClient and WebViewClient contains a number of methods that your are free to override in order to customise the WebView. A simple application with no requirements on the integration will be fine without overriding any of the methods while a more demanding application will require you to implement all of them.

Summary

In this first post, we’ve learn the basics of the web view and what the different classes are responsible for and how they work. In the next article I will start to implement the main view, containing the seven images.

7 Comments

  1. very good articles, thank you
  2. Hax
    Brilliant article – looking forward to the second part!
  3. Darpan
    Great work, would like to check out next post.
  4. bangdroid
    Good writing.complex content in simple text.waiting for the second part. if possible please provide full source code.
  5. zatziky
    Man, good article but I think you have forgotten to insert the code snippets ;) I can’t see anything in Chrome and neither IE…

How to download the playlist from youtube and play the videos in android

How to download the playlist from youtube and play the videos in android




1)   Click on the link to register your application to get the developer api key
      https://developers.google.com/youtube/v3/




2)    After clicking on the above link click on  Register your application
       this will redirect you to a Google console page


      
       Create a new project

      a) Enter the name of your project and check the term and service box.
      b) Click create after this it will ask to verify your account enter the SMS code
           that you get via SMS

     
 3) After verifying click on APIs under APIs and auth.
     Turn ON the YouTube Analytics API and YouTube Data API v3


  4) Now click on credentials

      In public API access   
      Click create new key  to generate the Android API key 



      For this open your cmd prompt change the location for your current directory to
      C:\Program Files\Java\jdk1.6.0_16\bin>
and type

      
       keytool -v -list -alias androiddebugkey -keystore "Your debug key location" -storepass android 
      -keypass android     

      this will give you the SHA1 fingerprints copy the fingerprints and paste the fingerprints to the API
      Console box with the package name of your project and click create.

5) Now copy the Android API key and save it to some Notepad.

6) Again go to the create new key and generate the Browser API key add some valid url and click 
    on create
   copy the API key and save that key to some Notepad.

7) You Need to download the YouTubeAndroidPlayerApi.jar from this link https://github.com/youtube/yt-direct-lite-android download the Zip extract it and copy the jar from the lib folder to your project lib folder.

8) Now open eclipse create a new project Android Application Project enter the name of project 
    for example
    Youtube and the package name com.example.youtube
    click Next to enter the activity name for example MainActivity
    and then click finish.

9)  In activity_main.xml type the following code

    <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" >

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/videolist"/>

</LinearLayout>

10) Right click on layout folder create new android xml file name it
  a) textvideo.xml type the following code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/tumbhid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="2dp"
        android:paddingLeft="4dp" />

    <TextView
        android:id="@+id/label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="118dp"
        android:textColor="#5D2EE8"
        android:textSize="20sp" >
    </TextView>

</RelativeLayout>

b) full_screendemo.xml  type the following code

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <com.google.android.youtube.player.YouTubePlayerView
        android:id="@+id/player"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:id="@+id/other_views"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical"
        android:background="@android:color/black"
        android:padding="5dp" >
        <CheckBox
            android:id="@+id/landscape_fullscreen_checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:textColor="@android:color/white"
            android:text="@string/landscape_fullscreen" />
    </LinearLayout>
</LinearLayout>

11) Navigate to Values folder open the Strings.xml file and add following values
  
 <string name="error_player">There was an error initializing the YouTubePlayer</string>
 <string name="landscape_fullscreen">Click on check for full screen video in landscape mode</string>
 <string name="enter_fullscreen">Enter Fullscreen</string>


12) Navigate to source folder open the MainActivity.java and type this code

package com.example.youtube;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;
import com.example.youtube.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class MainActivity extends Activity implements OnItemClickListener{

    private ArrayList<Video> videoArrayList;
    private ListView listVideo;
    private VideoAdapter videoAdapter;
    private String auth_token;
    private Video vObject;
    private JsonParser parserVideo;
    private ProgressDialog progress;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listVideo=(ListView)findViewById(R.id.videolist);
        parserVideo=new JsonParser();
        getAuthToken();       
        videoArrayList=new ArrayList<Video>();
        listVideo.setOnItemClickListener(this);
        listVideo.setAdapter(videoAdapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
        // TODO Auto-generated method stub
        // here we are getting the index of listview and through this we are getting the youtube video id
        vObject=videoArrayList.get(position);
        String video=vObject.getVideoId();
        Intent inFullScreenDemo=new Intent(MainActivity.this,FullscreenDemoActivity.class);
        inFullScreenDemo.putExtra("video",video);
        inFullScreenDemo.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK| Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(inFullScreenDemo);   
    }
     ////This method is used to get the auth_token from your gmail sync account////
    public void getAuthToken(){
    AccountManager.get(getApplicationContext()).getAuthTokenByFeatures("com.google", "oauth2:https://gdata.youtube.com", null, this,
                null, null, new AccountManagerCallback<Bundle>() {
        @Override
            public void run(AccountManagerFuture<Bundle> future) {
                try {
                    Bundle bundle = future.getResult();
                    @SuppressWarnings("unused")
                    String acc_name = bundle.getString(AccountManager.KEY_ACCOUNT_NAME);
                    auth_token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                    Log.e("auth_token",auth_token);
                } catch (Exception e) {                   
                    e.printStackTrace();                       
                }
            }
        }, null);   
       new Async().execute(""); 
    }
   
    public ArrayList<Video>parsingJson(String videoUrl){
    try {   
            JSONObject json=parserVideo.getJsonFromYoutube(videoUrl+auth_token);
            JSONArray jArray=new JSONArray(json.getString("items"));
            for(int i=0;i<jArray.length();i++){
                JSONObject thumbnail=jArray.getJSONObject(i);
                JSONObject snippets=thumbnail.getJSONObject("snippet");
                JSONObject defaulturl=snippets.getJSONObject("thumbnails");
                JSONObject url=defaulturl.getJSONObject("high");
                JSONObject resourceId=snippets.getJSONObject("resourceId");
                String videoId=resourceId.getString("videoId");
                String imageurl=url.getString("url");
                String title=snippets.getString("title");
                vObject=new Video(title, imageurl, videoId);
                videoArrayList.add(i,vObject);               
                //Log.e("videoArrayList",""+videoArrayList.size());
            }
        } catch (Exception e) {
            e.printStackTrace();           
        }   
        return videoArrayList;
    }
   
    public void invalidateAccount(){
        AccountManager accountManager = AccountManager.get(MainActivity.this);
        accountManager.invalidateAuthToken("com.google",auth_token);
    }
    ///This class is used to do some background task.
    //Here in this blog, we are using it for parsing the JSON data
    //that we are getting from youtube. 
    public class Async extends AsyncTask<String,String,String>{
        ArrayList<Video> videolist;
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            progress=new ProgressDialog(MainActivity.this);
            progress.setMessage("Loading data...");
            progress.show();
        }
        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            try{
                videolist=parsingJson(parserVideo.url); //through this method we are parsing the data
            }catch (Exception e) {
                // TODO: handle exception
                finish(); //If some exception occur we are killing the application

            }
            return null;
        }
        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            try{
                //videoAdapter class is used to customized the ListView
                videoAdapter=new VideoAdapter(MainActivity.this,videolist,MainActivity.this.getContentResolver(),MainActivity.this.getResources());       
                listVideo.setAdapter(videoAdapter);
                listVideo.setFastScrollEnabled(true);
                progress.dismiss();  // Here we are closing the progress dialog after completing the background task.
            }catch (Exception e) {
                // TODO: handle exception
            }
        }
    }
   
}












13) Right Click to com.example.youtube create new java class name it Video.java and type this code


package com.example.youtube;

public class Video {
    private String videoTitle;
    private String videoThumbnail;
    private String videoId;
    public String getVideoTitle() {
        return videoTitle;
    }
    public void setVideoTitle(String videoTitle) {
        this.videoTitle = videoTitle;
    }
    public String getVideoThumbnail() {
        return videoThumbnail;
    }
    public void setVideoThumbnail(String videoThumbnail) {
        this.videoThumbnail = videoThumbnail;
    }
    public String getVideoId() {
        return videoId;
    }
    public void setVideoId(String videoId) {
        this.videoId = videoId;
    }
    public Video(String videoTitle, String videoThumbnail, String videoId) {
        super();
        this.videoTitle = videoTitle;
        this.videoThumbnail = videoThumbnail;
        this.videoId = videoId;
    }
   
    public Video() {
        super();
    }
    @Override
    public String toString() {
        return "Video [videoTitle=" + videoTitle + ", videoThumbnail="
                + videoThumbnail + ", videoId=" + videoId + "]";
    }
}

14) Right Click to com.example.youtube create new java class name it VideoAdapter.java
      and in Superclass tab type android.widget.ArrayAdapter

package com.example.youtube;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Set;
import com.example.youtube.R;
import com.example.loadimage.ImageLoader;

import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;
public class VideoAdapter extends ArrayAdapter<Video> implements SectionIndexer {

    @SuppressWarnings("unused")
    private final Context context;
    private final ArrayList<Video> itemsArrayList;
    ContentResolver resolver;
    Resources resource;
    HashMap<String, Integer> alphaIndexer;
    String[] sections;
    private ImageLoader imgLoader;

    public VideoAdapter(Context context, ArrayList<Video> itemsArrayList,ContentResolver resolver,Resources resource) {

        super(context, R.layout.textvideo, itemsArrayList);
        this.context = context;
        this.itemsArrayList = itemsArrayList;
        this.resolver=resolver;
        this.resource=resource;

        alphaIndexer = new HashMap<String, Integer>();
        int size = itemsArrayList.size();

        for (int x = 0; x < size; x++) {
            Video s = itemsArrayList.get(x);
            // get the first letter of the store
            String ch = s.getVideoTitle().substring(0, 1);
            // convert to uppercase otherwise lowercase a -z will be sorted
            // after upper A-Z           
            ch = ch.toUpperCase();
            // put only if the key does not exist
            if (!alphaIndexer.containsKey(ch))
                alphaIndexer.put(ch, x);
        }
         imgLoader = new ImageLoader(context);
        Set<String> sectionLetters = alphaIndexer.keySet();
        // create a list from the set to sort
        ArrayList<String> sectionList = new ArrayList<String>(
                sectionLetters);
        Collections.sort(sectionList);
        sections = new String[sectionList.size()];
        sections = sectionList.toArray(sections);
        notifyDataSetChanged();       
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        RelativeLayout alertView;
        //Get the current alert object
        // alerts al = getItem(position);

        //Inflate the view
        if(convertView==null)
        {
            alertView = new RelativeLayout(getContext());
            String inflater = Context.LAYOUT_INFLATER_SERVICE;
            LayoutInflater vi;
            vi = (LayoutInflater)getContext().getSystemService(inflater);
            vi.inflate(R.layout.textvideo, alertView, true);
        }
        else
        {
            alertView = (RelativeLayout) convertView;
        }
        ImageView image=(ImageView)alertView.findViewById(R.id.tumbhid);
        TextView labelView = (TextView) alertView.findViewById(R.id.label);
        imgLoader.DisplayImage(itemsArrayList.get(position).getVideoThumbnail(), R.drawable.ic_launcher, image);
        labelView.setText(itemsArrayList.get(position).getVideoTitle());
        return alertView;
    }

    @Override
    public int getPositionForSection(int section) {
        // TODO Auto-generated method stub
        return alphaIndexer.get(sections[section]);
    }

    @Override
    public int getSectionForPosition(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public Object[] getSections() {
        // TODO Auto-generated method stub
        return sections;
    }
}



15) Right Click to com.example.youtube create new java class name it JsonParser.java
and type this code
    
package com.example.youtube;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.util.Log;

public class JsonParser {
   
    public String url="https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&maxResults=30&playlistId=PLuwvwpFd3r9VCVeEymYcRqmoPVFzJjhZJ&fields=items(contentDetails%2Cetag%2Cid%2Csnippet)%2CnextPageToken&key="ENTER Your Browser API KEY"&access_token=";

//You can change the playlistId
//You can change the maxResults from 30 to 50 only videos can be fetched at a time
//For more detail go to this link https://developers.google.com/youtube/v3/docs/playlistItems/list#try-it

    private static StringBuilder sb;
    private JSONObject jObj;   
   
    public JsonParser() {
        // TODO Auto-generated constructor stub
    }

    public JSONObject getJsonFromYoutube(String url){       
        DefaultHttpClient httpclient = new DefaultHttpClient();
        Log.e("url",url);       
        HttpGet getRequest = new HttpGet(url);
        getRequest.setHeader("Accept", "application/json");
        // Use GZIP encoding
        getRequest.setHeader("Accept-Encoding", "gzip"); //
        try {
            HttpResponse response = (HttpResponse) httpclient
            .execute(getRequest);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                Header contentEncoding = response.getFirstHeader("Content-Encoding");
                if (contentEncoding != null
                        && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                    instream = new GZIPInputStream(instream);
                }
                // convert content stream to a String
                String result = readStream(instream);
                Log.i("JSON", result);
                instream.close();
                jObj = new JSONObject(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jObj;
    }
    private static String readStream(InputStream is) {
        BufferedReader reader;
        try {
            reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);

            sb = new StringBuilder();

            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return sb.toString();
    }
}
















16) Right Click to com.example.youtube create new java class name it DeveloperKey.java and type this code

// Copyright 2012 Google Inc. All Rights Reserved.

package com.example.youtube;

/**
 * Static container class for holding a reference to your YouTube Developer Key.
 */
public class DeveloperKey {

  /**
   * Please replace this with a valid API key which is enabled for the
   * YouTube Data API v3 service. Go to the
   * <a href="https://code.google.com/apis/console/">Google APIs Console</a> to
   * register a new developer key.
   */
  public static final String DEVELOPER_KEY = "Enter your Android API KEY";

}



17) Right Click to com.example.youtube create new java class name it FullscreenDemoActivity.java and  type this code




/*
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.youtube;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import com.example.youtube.R;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

/**
 * Sample activity showing how to properly enable custom fullscreen behavior.
 * <p>
 * This is the preferred way of handling fullscreen because the default fullscreen implementation
 * will cause re-buffering of the video.
 */
public class FullscreenDemoActivity extends YouTubeFailureRecoveryActivity implements
View.OnClickListener,
CompoundButton.OnCheckedChangeListener,
YouTubePlayer.OnFullscreenListener {

    private static final int PORTRAIT_ORIENTATION = Build.VERSION.SDK_INT < 9
    ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
            : ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT;

    private LinearLayout baseLayout;
    private YouTubePlayerView playerView;
    private YouTubePlayer player;
    // private Button fullscreenButton;
    private CompoundButton checkbox;
    private View otherViews;

    private boolean fullscreen;

    private String videoid;

    @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.fullscreen_demo);
        baseLayout = (LinearLayout) findViewById(R.id.layout);
        playerView = (YouTubePlayerView) findViewById(R.id.player);
        // fullscreenButton = (Button) findViewById(R.id.fullscreen_button);
        checkbox = (CompoundButton) findViewById(R.id.landscape_fullscreen_checkbox);
        otherViews = findViewById(R.id.other_views);
        Intent intent=getIntent();
        videoid=intent.getStringExtra("video");
        checkbox.setOnCheckedChangeListener(this);
        // You can use your own button to switch to fullscreen too
        //  fullscreenButton.setOnClickListener(this);

        playerView.initialize(DeveloperKey.DEVELOPER_KEY, this);

        doLayout();
    }

    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
            boolean wasRestored) {
        this.player = player;
        setControlsEnabled();
        // Specify that we want to handle fullscreen behavior ourselves.
        player.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_CUSTOM_LAYOUT);
        player.setOnFullscreenListener(this);
        if (!wasRestored) {
            player.cueVideo(videoid);
        }
    }

    @Override
    protected YouTubePlayer.Provider getYouTubePlayerProvider() {
        return playerView;
    }

    @Override
    public void onClick(View v) {
        //  player.setFullscreen(!fullscreen);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        int controlFlags = player.getFullscreenControlFlags();
        if (isChecked) {
            // If you use the FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE, your activity's normal UI
            // should never be laid out in landscape mode (since the video will be fullscreen whenever the
            // activity is in landscape orientation). Therefore you should set the activity's requested
            // orientation to portrait. Typically you would do this in your AndroidManifest.xml, we do it
            // programmatically here since this activity demos fullscreen behavior both with and without
            // this flag).
            setRequestedOrientation(PORTRAIT_ORIENTATION);
            controlFlags |= YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE;
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
            controlFlags &= ~YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE;
        }
        player.setFullscreenControlFlags(controlFlags);
    }

    private void doLayout() {
        LinearLayout.LayoutParams playerParams =
            (LinearLayout.LayoutParams) playerView.getLayoutParams();
        if (fullscreen) {
            // When in fullscreen, the visibility of all other views than the player should be set to
            // GONE and the player should be laid out across the whole screen.
            playerParams.width = LayoutParams.MATCH_PARENT;
            playerParams.height = LayoutParams.MATCH_PARENT;

            otherViews.setVisibility(View.GONE);
        } else {
            // This layout is up to you - this is just a simple example (vertically stacked boxes in
            // portrait, horizontally stacked in landscape).
            otherViews.setVisibility(View.VISIBLE);
            ViewGroup.LayoutParams otherViewsParams = otherViews.getLayoutParams();
            if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                playerParams.width = otherViewsParams.width = 0;
                playerParams.height = WRAP_CONTENT;
                otherViewsParams.height = MATCH_PARENT;
                playerParams.weight = 1;
                baseLayout.setOrientation(LinearLayout.HORIZONTAL);
            } else {
                playerParams.width = otherViewsParams.width = MATCH_PARENT;
                playerParams.height = WRAP_CONTENT;
                playerParams.weight = 0;
                otherViewsParams.height = 0;
                baseLayout.setOrientation(LinearLayout.VERTICAL);
            }
            setControlsEnabled();
        }
    }

    private void setControlsEnabled() {
        checkbox.setEnabled(player != null
                && getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
        // fullscreenButton.setEnabled(player != null);
    }

    @Override
    public void onFullscreen(boolean isFullscreen) {
        fullscreen = isFullscreen;
        doLayout();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        doLayout();
    }   

}


18)Right Click to com.example.youtube create new java class name it YouTubeFailureRecoveryActivity.java and  type this code

/*
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.youtube;

import com.example.youtube.R;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;

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

/**
 * An abstract activity which deals with recovering from errors which may occur during API
 * initialization, but can be corrected through user action.
 */
public abstract class YouTubeFailureRecoveryActivity extends YouTubeBaseActivity implements
    YouTubePlayer.OnInitializedListener {

  private static final int RECOVERY_DIALOG_REQUEST = 1;

  @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
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == RECOVERY_DIALOG_REQUEST) {
      // Retry initialization if user performed a recovery action
      getYouTubePlayerProvider().initialize(DeveloperKey.DEVELOPER_KEY, this);
    }
  }

  protected abstract YouTubePlayer.Provider getYouTubePlayerProvider();

}

19)  Right click to source folder,Create new package name it com.example.loadimage 
       Create new class in this package name it as ImageLoader.java 
    
 // This class is used to cache the image 

package com.example.loadimage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
//import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.net.ssl.HttpsURLConnection;
import com.example.youtube.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;
public class ImageLoader {
    MemoryCache memoryCache=new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;

    public ImageLoader(Context context){
        fileCache=new FileCache(context);
        executorService=Executors.newFixedThreadPool(5);
    }

    int stub_id = R.drawable.ic_launcher;
    public void DisplayImage(String url, int loader, ImageView imageView)
    {
        stub_id = loader;
        imageViews.put(imageView, url);
        Bitmap bitmap=memoryCache.get(url);
        if(bitmap!=null)
            imageView.setImageBitmap(bitmap);
        else
        {
            queuePhoto(url, imageView);
            imageView.setImageResource(loader);
        }
    }

    private void queuePhoto(String url, ImageView imageView)
    {
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }

    private Bitmap getBitmap(String url)
    {  
        File f=fileCache.getFile(url);

        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;

        //from web
        try {
            Log.e("urll",""+url.toString());

            Bitmap bitmap=null;
            URL imageUrl = new URL(url.toString());
            HttpsURLConnection conn = (HttpsURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is=conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
            ex.printStackTrace();
            return null;
        }
    }

    //decodes image and scales it to reduce memory consumption
    @SuppressWarnings("static-access")
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);

            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }

            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=2;
            Bitmap b=BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
            return b.createScaledBitmap(b,80, 60,true);               
        } catch (FileNotFoundException e) {}
        return null;
    }

    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url=u;
            imageView=i;
        }
    }

    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;
        PhotosLoader(PhotoToLoad photoToLoad){
            this.photoToLoad=photoToLoad;
        }

        @Override
        public void run() {
            if(imageViewReused(photoToLoad))
                return;
            Bitmap bmp=getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if(imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
            Activity a=(Activity)photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        }
    }

    boolean imageViewReused(PhotoToLoad photoToLoad){
        String tag=imageViews.get(photoToLoad.imageView);
        if(tag==null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }

    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;
        public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
        public void run()
        {
            if(imageViewReused(photoToLoad))
                return;
            if(bitmap!=null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }

    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }
}


20) Create new class in the above package (com.example.loadimage) name it as FileCache.java

package com.example.loadimage;
import java.io.File;
import android.content.Context;
public class FileCache {
    private File cacheDir;

    public FileCache(Context context){
        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"youtubeimage");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }

    public File getFile(String url){
        String filename=String.valueOf(url.hashCode());
        File f = new File(cacheDir, filename);
        return f;

    }

    public void clear(){
        File[] files=cacheDir.listFiles();
        if(files==null)
            return;
        for(File f:files)
            f.delete();
    }
}



21)  Create new class in the above package (com.example.loadimage) name it as MemoryCache.java




package com.example.loadimage;

import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import android.graphics.Bitmap;

public class MemoryCache {
    private Map<String, SoftReference<Bitmap>> cache=Collections.synchronizedMap(new HashMap<String, SoftReference<Bitmap>>());

    public Bitmap get(String id){
        if(!cache.containsKey(id))
            return null;
        SoftReference<Bitmap> ref=cache.get(id);
        return ref.get();
    }

    public void put(String id, Bitmap bitmap){
        cache.put(id, new SoftReference<Bitmap>(bitmap));
    }

    public void clear() {
        cache.clear();
    }
}







22) Create new class in the above package (com.example.loadimage) name it as Utils.java



package com.example.loadimage;

import java.io.InputStream;
import java.io.OutputStream;

public class Utils {
    public static void CopyStream(InputStream is, OutputStream os)
    {
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
                int count=is.read(bytes, 0, buffer_size);
                if(count==-1)
                    break;
                os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }
}









23) Open AndroidManifest.xml and type this code

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.youtube"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCOUNT_MANAGER" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.READ_PROFILE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.youtube.MainActivity"
            android:label="@string/app_name"
            android:launchMode="singleInstance" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.youtube.FullscreenDemoActivity"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:screenOrientation="sensor" >
        </activity>
    </application>

</manifest>


24) Your done now compile your project and run it.



>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


Second Project
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>




Android development: Play Youtube video in your app, “Can’t play this video” and troubleshooting

17 Mar
 
 
 
 
 
 
1 Votes

Playing Youtube video in your app is a frequently requested feature, and some time ago, it is trivial to do this using VideoView:
image
In the layout file, add below:
<VideoView
     android:id=@+id/videoView1
     android:layout_width=match_parent
     android:layout_height=wrap_content />

And in the Activity’s onCreate() function, add below code:
final VideoView mVideoView = (VideoView) findViewById(R.id.videoView1);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(mVideoView);
mVideoView.setMediaController(mediaController);
mVideoView.setVideoPath(“https://http://www.youtube.com/watch?v=XSMOykMIO3c“);
mVideoView.requestFocus();
mVideoView.setOnPreparedListener(new OnPreparedListener() {
    public void onPrepared(MediaPlayer mp) {
    mVideoView.start();
}});
Well this is the implementation that works some time ago, but it might no longer works as expected, and you are likely to get a “Can’t play this video.” error, as shown above:
To solve this, a recommended approach is to use YouTube Android Player API, which seems to be very involved to use, but actually it is not!
To illustrate this, I will not go through the process sequentially, but rather dive in directly to show how to use it first, and how easy it is, assuming you have got everything installed (which scared most users and make it feel like very heavy and unwieldy):
Create new project with an empty Activity
1. In the layout XML, add below code:
<com.google.android.youtube.player.YouTubePlayerView
            android:id=@+id/videoView1
            android:layout_width=match_parent
            android:layout_height=wrap_content />
2. In the YourActivity.Java class, change the base class from Acitivity to YouTubeBaseActivity:
public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener
3. In the onCreate() function in your activity, add below code:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    YouTubePlayerView youTubeView = (YouTubePlayerView)
                     findViewById(R.id.videoView1);
    youTubeView.initialize(DeveloperKey.DEVELOPER_KEY, this);
}

Here you need a developer key, which is saved in the static class DeveloperKey:
public class DeveloperKey {
       /**
       * Please replace this with a valid API key which is enabled for the
       * YouTube Data API v3 service. Go to the
       * <a href=”https://code.google.com/apis/console/“>Google APIs Console</a> to
       * register a new developer key.
       */
       public static final String DEVELOPER_KEY = “abcdedefghijklmnopqrstuvwxyz”;
}
4. Implement the interface YouTubePlayer.OnInitializedListener:
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
             YouTubePlayer player, boolean wasRestored) {
         if (!wasRestored) player.cueVideo(“XSMOykMIO3c”); // your video to play
}
@Override
public void onInitializationFailure(Provider arg0,
            YouTubeInitializationResult arg1){
}
5. In AndroidManfest.xml, add below code:      

<uses-permission android:name=”android.permission.INTERNET” />
Compile and run it on your android device, yeah! That is it!
image
That said, once you get the developer API key, playing the video seems no harder than the VideoView! I will not cover how to get an API key here, which has been covered here in detail.
This is the simplest use of many features Google Youtube API, you might be interested in getting more from the examples. For instance, you may make your activity implement YouTubeFailureRecoveryActivity, which deals with recovering from errors that may occur during API initialization, but can be corrected through user action.
Yes, no fear, it is quite straightforward, abandon your VideoView, say goodbye to “Can’t play this video”! Happy coding..

>>>>>>>>>>>>>>>>>>

Right now I am getting the information of a youtube video by using the Data API Protocol Visiting this url displays the information I need, but its much too slow for doing a dozen queries. It takes around 10 seconds to get 24 videos.
Is there a way to send multiple queries in 1 request or another method for getting the information faster? Right now I am only using this to get the ratings.
https://gdata.youtube.com/feeds/api/videos/[video id]