Home > Articles > Mobile Application Development & Programming

Developing Second Screen Apps for Google TV

Carmen Delessio shows you how to develop second screen apps for Google TV, including how to fling a URL, how to send KeyEvents to the TV, and how to send mouse events to the TV.

Read Sams Teach Yourself Google TV App Development in 24 Hours and more than 24,000 other books and videos on Safari Books Online. Start a free trial today.

This chapter is from the book

In Hour 22, “Examining an Example Second Screen App,” you installed the example Blackjack second screen app. In doing so, you downloaded and installed the Anymote Library and set up three Eclipse projects. Those projects were the Anymote Library, the remote control app, and the TV app.

In this hour, we will develop several second screen apps. The first app takes a URL entered on the remote device and opens the corresponding web page in the Chrome browser on Google TV. That represents a simple content app that pairs with the TV, but runs only on the remote. It provides an example of a basic remote app and uses the ability to fling an Android Intent to the TV. Apps for keyboard input and mouse events will also be developed. We’ll use the phone’s Accelerometer as the input device for sending mouse events to the TV. These example apps provide a foundation for creating more sophisticated second screen apps.

Flinging a URL

By installing and running the Blackjack second screen app in Hour 22, you added the Anymote Library to your Eclipse projects. We’ll use the Anymote Library and develop a remote app that takes a URL as input on an Android phone and opens the website on the Chrome browser on a Google TV. Because we can use an Android Intent to show the website on the TV, there is no need to create a separate TV app.

An App for Displaying Websites on a Google TV

We’ll start with an Android app that includes an EditText field for input and a button to initiate an action. We’ll make it a Google TV remote app by doing the following:

  • Adding the Anymote Library
  • Implementing the Activity as an AnymoteClientService ClientListener
  • Binding to the Anymote Service
  • Modifying the Android manifest to support the Anymote Library

All these things were done in the code for the Blackjack remote app, and we will use that as our model.

The input field for this app will accept a URL. The button in the activity reads the URL and attempts to send it to the TV. Figure 23.1 shows the remote user interface.

Figure 23.1

Figure 23.1. Send a URL to the Chrome Browser remotely.

The Anymote Library is added to the working Eclipse project, as it was in Hour 22.

For this app, we need only the remote app, and it will consist of a single Activity. Each remote app in this hour has a similar code structure:

  • An Activity that implements the AnymoteClientService ClientListener
  • A declaration of a ServiceConnection to bind to the Anymote Service
  • The Activity’s onCreate method that includes the binding to the Anymote Service
  • The implementation of the three methods required for ClientListener

Our Activity is called ExampleOneActivity. Similar to the BlackJackRemoteActivity, it is declared as follows:

public class ExampleOneActivity extends Activity implements ClientListener

Listing 23.1 shows the declaration of the Anymote sender and the service connection. A ServiceConnection is an Interface for monitoring the state of an application service. In our case, the service is the AnymoteClientService.

Listing 23.1. ServiceConnection Declaration

1: private AnymoteSender anymoteSender;
2: private ServiceConnection mConnection = new ServiceConnection() {
3:   public void onServiceConnected(ComponentName name, IBinder service) {
4:      mAnymoteClientService=((AnymoteClientService.AnymoteClientServiceBinder)
5:      service).getService();
6:      mAnymoteClientService.attachClientListener(ExampleOneActivity.this);
7:   }
8:   public void onServiceDisconnected(ComponentName name) {
9:      mAnymoteClientService.detachClientListener(ExampleOneActivity.this);
10:      mAnymoteClientService = null;
11:   }

In the onCreate method, we bind the AnymoteClientService to the Activity. The code to do that is shown next. An Intent is created using the activity and the AnymoteClientService class. A call to bindService binds the intent to the ServiceConnecton mService that we declared earlier. The flag BIND_AUTO_CREATE indicates that the service should be created.

Intent intent = new Intent(ExampleOneActivity.this,
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

Listing 23.2 shows the complete onCreate method for the Activity.

Listing 23.2. Remote Activity onCreate Method

1:  @Override
2:  public void onCreate(Bundle savedInstanceState) {
3:    super.onCreate(savedInstanceState);
4:    mContext = this;
5:    setContentView(R.layout.main);
6:    progressBar = (ProgressBar) findViewById(R.id.a_progressbar);
7:    progressBar.setVisibility(View.VISIBLE);
8:    Button go = (Button) findViewById(R.id.go);
9:    final EditText destination = (EditText) findViewById(R.id.destination);
10:   go.setOnClickListener(new OnClickListener() {
11:     @Override
12:     public void onClick(View v) {
13:       String url = destination.getText().toString();
14:       final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
15:       anymoteSender.sendUrl (intent.toUri(Intent.URI_INTENT_SCHEME));
16:     }
17:   });
18:   handler = new Handler();
19:   Intent intent = new Intent(ExampleOneActivity.this, AnymoteClientService.class);
20:   bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
21: }

Lines 19 and 20 in Listing 23.2 show the binding of the AnymoteClientService to the Activity.

Lines 5 to 9 define the UI components. A ProgressBar is shown while pairing occurs. An EditText and Button are defined. A URL can be entered into the EditText. The Go Button initiates the action of displaying the URL on the TV. Figure 23.1 showed what these look like on the remote.

Lines 10 to 17 define the action that occurs when the Button is pressed. The value in the EditText field is read in line 13. In line 14, that value is used to create an Intent. Line 15 sends the Intent to the Google TV using the anymoteSender. The TV will launch the Chrome browser and display the page associated with the URL.

The work of the app is done in the onCreate method, but the setup of the AnymoteService and library is required to make it happen. Finally, the three methods required for the ClientListener must be implemented. Those are the onConnected, onDisconnected, and onConnectionFailed methods. They are shown in Listing 23.3. Because the Activity implements ClientListener, we can say that it is a ClientListener.

We are relying on the Anymote Library for the user interface for pairing. Our app controls the ProgressBar and provides the UI for navigating to a URL. Listing 23.3 shows that we hide the ProgressBar when the connection is made. The field anymoteSender is populated in the onConnected method on line 3.

Listing 23.3. Required Methods for ClientListener

1:   @Override
2:   public void onConnected(final AnymoteSender anymoteSender) {
3:     this.anymoteSender = anymoteSender;
4:     handler.post(new Runnable() {
5:       public void run() {
6:         progressBar.setVisibility(View.INVISIBLE);
7:       }
8:     });
9:   }
10:  @Override
11:  public void onDisconnected() {
12:    this.anymoteSender = null;
13:  }
14:  @Override
15:  public void onConnectionFailed() {
16:    System.out.println("connection failed");
17:  }

The onDestroy method for the Activity is used to clean up any outstanding resources when the Activity is destroyed. In Listing 23.4, we use the onDestroy method to detach and unbind the Anymote services from the current Activity.

Listing 23.4. Cleaning Up in the onDestroy Method

1:  @Override
2:  protected void onDestroy() {
3:    if (mAnymoteClientService != null) {
4:      mAnymoteClientService.detachClientListener(this);
5:    }
6:    unbindService(mConnection);
7:    super.onDestroy();
8:  }

The Anymote Library handles the UI for discovery and pairing. For this remote app, no companion TV app is required. The native functionality of flinging an Intent to the TV provides the functionality required.

An App for Showing a Facebook Image on a Google TV

We will create another second content app that flings a URL to the TV that is based on the work we did in Hour 18, “Developing a Complete App.” In that hour, we created a Google TV app that showed random images from a Facebook page. We will turn that app into a remote content app using the Anymote protocol. The phone will show a random image when a button is pressed. The TV will show the same image.

The onCreate method for the app shows how we make this happen. It is shown in Listing 23.5. The basic infrastructure of a remote app is followed. The Activity extends ClientListener and binds to the AnymoteClientService.

In the app in Hour 17, “Using Cursors and CursorLoaders,” we retrieved a list of photos from Facebook. We parsed the data and selected a random image to display. We select the random URL as a String in line 16 of Listing 23.5. We then use that URL for two things. We use an ImageViewFragment to display it on the phone and we use the Anymote Service to fling it to the TV as an Intent. The flinging occurs in lines 18 and 19.

Listing 23.5. Facebook Random Image Remote App

1:  @Override
2:  public void onCreate(Bundle savedInstanceState) {
3:    super.onCreate(savedInstanceState);
4:    setContentView(R.layout.main);
5:    LoadPhotos lp = new LoadPhotos("99394368305" );
6:    lp.execute();
7:    progressBar = (ProgressBar) findViewById(R.id.progressBar1);
8:    progressBar.setVisibility(View.VISIBLE);
9:    mButton2= (Button)findViewById(R.id.button2);
10:   mButton2.setEnabled(false);
11:   mButton2.setOnClickListener(new OnClickListener() {
12:     public void onClick(View v) {
13:       ImageViewFragment fbImg = new ImageViewFragment();
14:       Bundle args = new Bundle();
15:       int random = (int)(Math.random() * mPagePhotos.size());
16:       String url = mPagePhotos.get(random).source;
17:       args.putString("URL", url);
18:       final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
19:       anymoteSender.sendUrl (intent.toUri(Intent.URI_INTENT_SCHEME));
20:       fbImg.setArguments(args);
21:       FragmentTransaction ft = getFragmentManager().beginTransaction();
22:       ft.replace(R.id.linearLayout1, fbImg, "Image from Facebook");
23:       ft.commit();
24:     }
25:   });
26:   handler = new Handler();
27:   Intent intent = new Intent(ExampleTwoActivity.this, AnymoteClientService.class);
28:   bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
29: }

Both of the examples used simple interfaces on the remote device and displayed the resulting content on the TV. They show the basic use of flinging a URL to the TV for display in a Chrome browser. It is easy to envision more complex user interfaces that also result in a URL being displayed on the TV. For example, an app could allow a user to enter complex search criteria into a phone and have the result displayed on the TV.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020