Example to use YouTubePlayerFragment of YouTube Android Player API

Example to use YouTubePlayerFragment of YouTube Android Player API

Example to use YouTubePlayerFragment of YouTube Android Player API


Follow the step in "YouTube Android Player API step-by-step" to Download and import YouTube Android Player API, and Register your app using YouTube Android Player API and obtain API Key. To use YouTubePlayerFragment, you have to define android:minSdkVersion="11" or higher in your AndroidManifest.xml.

Modify /res/layout/activity_main.xml to define layout, with <fragment> of "com.google.android.youtube.player.YouTubePlayerFragment".
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >

<fragment
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:id="@+id/youtubeplayerfragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold"
android:layout_gravity="center_horizontal"
android:autoLink="web" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<Button
android:id="@+id/btnviewfullscreen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="View in Full Screen" />
<TextView
android:id="@+id/videolog"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>
</ScrollView>

</LinearLayout>


Create /res/layout-land/activity_main.xml to define layout in Landscape orientation.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="horizontal"
tools:context=".MainActivity" >

<fragment
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:id="@+id/youtubeplayerfragment"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold"
android:layout_gravity="center_horizontal"
android:autoLink="web" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/btnviewfullscreen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="View in Full Screen" />
<TextView
android:id="@+id/videolog"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
</LinearLayout>
</LinearLayout>


MainActivity.java
package com.example.androidyoutubeapiplayer;

import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.PlaybackEventListener;
import com.google.android.youtube.player.YouTubePlayerFragment;
import com.google.android.youtube.player.YouTubePlayer.PlayerStateChangeListener;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{

public static final String API_KEY = "AIzaSyCe6tORd9Ch4lx-9Ku5SQ476uS9OtZYsWA";
public static final String VIDEO_ID = "o7VVHhK9zf0";

private YouTubePlayer youTubePlayer;
private YouTubePlayerFragment youTubePlayerFragment;
private TextView textVideoLog;
private Button btnViewFullScreen;

private static final int RQS_ErrorDialog = 1;

private MyPlayerStateChangeListener myPlayerStateChangeListener;
private MyPlaybackEventListener myPlaybackEventListener;

String log = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

youTubePlayerFragment = (YouTubePlayerFragment)getFragmentManager()
.findFragmentById(R.id.youtubeplayerfragment);
youTubePlayerFragment.initialize(API_KEY, this);

textVideoLog = (TextView)findViewById(R.id.videolog);

myPlayerStateChangeListener = new MyPlayerStateChangeListener();
myPlaybackEventListener = new MyPlaybackEventListener();

btnViewFullScreen = (Button)findViewById(R.id.btnviewfullscreen);
btnViewFullScreen.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
youTubePlayer.setFullscreen(true);
}});
}

@Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {

if (result.isUserRecoverableError()) {
result.getErrorDialog(this, RQS_ErrorDialog).show();
} else {
Toast.makeText(this,
"YouTubePlayer.onInitializationFailure(): " + result.toString(),
Toast.LENGTH_LONG).show();
}
}

@Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {

youTubePlayer = player;

Toast.makeText(getApplicationContext(),
"YouTubePlayer.onInitializationSuccess()",
Toast.LENGTH_LONG).show();

youTubePlayer.setPlayerStateChangeListener(myPlayerStateChangeListener);
youTubePlayer.setPlaybackEventListener(myPlaybackEventListener);

if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}

}

private final class MyPlayerStateChangeListener implements PlayerStateChangeListener {

private void updateLog(String prompt){
log += "MyPlayerStateChangeListener" + "\n" +
prompt + "\n\n=====";
textVideoLog.setText(log);
};

@Override
public void onAdStarted() {
updateLog("onAdStarted()");
}

@Override
public void onError(
com.google.android.youtube.player.YouTubePlayer.ErrorReason arg0) {
updateLog("onError(): " + arg0.toString());
}

@Override
public void onLoaded(String arg0) {
updateLog("onLoaded(): " + arg0);
}

@Override
public void onLoading() {
updateLog("onLoading()");
}

@Override
public void onVideoEnded() {
updateLog("onVideoEnded()");
}

@Override
public void onVideoStarted() {
updateLog("onVideoStarted()");
}

}

private final class MyPlaybackEventListener implements PlaybackEventListener {

private void updateLog(String prompt){
log += "MyPlaybackEventListener" + "\n-" +
prompt + "\n\n=====";
textVideoLog.setText(log);
};

@Override
public void onBuffering(boolean arg0) {
updateLog("onBuffering(): " + String.valueOf(arg0));
}

@Override
public void onPaused() {
updateLog("onPaused()");
}

@Override
public void onPlaying() {
updateLog("onPlaying()");
}

@Override
public void onSeekTo(int arg0) {
updateLog("onSeekTo(): " + String.valueOf(arg0));
}

@Override
public void onStopped() {
updateLog("onStopped()");
}

}

}

download filesDownload the files.

Download APK to try on your device.



The tutorial: YouTube Android Player API step-by-step

Embed html using Google Maps JavaScript API v3 in Android App

The Google Maps Javascript API Version 3 is now the official Javascript API. Version 2 of this API has been officially deprecated as per our deprecation policy.

The Google Maps Javascript API lets you embed Google Maps in your own web pages. Version 3 of this API is especially designed to be faster and more applicable to mobile devices, as well as traditional desktop browser applications.

The API provides a number of utilities for manipulating maps (just like on the http://maps.google.com web page) and adding content to the map through a variety of services, allowing you to create robust maps applications on your website.

The JavaScript Maps API V3 is a free service, available for any web site that is free to consumers. Please see the terms of use for more information.




It's easy to embed WebView, load with HTML using Google Maps JavaScript API v3, in Android App:



Create /assets/simplemap.html, copy from Simple Map example in Google Maps JavaScript API v3, html code with Google Maps JavaScript API v3.
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}

google.maps.event.addDomListener(window, 'load', initialize);

</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>


Modify /res/layout/activity_main.xml, to add <WebView> in layout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold"
android:layout_gravity="center_horizontal"
android:autoLink="web" />
<WebView
android:id="@+id/mybrowser"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</LinearLayout>


MainActivity.java
package com.example.androidsimplemap;

import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebView;

public class MainActivity extends Activity {

WebView myBrowser;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

myBrowser = (WebView)findViewById(R.id.mybrowser);
myBrowser.loadUrl("file:///android_asset/simplemap.html");
myBrowser.getSettings().setJavaScriptEnabled(true);
}

}


Note that, in order for your Activity to access the Internet and load web pages in a WebView, you must add the INTERNET permissions to your Android Manifest file:

<uses-permission android:name="android.permission.INTERNET"/>



add@2014-05-22:

download filesDownload the files.

Download and try the APK.

Free eBook: First preview: Programming Windows Store Apps with HTML, CSS, and JavaScript, Second Edition

Microsoft Press provide a First Preview of the upcoming second edition of Kraig Brockschmidt’s Programming Windows Store Apps with HTML, CSS, and JavaScript!

First preview: Programming Windows Store Apps with HTML, CSS, and JavaScript, Second Edition

The 255-page PDF itself can be downloaded here: http://aka.ms/SecondEdition/FirstPreview (5.57 MB)

FYI, EPUB and MOBI for the ebook’s final release will be provided, not for the two preliminary releases.

Also, please remember that this material is in DRAFT form. This content will not be final until the ebook’s final release.

Source: Microsoft Press Blog

Force YouTube Android Player to run in full screen mode

TO force YouTube Android Player to run in full screen mode, simple call setFullscreen(true) method of the YouTubePlayer object.

Force YouTube Android Player to run in full screen mode


Modify from last exercise "Handle player state changes and playback events, by implementing PlayerStateChangeListener and PlaybackEventListener.", to add a Button in layout, to force running in Full Screen mode.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold"
android:layout_gravity="center_horizontal"
android:autoLink="web" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<com.google.android.youtube.player.YouTubePlayerView
android:id="@+id/youtubeplayerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp" />
<Button
android:id="@+id/btnviewfullscreen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="View in Full Screen" />
<TextView
android:id="@+id/videolog"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>
</ScrollView>

</LinearLayout>


Force running in Full Screen mode by calling youTubePlayer.setFullscreen(true).
package com.example.androidyoutubeapiplayer;

import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.PlaybackEventListener;
import com.google.android.youtube.player.YouTubePlayerView;
import com.google.android.youtube.player.YouTubePlayer.PlayerStateChangeListener;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{

public static final String API_KEY = "AIzaSyCe6tORd9Ch4lx-9Ku5SQ476uS9OtZYsWA";
public static final String VIDEO_ID = "o7VVHhK9zf0";

private YouTubePlayer youTubePlayer;
private YouTubePlayerView youTubePlayerView;
private TextView textVideoLog;
private Button btnViewFullScreen;

private static final int RQS_ErrorDialog = 1;

private MyPlayerStateChangeListener myPlayerStateChangeListener;
private MyPlaybackEventListener myPlaybackEventListener;

String log = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

youTubePlayerView = (YouTubePlayerView)findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);

textVideoLog = (TextView)findViewById(R.id.videolog);

myPlayerStateChangeListener = new MyPlayerStateChangeListener();
myPlaybackEventListener = new MyPlaybackEventListener();

btnViewFullScreen = (Button)findViewById(R.id.btnviewfullscreen);
btnViewFullScreen.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
youTubePlayer.setFullscreen(true);
}});
}

@Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {

if (result.isUserRecoverableError()) {
result.getErrorDialog(this, RQS_ErrorDialog).show();
} else {
Toast.makeText(this,
"YouTubePlayer.onInitializationFailure(): " + result.toString(),
Toast.LENGTH_LONG).show();
}
}

@Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {

youTubePlayer = player;

Toast.makeText(getApplicationContext(),
"YouTubePlayer.onInitializationSuccess()",
Toast.LENGTH_LONG).show();

youTubePlayer.setPlayerStateChangeListener(myPlayerStateChangeListener);
youTubePlayer.setPlaybackEventListener(myPlaybackEventListener);

if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}

}

private final class MyPlayerStateChangeListener implements PlayerStateChangeListener {

private void updateLog(String prompt){
log += "MyPlayerStateChangeListener" + "\n" +
prompt + "\n\n=====";
textVideoLog.setText(log);
};

@Override
public void onAdStarted() {
updateLog("onAdStarted()");
}

@Override
public void onError(
com.google.android.youtube.player.YouTubePlayer.ErrorReason arg0) {
updateLog("onError(): " + arg0.toString());
}

@Override
public void onLoaded(String arg0) {
updateLog("onLoaded(): " + arg0);
}

@Override
public void onLoading() {
updateLog("onLoading()");
}

@Override
public void onVideoEnded() {
updateLog("onVideoEnded()");
}

@Override
public void onVideoStarted() {
updateLog("onVideoStarted()");
}

}

private final class MyPlaybackEventListener implements PlaybackEventListener {

private void updateLog(String prompt){
log += "MyPlaybackEventListener" + "\n-" +
prompt + "\n\n=====";
textVideoLog.setText(log);
};

@Override
public void onBuffering(boolean arg0) {
updateLog("onBuffering(): " + String.valueOf(arg0));
}

@Override
public void onPaused() {
updateLog("onPaused()");
}

@Override
public void onPlaying() {
updateLog("onPlaying()");
}

@Override
public void onSeekTo(int arg0) {
updateLog("onSeekTo(): " + String.valueOf(arg0));
}

@Override
public void onStopped() {
updateLog("onStopped()");
}

}

}


download filesDownload the files.

Download APK to try on your device.



The Tutorial: YouTube Android Player API step-by-step

Android Studio 0.1.8 just released

Android Studio 0.1.8 just released to address several bugs in 0.1.7 around gradle builds. In addition, there are the following changes:
  • Support for running instrumentation tests on device. Tests should be created in the folder "src/instrumentTest/java" (of the main application or a library) following the conventions described at http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Testing
    • To run them, simply right click on the test and click on Run as type Android Junit test.
    • You can also create a new run configuration of type "Android Test" and specify whether you want to run all the tests in a module, package, class or just a single test.
    • NOTE: Debugging tests will be supported in the next release
  • 0.1.8 also comes with a brand new implementation of a resource manager in the IDE, used for layout preview, editor resource folding, etc. This should address many bugs reported in earlier versions (such as @id attributes not being handled properly in RelativeLayouts, bugs with opening layouts after making edits, etc, and should be more performant.
  • New lint check validating device admin receivers

Details: Android Tools Project Site - Android Studio 0.1.8 Released

Adding a Backend to Your App In Android Studio

Posted by Sachin Kotwani, Google Cloud Platform team

Android Studio lets you easily add a cloud backend to your application, right from your IDE. A backend allows you to implement functionality such as backing up user data to the cloud, serving content to client apps, real-time interactions, sending push notifications through Google Cloud Messaging for Android (GCM), and more. Additionally, having your application’s backend hosted on Google App Engine means that you can focus on what the cloud application does, without having to worry about administration, reliability or scalability.



When you create a backend using Android Studio, it generates a new App Engine application under the same project, and gives your Android application the necessary libraries and a sample activity to interact with that backend. Support for GCM is built-in, making it easy to sync data across multiple devices. Once you've generated the project, you can build and run your client and server code together, in a single environment, and even deploy your backend code right from Android Studio.



In this post we’ll focus on how to get started with the basic setup. From there it's easy to extend the basic setup to meet your needs.









Preliminary setup



Before you get started, make sure you take care of these tasks first:



  • Download Android Studio if you haven’t done so already and set it up.

  • Make sure you have an application project set up in Android Studio. You can use any working app that you want to integrate with your backend, even a sample app.

  • If you'll be running the app on an emulator, download the Google APIs Addon from the SDK Manager and run your app on that image.



  • Create a Google Cloud Platform project: In the Cloud Console, create a new project (or reuse an old one) and make note of the Project ID. Click on the words “Project ID” on the top left to toggle to the Project Number. Copy this as well.

  • Enable GCM and obtain API Key: In the Cloud Console, click on APIs and turn on the Google Cloud Messaging for Android API. Then, click on the “Register App” button on the top left, enter a name for the app, then select “Android” and “Accessing APIs via a web server”. In the resulting screen, expand the “Server Key” box and copy the API key.




1. Generate an App Engine project



In Android Studio, open an existing Android application that you want to modify, or create a new one. Select the Android app module under the Project node. Then click Tools > Google Cloud Endpoints > Create App Engine Backend.



In the wizard, enter the Project ID, Project Number, and API Key of your Cloud project.





This will create:



  • An App Engine project which contains the backend application source

  • An endpoints module with a RegisterActivity class, related resources, and client libraries for the Android app to communicate with the backend



The generated App Engine application (<app_name>-AppEngine) is an Apache Maven-based project. The Maven pom.xml file takes care of downloading all the dependencies, including the App Engine SDK. This module also contains the following:



  • A Google Cloud Endpoint (DeviceInfoEndpoint.java, auto-generated from DeviceInfo.java) that your Android app will “register” itself through. Your backend will use that registration info to send a push notification to the device.

  • A sample endpoint, MessageEndpoint.java, to list previously sent GCM messages and send new ones.

  • A starter web frontend application (index.html in webapp directory) that will show all the devices that have registered with your service, and a form to send them a GCM notification.



The endpoints module (<app_name>-endpoints) generated for you contains the classes and libraries needed by the Android application to interact with the backend:



  • A RegisterActivity.java class that, when invoked, will go through the GCM registration flow and also register itself with the recently created backend through DeviceInfoEndpoint.

  • Client libraries, so that the application can talk to the backend using an object rather than directly using raw REST calls.

  • XML files related to the newly created activity.



2. Add GCM registration to your app



In your Android application, you can call RegisterActivity whenever you want the registration to take place (for example, from within the onCreate() method of your main activity.



...
import android.content.Intent;
...

@Override
protected void onCreate(Bundle savedInstanceState) {
...
Intent intent = new Intent(this, RegisterActivity.class);
startActivity(intent);
}



3. Deploy the sample backend server



When you're ready to deploy an update to your ( the sample ) production backend in the cloud, you can do that easily from the IDE. Click on the “Maven Projects” button on the right edge of the IDE, under Plugins > App Engine, right-click and run the appengine:update goal.





As soon as the update is deployed, you can also access your endpoints through the APIs Explorer at http://<project-id>.appspot.com/_ah/api/explorer.






For testing and debugging, you can also run your backend server locally without having to deploy your changes to the production backend. To run the backend locally, just set the value of LOCAL_ANDROID_RUN to true in CloudEndpointUtils.java in the App Engine module.



4. Build and run the Android app



Now build and run your Android app. If you called RegisterActivity from within your main activity, the device will register itself with the GCM service and the App Engine app you just deployed. If you are running the app on an emulator, note that GCM functionality requires the Google APIs Addon image, which you can download from the SDK Manager.



You can access your sample web console on any browser at http://<project-id>.appspot.com. There, you will see that the app you just started has registered with the backend. Fill out the form and send a message to see GCM in action!



Extending the basic setup



It's easy to expand your cloud services right in Android Studio. You can add new server-side code and through Android Studio instantly generate your own custom endpoints to access those services from your Android app.



Handle player state changes and playback events, by implementing PlayerStateChangeListener and PlaybackEventListener.

To keep track with events and states of Android YouTubePlayer, implement PlayerStateChangeListener and PlaybackEventListener.

Handle player state changes and playback events


Modify from last exercise "Handle initialization error YouTube API Service".

Modify activity_main.xml to add a TextView in layout, to display our log.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold"
android:layout_gravity="center_horizontal"
android:autoLink="web" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<com.google.android.youtube.player.YouTubePlayerView
android:id="@+id/youtubeplayerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp" />
<TextView
android:id="@+id/videolog"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>
</ScrollView>

</LinearLayout>


Modify MainActivity.java, to implement PlayerStateChangeListener and PlaybackEventListener.
package com.example.androidyoutubeapiplayer;

import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.PlaybackEventListener;
import com.google.android.youtube.player.YouTubePlayerView;
import com.google.android.youtube.player.YouTubePlayer.PlayerStateChangeListener;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{

public static final String API_KEY = "AIzaSyCe6tORd9Ch4lx-9Ku5SQ476uS9OtZYsWA";
public static final String VIDEO_ID = "o7VVHhK9zf0";

private YouTubePlayer youTubePlayer;
private YouTubePlayerView youTubePlayerView;
private TextView textVideoLog;

private static final int RQS_ErrorDialog = 1;

private MyPlayerStateChangeListener myPlayerStateChangeListener;
private MyPlaybackEventListener myPlaybackEventListener;

String log = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

youTubePlayerView = (YouTubePlayerView)findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);

textVideoLog = (TextView)findViewById(R.id.videolog);

myPlayerStateChangeListener = new MyPlayerStateChangeListener();
myPlaybackEventListener = new MyPlaybackEventListener();
}

@Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {

if (result.isUserRecoverableError()) {
result.getErrorDialog(this, RQS_ErrorDialog).show();
} else {
Toast.makeText(this,
"YouTubePlayer.onInitializationFailure(): " + result.toString(),
Toast.LENGTH_LONG).show();
}
}

@Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {

youTubePlayer = player;

Toast.makeText(getApplicationContext(),
"YouTubePlayer.onInitializationSuccess()",
Toast.LENGTH_LONG).show();

youTubePlayer.setPlayerStateChangeListener(myPlayerStateChangeListener);
youTubePlayer.setPlaybackEventListener(myPlaybackEventListener);

if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}

}

private final class MyPlayerStateChangeListener implements PlayerStateChangeListener {

private void updateLog(String prompt){
log += "MyPlayerStateChangeListener" + "\n" +
prompt + "\n\n=====";
textVideoLog.setText(log);
};

@Override
public void onAdStarted() {
updateLog("onAdStarted()");
}

@Override
public void onError(
com.google.android.youtube.player.YouTubePlayer.ErrorReason arg0) {
updateLog("onError(): " + arg0.toString());
}

@Override
public void onLoaded(String arg0) {
updateLog("onLoaded(): " + arg0);
}

@Override
public void onLoading() {
updateLog("onLoading()");
}

@Override
public void onVideoEnded() {
updateLog("onVideoEnded()");
}

@Override
public void onVideoStarted() {
updateLog("onVideoStarted()");
}

}

private final class MyPlaybackEventListener implements PlaybackEventListener {

private void updateLog(String prompt){
log += "MyPlaybackEventListener" + "\n-" +
prompt + "\n\n=====";
textVideoLog.setText(log);
};

@Override
public void onBuffering(boolean arg0) {
updateLog("onBuffering(): " + String.valueOf(arg0));
}

@Override
public void onPaused() {
updateLog("onPaused()");
}

@Override
public void onPlaying() {
updateLog("onPlaying()");
}

@Override
public void onSeekTo(int arg0) {
updateLog("onSeekTo(): " + String.valueOf(arg0));
}

@Override
public void onStopped() {
updateLog("onStopped()");
}

}

}


download filesDownload the files.

Download APK to try on your device.



The Tutorial: YouTube Android Player API step-by-step

Introducing Google Play for Education

BizDevBytes: Introducing Google Play for Education
As Google expands its education offering to Android, Shazia Makhdumi provides an overview of the Google Play for Education program. Developers will learn how the program works and how to leverage the unique business opportunities in creating educational apps for the K-12 market.

To learn more visit developer.android.com/edu

Handle initialization error YouTube API Service

Refer to the exercises of "Simple example using YouTube Android Player API" and "YouTubeThumbnailView example", onInitializationFailure() methods will be called with YouTubeInitializationResult passed if fail in initialization.

If the error is is user-recoverable (isUserRecoverableError() == true), we can proceed by calling getErrorDialog(Activity, int), and then show this dialog to enable users to recover from this error.

Handle initialization error YouTube API Service

Modify MainActivity.java from last exercise "YouTubeThumbnailView example of YouTube Android Player API" to handle onInitializationFailure() for YouTubePlayer and YouTubeThumbnailView.
package com.example.androidyoutubeapiplayer;

import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubeThumbnailLoader;
import com.google.android.youtube.player.YouTubeThumbnailLoader.ErrorReason;
import com.google.android.youtube.player.YouTubeThumbnailView;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener, YouTubeThumbnailView.OnInitializedListener{

public static final String API_KEY = "AIzaSyCe6tORd9Ch4lx-9Ku5SQ476uS9OtZYsWA";
public static final String VIDEO_ID = "o7VVHhK9zf0";

private YouTubePlayer youTubePlayer;
private YouTubePlayerView youTubePlayerView;
private YouTubeThumbnailView youTubeThumbnailView;
private YouTubeThumbnailLoader youTubeThumbnailLoader;

private static final int RQS_ErrorDialog = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

youTubePlayerView = (YouTubePlayerView)findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);

youTubeThumbnailView = (YouTubeThumbnailView)findViewById(R.id.youtubethumbnailview);
youTubeThumbnailView.initialize(API_KEY, this);
youTubeThumbnailView.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
if(youTubePlayer != null){
youTubePlayer.play();
}
}});
}

@Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {

if (result.isUserRecoverableError()) {
result.getErrorDialog(this, RQS_ErrorDialog).show();
} else {
Toast.makeText(this,
"YouTubePlayer.onInitializationFailure(): " + result.toString(),
Toast.LENGTH_LONG).show();
}
}

@Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {

youTubePlayer = player;

Toast.makeText(getApplicationContext(),
"YouTubePlayer.onInitializationSuccess()",
Toast.LENGTH_LONG).show();

if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}

@Override
public void onInitializationFailure(YouTubeThumbnailView thumbnailView,
YouTubeInitializationResult result) {

if (result.isUserRecoverableError()) {
result.getErrorDialog(this, RQS_ErrorDialog).show();
} else {
Toast.makeText(this,
"YouTubeThumbnailView.onInitializationFailure(): " + result.toString(),
Toast.LENGTH_LONG).show();
}
}

@Override
public void onInitializationSuccess(YouTubeThumbnailView thumbnailView,
YouTubeThumbnailLoader thumbnailLoader) {

Toast.makeText(getApplicationContext(),
"YouTubeThumbnailView.onInitializationSuccess()",
Toast.LENGTH_LONG).show();

youTubeThumbnailLoader = thumbnailLoader;
thumbnailLoader.setOnThumbnailLoadedListener(new ThumbnailLoadedListener());

youTubeThumbnailLoader.setVideo(VIDEO_ID);

}

private final class ThumbnailLoadedListener implements
YouTubeThumbnailLoader.OnThumbnailLoadedListener {

@Override
public void onThumbnailError(YouTubeThumbnailView arg0, ErrorReason arg1) {
Toast.makeText(getApplicationContext(),
"ThumbnailLoadedListener.onThumbnailError()",
Toast.LENGTH_LONG).show();
}

@Override
public void onThumbnailLoaded(YouTubeThumbnailView arg0, String arg1) {
Toast.makeText(getApplicationContext(),
"ThumbnailLoadedListener.onThumbnailLoaded()",
Toast.LENGTH_LONG).show();

}

}

}


download filesDownload the files.

Download APK to try on your device.

Next: Handle player state changes and playback events, by implementing PlayerStateChangeListener and PlaybackEventListener.


The Tutorial: YouTube Android Player API step-by-step

Offer Your Educational Apps On Google Play for Education

Posted by Pratip Banerji, Google Play for Education team




Last month, we announced Google Play for Education — a platform enabling developers and content providers to reach K-12 educators and students in the United States through a new Android based initiative. Google Play for Education is an extension of the Google Play Store for schools, adding curation, bulk purchasing, and instant distribution to students’ Android tablets for educational apps, books and videos. As we said at the time, we are excited to be doing our part to make technology and innovation in the classroom more accessible.



Starting today, you can use the Google Play Developer Console to mark your apps for inclusion in Google Play for Education, which is actively being piloted in schools across the country. Marking your app identifies it as targeted for the US K-12 educational market and queues it for evaluation by a third-party network of educators. These educators perform a first-pass qualification of apps, assigning the appropriate subject, grade, and common core standards metadata, while evaluating whether they meet the Google Play for Education criteria for classroom use.



Leading up to the fall launch, the Google Play for Education team is conducting an extensive series of pilots that include schools and students across the U.S. By marking your app for inclusion now, you will be getting your app into the hands of these schools and key influencers in the education technology community.



Whether you already have an existing educational app or are looking to build one, take a look at our Guidelines for Apps to make sure your app is appropriate for the K-12 environment. Follow our detailed requirements and test your app to ensure it is optimized for Android tablets. Then, upload your new or updated app, mark it for inclusion in Google Play for Education, and publish. We will email you when your app has been evaluated. Depending on app submission volume, this process can take 3-4 weeks. For more information, see Get Started.



Also please tune in to our panel for education developers on Tuesday June 25th at 10:30 AM EDT. Live from the ISTE (the International Society for Technology in Education) Conference, we’ll tell you more about developing for Google in Education and we’ll host some educators who explain what they are looking for in educational apps. The panel will be streamed on Google Developers Live and we'll make the video available to you as well.



For more information on Google Play for Education, please visit developer.android.com/edu.

YouTubeThumbnailView example of YouTube Android Player API

Extend the exercise of "Simple example using YouTube Android Player API", add YouTubeThumbnailView. When the YouTubeThumbnailView clicked, start play the YouTubePlayer.

YouTubeThumbnailView

Modify layout file, activity_main.xml, to add <YouTubePlayerView>.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold"
android:layout_gravity="center_horizontal"
android:autoLink="web" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<com.google.android.youtube.player.YouTubeThumbnailView
android:id="@+id/youtubethumbnailview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp" />
<com.google.android.youtube.player.YouTubePlayerView
android:id="@+id/youtubeplayerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp" />

</LinearLayout>
</ScrollView>

</LinearLayout>


MainActivity.java
package com.example.androidyoutubeapiplayer;

import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubeThumbnailLoader;
import com.google.android.youtube.player.YouTubeThumbnailLoader.ErrorReason;
import com.google.android.youtube.player.YouTubeThumbnailView;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener, YouTubeThumbnailView.OnInitializedListener{

public static final String API_KEY = "AIzaSyCe6tORd9Ch4lx-9Ku5SQ476uS9OtZYsWA";
public static final String VIDEO_ID = "o7VVHhK9zf0";

private YouTubePlayer youTubePlayer;
private YouTubePlayerView youTubePlayerView;
private YouTubeThumbnailView youTubeThumbnailView;
private YouTubeThumbnailLoader youTubeThumbnailLoader;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

youTubePlayerView = (YouTubePlayerView)findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);

youTubeThumbnailView = (YouTubeThumbnailView)findViewById(R.id.youtubethumbnailview);
youTubeThumbnailView.initialize(API_KEY, this);
youTubeThumbnailView.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
if(youTubePlayer != null){
youTubePlayer.play();
}
}});
}

@Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {
Toast.makeText(getApplicationContext(),
"YouTubePlayer.onInitializationFailure()",
Toast.LENGTH_LONG).show();
}

@Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {

youTubePlayer = player;

Toast.makeText(getApplicationContext(),
"YouTubePlayer.onInitializationSuccess()",
Toast.LENGTH_LONG).show();

if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}

@Override
public void onInitializationFailure(YouTubeThumbnailView thumbnailView,
YouTubeInitializationResult error) {

Toast.makeText(getApplicationContext(),
"YouTubeThumbnailView.onInitializationFailure()",
Toast.LENGTH_LONG).show();

}

@Override
public void onInitializationSuccess(YouTubeThumbnailView thumbnailView,
YouTubeThumbnailLoader thumbnailLoader) {

Toast.makeText(getApplicationContext(),
"YouTubeThumbnailView.onInitializationSuccess()",
Toast.LENGTH_LONG).show();

youTubeThumbnailLoader = thumbnailLoader;
thumbnailLoader.setOnThumbnailLoadedListener(new ThumbnailLoadedListener());

youTubeThumbnailLoader.setVideo(VIDEO_ID);

}

private final class ThumbnailLoadedListener implements
YouTubeThumbnailLoader.OnThumbnailLoadedListener {

@Override
public void onThumbnailError(YouTubeThumbnailView arg0, ErrorReason arg1) {
Toast.makeText(getApplicationContext(),
"ThumbnailLoadedListener.onThumbnailError()",
Toast.LENGTH_LONG).show();
}

@Override
public void onThumbnailLoaded(YouTubeThumbnailView arg0, String arg1) {
Toast.makeText(getApplicationContext(),
"ThumbnailLoadedListener.onThumbnailLoaded()",
Toast.LENGTH_LONG).show();

}

}

}


download filesDownload the files.

Download APK to try on your device.

Next: Handle initialization error YouTube API Service


The Tutorial: YouTube Android Player API step-by-step

Convert Uri return from Gallery to file path

The old exercise "Select Image using Android build-in Gallery" show how to selecte photo using Gallery app, in Uri form. In this exercise, the returned Uri is converted to file path in String form.

Convert Uri return from Gallery to file path

I also show using deprecated managedQuery() method for API under level 11, and CursorLoader() method for API level 11 or higher.

Layout file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold"
android:layout_gravity="center_horizontal"
android:autoLink="web" />

<Button
android:id="@+id/loadimage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Load Image"/>
<TextView
android:id="@+id/targeturi"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/targetpath1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/targetpath2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>


MainActivity.java
package com.example.androidselectimage;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

TextView textTargetUri, textTargetPath1, textTargetPath2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button buttonLoadImage = (Button)findViewById(R.id.loadimage);
textTargetUri = (TextView)findViewById(R.id.targeturi);
textTargetPath1 = (TextView)findViewById(R.id.targetpath1);
textTargetPath2 = (TextView)findViewById(R.id.targetpath2);

buttonLoadImage.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK){
Uri targetUri = data.getData();
textTargetUri.setText("Uri: " + targetUri.toString());
textTargetPath1.setText("path: " + getPathFromUri_managedQuery(targetUri));
textTargetPath2.setText("path: " + getPathFromUri_CursorLoader(targetUri));
}
}

//using deprecated managedQuery() method
private String getPathFromUri_managedQuery(Uri uri){
String [] projection = {MediaStore.Images.Media.DATA};

Cursor cursor = managedQuery(
uri,
projection,
null, //selection
null, //selectionArgs
null //sortOrder
);

int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();

return cursor.getString(column_index);
}

//using CursorLoader() method for API level 11 or higher
private String getPathFromUri_CursorLoader(Uri uri){

String [] projection = {MediaStore.Images.Media.DATA};

CursorLoader cursorLoader = new CursorLoader(
getApplicationContext(),
uri,
projection,
null, //selection
null, //selectionArgs
null //sortOrder
);

Cursor cursor = cursorLoader.loadInBackground();

int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();

return cursor.getString(column_index);
}
}


Note: To use CursorLoader() in your code, you have to modify AndroidManifest.xml to speciify android:minSdkVersion="11".
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidselectimage"
android:versionCode="1"
android:versionName="1.0" >

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

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

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>


download filesDownload the files.

Start activity once notification clicked

In the exercise "Generate Notification with sound when alarm received", a browse opened and load a specified url once user click on the notification. We can also pass intent to start activity to notification, to start activity once user click on the notification.

Start activity once notification clicked

Modify AlarmReceiver.java in the exercise "Generate Notification with sound when alarm received", pass Intent(context, DoSomething.class) to PendingIntent.getActivity(...).
package com.example.androiddatepicker;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {

private static final int MY_NOTIFICATION_ID=1;
NotificationManager notificationManager;
Notification myNotification;

@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm received!", Toast.LENGTH_LONG).show();

Intent myIntent = new Intent(context, DoSomething.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
0,
myIntent,
Intent.FLAG_ACTIVITY_NEW_TASK);

myNotification = new NotificationCompat.Builder(context)
.setContentTitle("Exercise of Notification!")
.setContentText("Do Something...")
.setTicker("Notification!")
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.build();

notificationManager =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
}

}


Create DoSomething.java, it will be started once user click the notification.
package com.example.androiddatepicker;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;

public class DoSomething extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
ImageView image = new ImageView(this);
image.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
setContentView(image);
Toast.makeText(getApplicationContext(),
"Do Something NOW",
Toast.LENGTH_LONG).show();
}

}


Modify AndroidManifest.xml to add <activity> of "DoSomething".
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androiddatepicker"
android:versionCode="1"
android:versionName="1.0" >

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

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.androiddatepicker.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.androiddatepicker.DoSomething"
android:label="@string/app_name" >
</activity>
<receiver android:name=".AlarmReceiver" android:process=":remote" />
</application>

</manifest>


download filesDownload the files.

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

Problem on Java Build Path again...! similar to the case of Unexpected namespace prefix "xmlns" found for tag fragment on xmlns:map="http://schemas.android.com/apk/res-auto".

Somebody report that my old exercise "Share IntentService among Fragments" not work. So I try to import the downloaded project in a new installed Android ADT, and the following error...sss reported in LogCat:

06-20 23:34:38.358: W/dalvikvm(26472): Unable to resolve superclass of Lcom/example/androidyahooweatherdom/MainActivity; (10)
06-20 23:34:38.358: W/dalvikvm(26472): Link of class 'Lcom/example/androidyahooweatherdom/MainActivity;' failed
06-20 23:34:38.358: W/dalvikvm(26472): threadid=1: thread exiting with uncaught exception (group=0x40cb92d0)
06-20 23:34:38.363: E/AndroidRuntime(26472): FATAL EXCEPTION: main
06-20 23:34:38.363: E/AndroidRuntime(26472): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.androidyahooweatherdom/com.example.androidyahooweatherdom.MainActivity}: java.lang.ClassNotFoundException: com.example.androidyahooweatherdom.MainActivity
06-20 23:34:38.363: E/AndroidRuntime(26472): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2267)
06-20 23:34:38.363: E/AndroidRuntime(26472): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
06-20 23:34:38.363: E/AndroidRuntime(26472): at android.app.ActivityThread.access$600(ActivityThread.java:151)
06-20 23:34:38.363: E/AndroidRuntime(26472): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1331)
06-20 23:34:38.363: E/AndroidRuntime(26472): at android.os.Handler.dispatchMessage(Handler.java:99)
06-20 23:34:38.363: E/AndroidRuntime(26472): at android.os.Looper.loop(Looper.java:155)
06-20 23:34:38.363: E/AndroidRuntime(26472): at android.app.ActivityThread.main(ActivityThread.java:5485)
06-20 23:34:38.363: E/AndroidRuntime(26472): at java.lang.reflect.Method.invokeNative(Native Method)
06-20 23:34:38.363: E/AndroidRuntime(26472): at java.lang.reflect.Method.invoke(Method.java:511)
06-20 23:34:38.363: E/AndroidRuntime(26472): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
06-20 23:34:38.363: E/AndroidRuntime(26472): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:795)
06-20 23:34:38.363: E/AndroidRuntime(26472): at dalvik.system.NativeStart.main(Native Method)
06-20 23:34:38.363: E/AndroidRuntime(26472): Caused by: java.lang.ClassNotFoundException: com.example.androidyahooweatherdom.MainActivity
06-20 23:34:38.363: E/AndroidRuntime(26472): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
06-20 23:34:38.363: E/AndroidRuntime(26472): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
06-20 23:34:38.363: E/AndroidRuntime(26472): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
06-20 23:34:38.363: E/AndroidRuntime(26472): at android.app.Instrumentation.newActivity(Instrumentation.java:1069)
06-20 23:34:38.363: E/AndroidRuntime(26472): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2258)
06-20 23:34:38.363: E/AndroidRuntime(26472): ... 11 more


Finally, I solve it by correcting Java Build Path - right clicking project -> Java Build Path, select Order and Export tab, check to include both Android 4.2.2 and Android Private Libraries, and click OK.

correct Java Build Path

Actually, I don't know what happen! May be there are something changed in new Android Developer Tools.

Learn Android App Development


Learn Android App Development is a hands-on tutorial and useful reference. You'll quickly get up to speed and master the Android SDK and the Java that you need for your Android Apps.

The Android SDK offers powerful features, and this book is the fastest path to mastering them—and the rest of the Andorid SDK—for programmers with some experience who are new to Android smartphone and tablet apps development. Many books introduce the Android SDK, but very few explain how to develop apps optimally. This book teaches both core Java language concepts and how to wisely but rapidly employ the design patterns and logic using the Android SDK, which is based on Java APIs.

You'll also learn best practices that ensure your code will be efficient and perform well.
  • Get an accelerated but complete enough treatment of the fundamentals of Java necessary to get you started.
  • Design your first app using prototyping and other design methods.
  • Build your first Android app using the code given over the course of the book.
  • Finally, debug and distribute your first app on Google Play or other Android app store.
After reading this book, you'll have your first app ready and on the app store, earning you the prestige and the money you seek.

What you’ll learn

  • How to get a quick start to learning Android to build your first Android app
  • How the Android development process works and what is the usual workflow
  • How to design an Android app User Interface (UI)
  • How to add interactivity and functionality to your Android apps

Who this book is for


This book is for those who have some programming experience but who are new to the Android mobile platform. This book is ideal for those who may be coming from iOS programming/development to learn about this other most popular mobile platform, Android.

Table of Contents

  1. Building Your Android Software Development Environment
  2. Exploring Android App Development: Building Your First Hello World App using the Lingo
  3. A Java for Android Primer: Enhancing our Hello World Application
  4. Designing User Interface Layouts via Android ViewGroup and Activity Classes
  5. Using Intents and Events to make an Android Application Interactive
  6. Populating a UI Design with Android Widgets via Android’s View Class
  7. Introduction to Graphics Design in Android: Concepts and Techniques
  8. Compositing in Android: Advanced Graphical User Interface Design
  9. Android Image Animation: Frame Animation Using XML Constructs
  10. Android Vector Animation: Procedural Animation via XML Constructs
  11. An Introduction to Digital Video: Video Concepts and Data Optimization
  12. Playing Digital Video in Android Apps using the Android VideoView Class
  13. An Introduction to Digital Audio: Audio Concepts and Data Optimization
  14. Playing Digital Audio in Android Apps using the Android MediaPlayer Class
  15. Audio Sequencing for Android Apps using the Android SoundPool Class
  16. Using Services to make your Android Application Functional
  17. Using Broadcast Receivers to allow an Android Application to Communicate
  18. Using Intents to Invoke Android Inter-Application Programming
  19. Using Android’s SQLite Class to store and access Custom Data
  20. Appendix A

Simple example using YouTube Android Player API

Simple example using YouTube Android Player API

Before create app using YouTube Android Player API, you have to "Download and import YouTube Android Player API" and "Register your app using YouTube Android Player API and obtain API Key".

Modify layout xml to add view of <com.google.android.youtube.player.YouTubePlayerView>.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="http://arteluzevida.blogspot.com/"
android:textStyle="bold"
android:layout_gravity="center_horizontal"
android:autoLink="web" />

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

</LinearLayout>


Modify MainActivity.java, extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener.
package com.example.androidyoutubeapiplayer;

import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
import com.google.android.youtube.player.YouTubePlayer.Provider;

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

public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{

public static final String API_KEY = "AIzaSyCe6tORd9Ch4lx-9Ku5SQ476uS9OtZYsWA";
public static final String VIDEO_ID = "o7VVHhK9zf0";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

YouTubePlayerView youTubePlayerView = (YouTubePlayerView)findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);
}

@Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {
Toast.makeText(getApplicationContext(),
"onInitializationFailure()",
Toast.LENGTH_LONG).show();
}

@Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}

}


Where API_KEY is the key obtained in the step of "Register your app using YouTube Android Player API and obtain API Key", VIDEO_ID is the ID of the video to play.

Permission of "android.permission.INTERNET" is needed in AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidyoutubeapiplayer"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>

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

</manifest>



download filesDownload the files.

Download APK to try on your device.

Next: YouTubeThumbnailView example of YouTube Android Player API

Related: YouTube Android Player API step-by-step