Monday, August 31, 2015

Move Android Emulator using keyboard, in Windows 10

My Android Emulator on Windows 10 always open with title bar hidden, cannot be moved using mouse.


To move it with keyboard shortcuts:
- Click to select Android Emulator window
- Press Alt + SPACE
- press m
- Up/Down/Left/Right to move the window.


Windows 10 Keyboard Shortcuts: WIN + Left/Right/Up/Down to snap active window


To snap active window Press and Hold WIN key and press Left/Right/Up/Down:
WIN + Left - snap window to left
WIN + Right - snap window to right
WIN + Up - snap window to up
WIN + Down - snap window to down

Find my IP and MAC address in Windows 10


Find my IP and MAC address in Windows 10
- click the Network connection icon on status bar
- Click "Network settings"
- Select "Ethernet" tap on left
- Click "Network Connected"



Windows 10 Store not work, fixed by setting Date/Time

In  my new bought Windows 10 notebook with default setting of auto-detect Date/Time, the Store cannot load/install any app. As show in below video; the Store closed when I try to load any app. Then I set Date/Time once, it work properly.

Hello World and create AVD for Android Wear

This video show how to create AVD for Android Wear, create Hello World and run on Android Wear Emulator.

Install Intel x86 Emulator Accelerator (HAXM), on Android Studio/Windows 10

After Install Android Studio on Windows 10, you can install Intel x86 Emulator Accelerator (HAXM).


Refer to Android Developers document "Using the Emulator - Configuring Virtual Machine Acceleration":

Many modern CPUs provide extensions for running virtual machines (VMs) more efficiently. Taking advantage of these extensions with the Android emulator requires some additional configuration of your development system, but can significantly improve the execution speed. Before attempting to use this type of acceleration, you should first determine if your development system’s CPU supports one of the following virtualization extensions technologies:
  • Intel Virtualization Technology (VT, VT-x, vmx) extensions
  • AMD Virtualization (AMD-V, SVM) extensions (only supported for Linux)
The specifications from the manufacturer of your CPU should indicate if it supports virtualization extensions. If your CPU does not support one of these virtualization technologies, then you cannot use virtual machine acceleration.

If your system with Intel's CPU, you can check if the Virtualization Technology is Enabled using Intel® Processor Identification Utility.

To install Intel x86 Emulator Accelerator (HAXM Installer) and run it, read this video.


Most probably, you will encounter the following error and the Android Emulator cannot run!

HAXM is not working and emulator runs in emulation mode
emulator: The memory needed by this AVD exceeds the max specified in your HAXM configuration.
emulator: AVD      RAM size = 1536 MB
emulator: HAXM max RAM size = 512 MB
emulator: You might want to adjust your AVD RAM size and/or HAXM configuration to run in fast virt mode.

Because The HAXM installer suggested a 512MB/1GB RAM by default, and the default AVD created by Android Studio Setup require 1536 MB. To fix it, edit your AVD to require 1GB of RAM.



Or, you can/have to re-install HAXM to increase HAXM max RAM size.


Install Android Studio on Windows 10

Android Studio IDE is the official Android development IDE.


Before install, check if your system meet the System Requirements.

In my system:
OS: Windows 10
Java: JDK 8 (Refer the Java-Buddy post "Install JDK 8 on Windows 10, and set Path")

To download Android Studio IDE, visit http://developer.android.com/sdk/index.html.

By default, the Setup Wizard will create a default AVD (Android Virtual Device) for you, Nexus 5 API 23 x86. (If you encounter error of "HAXM is not working and emulator runs in emulation mode" when run Android Emulator with HAXM, refer to the next post "Install Intel x86 Emulator Accelerator (HAXM), on Android Studio/Windows 10")



After installed, I always run SDK Manager to check if any update and install the suggested packages.


Next:
Install Intel x86 Emulator Accelerator (HAXM)



Create Marshmallow Emulator in Android Studio AVD Manager




Related:
- Download and run Android Studio 2.0 Preview on Windows 10

Android Programming: The Big Nerd Ranch Guide (2nd Edition)

Android Programming: The Big Nerd Ranch Guide is an introductory Android book for programmers with Java experience.

Android Programming: The Big Nerd Ranch Guide (2nd Edition)

Based on Big Nerd Ranch's popular Android Bootcamp course, this guide will lead you through the wilderness using hands-on example apps combined with clear explanations of key concepts and APIs. This book focuses on practical techniques for developing apps compatible with Android 4.1 (Jelly Bean) and up, including coverage of Lollipop and material design.

Write and run code every step of the way, creating apps that integrate with other Android apps, download and display pictures from the web, play sounds, and more. Each chapter and app has been designed and tested to provide the knowledge and experience you need to get started in Android development.

Big Nerd Ranch specializes in developing and designing innovative applications for clients around the world. Our experts teach others through our books, bootcamps, and onsite training. Whether it's Android, iOS, Ruby and Ruby on Rails, Cocoa, Mac OS X, JavaScript, HTML5 or UX/UI, we've got you covered.

Sunday, August 30, 2015

How to check if your Intel CPU's Virtualization Technology is Enabled? - Intel® Processor Identification Utility

If your CPU is Intel, you can use Intel® Processor Identification Utility to check if your CPU's Virtualization Technology is Enabled or not.

Intel® Processor Identification Utility Download for Windows

Intel® Processor Identification Utility is designed to identify current Intel® Processors and technologies, and it enables you to run and save a processor ID report. The utility also features a frequency test to make sure that the processor is working at the rated speed.




This video walks you through how to download and install the application. It also provides an overview of the most common technologies supported by the processor.


Alternatively, you can check it with Coreinfo.

Retrieve system properties using System.getProperties()

getProperties() method of java.lang.System returns the system properties. Here is a example to retrieve system properties using System.getProperties().


package com.blogspot.android_er.androidsystemproperties;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.util.Enumeration;
import java.util.Properties;

public class MainActivity extends AppCompatActivity {

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

        TextView info = (TextView)findViewById(R.id.info);

        Properties properties = System.getProperties();
        info.append(properties.toString());
        info.append("\n----------\n\n");

        Enumeration<String> prop =
                (Enumeration<String>) properties.propertyNames();

        while(prop.hasMoreElements()){
            String propName = prop.nextElement();
            info.append(propName + " : \n" +
                    System.getProperty(propName) + "\n\n");

        }
    }

}


<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:padding="10dp"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/info"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>

</LinearLayout>


Saturday, August 29, 2015

On-Screen Keyboard of Windows 10

To run On-Screen Keyboard on Windows 10, simple search "on-screen keyboard".

On-Screen Keyboard run on Windows 10




Related:
- Show touch keyboard button on Task Bar, in Windows 10

Microsoft Visual Studio 2015 Unleashed (3rd Edition)

Microsoft Visual Studio 2015 Unleashed (3rd Edition)

Microsoft Visual Studio 2015 empowers you to write next-generation applications for any modern environment: mobile, web, cloud, universal Windows 10/8.x, database, and beyond. This end-to-end deep dive will help working developers squeeze maximum productivity out of Microsoft’s powerful new toolset.

The authors combine authoritative and detailed information about Microsoft’s latest IDE, with extensive insights and best practices drawn from decades of development experience. Developers will quickly get comfortable with Visual Studio 2015’s updated interface, master its new capabilities, leverage its extensive new support for open standards, and discover multiple opportunities to leverage its .NET 4.6 platform and language improvements.

By focusing entirely on Visual Studio 2015 Professional, the authors go deeper into Microsoft’s core product than ever before. You’ll find expert coverage of everything from debugging through deploying to Azure, IDE extension and automation through cross-platform mobile development. Throughout, this book’s focus is relentlessly practical: how to apply Microsoft’s tools to build better software, faster.

Detailed information on how to...
  • Master Visual Studio 2015’s updated interface and key tools: Solutions, Projects, Browsers, Explorers, Editors, and Designers to improve productivity
  • Develop robust cross-platform mobile apps for Windows, iOS, and Android using Apache Cordova templates for Visual Studio
  • Use the new ASP.NET 5 to build modern web solutions that run on Windows, Mac, or Linux
  • Develop Single Page Applications (SPAs) based on HTML5 and rich client-side JavaScript frameworks such as Knockout, AngularJS, Bootstrap, and more
  • Accelerate cloud development with the Azure SDK, QuickStart templates, and Azure management portal
  • Create mobile service solutions using ASP.NET Web API and WCF
  • Streamline data development across multiple platforms with Entity Framework 7
  • Develop modern Microsoft Office business applications
  • Perform robust, automated unit testing as you code, increasing your confidence in changes and refactoring
  • Extend the VS 2015 IDE and Code Editor by creating custom, productivity-enhancing solutions
Download all examples and source code presented in this book from informit.com/title/9780672337369 as they become available.

Install Movie Maker in Windows 10

Movie Maker is included in the Windows Essentials 2012 program suite, it is not supported for Windows 10 officially, but you can still download Movie Maker if you really want it. (ref: http://windows.microsoft.com/en-hk/windows-10/movie-maker-is-not-available-in-windows-10)


visit http://windows.microsoft.com/en-us/windows-live/movie-maker to download Windows Movie Maker.

Movie Maker run on Windows 10

Free eBook: Visual Studio 2015 Succinctly

Description
Microsoft Visual Studio 2015 is the new version of the widely-used integrated development environment for building modern, high-quality applications for a number of platforms such as Windows, the web, the cloud, and mobile devices. In Visual Studio 2015 Succinctly, author Alessandro Del Sole explains how to take advantage of the most useful of these highly anticipated features. Topics include sharing code between different types of projects, new options for debugging and diagnostics, and improving productivity with other services in the Visual Studio ecosystem, such as NuGet and Azure. Changes to the code editor and XAML editor are also covered, as well as updates for mobile development in Visual Studio.

Table of Contents
Account Management Experience
Shared Projects
Code Editor Improvements
XAML Editor Improvements
IDE Customizations: Window Layout
Error List Revisited and Debugging Improvements
Managing NuGet Packages
Visual Studio 2015 for ASP.NET and Azure Chapter Prerequisites
Visual Studio 2015 for Mobile Development

Visit: https://www.syncfusion.com/resources/techportal/details/ebooks/visualstudio2015, register and download for FREE.

Friday, August 28, 2015

Android Application Development All-in-One For Dummies


Android Application Development All-in-One For Dummies

6 BOOKS IN 1
  • Android Jump-Start
  • Background Material
  • The Building Blocks
  • Programming Cool Phone Features
  • Apps for All Kinds of Devices
  • Publishing and Marketing Your App
No experience? No problem! Start creating Android apps today!

Android is everywhere. Get your piece of the action with this all-in-one guide to creating great apps for this booming market! Six self-contained minibooks provide everything you need to program cool phone features, refine your apps, and add the perfect finishing touches.
  • First, the groundwork — set up your system for app development and create your first basic Android app
  • Android underpinnings — see how Java and XML are necessary and learn to use Android Studio
  • Nuts and bolts — discover the essentials common to every app from simple to complex
  • What phones can do — explore how to take advantage of a mobile device's unique feature set
  • Both big and small — learn to create apps for larger tablet screens, small watch screens, and larger TV screens
  • Make a game of it — investigate Android game development and learn to connect to social media
  • To market, to market — find out how to market your apps
  • The alternative world — learn app development techniques involving C and C++
Open the book and find:
  • Steps to create your first app
  • Major technical ideas behind Android
  • Tips for handling button presses
  • Hints for effective screen layout
  • Android's built-in tools
  • What a fragment is and how to use one
  • Programming tricks essential to building games
  • Posting your app to the Google Play Store
About the Author
Barry Burd, PhD, is a professor of mathematics and computer science at Drew University. He leads training courses for professional programmers in business and industry, and has lectured at conferences around the world. He is the author of the bestselling Java For Dummies and other programming books.

Android 5 Programming by Example

Turn your ideas into elegant and powerful mobile applications using the latest Android Studio for the Android Lollipop platform

Android 5 Programming by Example

About This Book
  • Design and customize GUI using material design to create attractive and intuitive layouts easily
  • Bring your designs to life with Android 5's powerful and extensive Java libraries, new sensors, and new platforms such as TVs, wearables, and cars
  • An example-based guide to learn and develop applications for Android 5
Who This Book Is For
If you have a great idea for a mobile app, and some familiarity with Java, or a similar procedural programming language, then all you need is this book to turn your idea into a reality.

What You Will Learn

  • Set up an effective development environment to create Android apps from scratch
  • Control the layout structure and design and edit code to control screen events
  • Respond to user interaction using Java and XML with your app
  • Keep your users up to date with Android's new notification framework
  • Implement Google APIs such as maps and other Google Services
  • Create apps for televisions, cars, and wearables and build home-screen app widgets
  • Add audio and video playback to your apps using the AudioManager and MediaPlayer classes
  • Program the two new Lollipop widgets, CardView and RecyclerView
  • Compile your apps, distribute them on the Google Play store, and build in a variety of ways to monetize them

In Detail
Android is a mobile operating system that runs on a staggering number of smart phones and tablets. Android offers developers the ability to build rich and innovative applications written using the Java programming language.

Beginning with detailed instructions on how to install and configure the Android SDK, Studio, and Virtual Device Manager, the book moves on to creating a simple, but working, "Hello World" app that can be run on a real device or emulator.

The book then moves on to layouts and the visual design of Lollipop apps. A new app is begun to demonstrate this and expanded as we move further, and, once material design has been introduced, the book moves on to the Java coding aspect and how to write code that responds to user interactions via callback methods such as touchscreen gesture listeners. No book on Lollipop APIs would be complete without explaining how the new Android TV, Wear, and Auto SDK tools work and how they can be utilized to either create new apps or convert those originally written for other platforms.

The book concludes by demonstrating how to package and deploy your finished app on the Google Play store.

Record screen on Windows 10

To record a video, just hit the Windows Key + G on your PC when any window is open and the Game DVR menu should pop-up. After that, click on the checkbox “This is a game” and you’ll be navigated to the simple interface where you can capture a screenshot and record your screen. Just hit the red record icon and it’ll start recording your screen.


reference: How to record your screen using the built-in screen recorder on Windows 10

Alternatively, Open Broadcaster Software is free and open source software for video recording and live streaming. Supported features include:

  • Encoding using H264 (x264) and AAC.
  • Support for Intel Quick Sync Video (QSV) and NVENC.
  • Unlimited number of scenes and sources.
  • Live RTMP streaming to Twitch, YouTube, DailyMotion, Hitbox and more.
  • File output to MP4 or FLV.
  • GPU-based game capture for high performance game streaming.
  • DirectShow capture device support (webcams, capture cards, etc).
  • Windows 8 high speed monitor capture support.
  • Bilinear or lanczos3 resampling.


Wednesday, August 26, 2015

FREE ebook: Android Programming Succinctly

Android Programming Succinctly

Description
In Android Programming Succinctly, Ryan Hodson provides a useful overview of the Android application lifecycle. Topics ranging from creating a UI to adding widgets and embedding fragments are covered, and he provides plenty of links to Android documentation along the way. Each chapter is conveniently summarized to ensure you get the most out of reading the book, and summaries include helpful suggestions for expanding your abilities in this growing app market.

Table of Contents
Setting Up
Hello, Android
The Activity Lifecycle
User Interface Layouts
User Interface Widgets
Fragments
Application Data

Visit https://www.syncfusion.com/resources/techportal/details/ebooks/android to download for free.

Thursday, August 20, 2015

Introducing Face Detection in the Google Vision APIs

The Google Vision APIs provide two main areas of functionality.

First is Face Tracking -- not to be confused with Facial Recognition -- which gives your apps the ability to detect faces, and landmarks on faces. This is useful for, for example -- writing a camera app that only takes a picture when everyone is smiling, and nobody is blinking, or for fun apps where you can superimpose hats or moustaches on people in the camera preview window. 

Second is recognizing visual codes such as bar codes or QR codes, and making it easy for developers to build apps with them.




~ My step-by-step posts of Face Detection with Google Play services, Mobile Vision API

Try PercentRelativeLayout and PercentFrameLayout of Percent Support Library

The Percent package provides APIs to support adding and managing percentage based dimensions in your app.

- Make sure you have downloaded/updated the Android Support Repository using the SDK Manager.

- Edit build.gradle, to add dependencies compile 'com.android.support:percent:23.0.0'.


Example of using PercentRelativeLayout:
<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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:padding="@dimen/activity_horizontal_margin"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <android.support.percent.PercentRelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <ImageView
            android:id="@+id/imageview"
            android:layout_gravity="center"
            app:layout_widthPercent="50%"
            app:layout_heightPercent="50%"
            android:src="@mipmap/ic_launcher"
            android:background="#cecece"/>
        <TextView
            android:id="@+id/textview1"
            android:layout_below="@id/imageview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_marginStartPercent="25%"
            app:layout_marginEndPercent="25%"
            android:text="PercentRelativeLayout example"
            android:background="#bebebe"/>
        <TextView
            android:id="@+id/textview2"
            android:layout_below="@id/textview1"
            android:layout_height="wrap_content"
            app:layout_widthPercent="60%"
            android:text="PercentRelativeLayout example"
            android:background="#aeaeae"/>

    </android.support.percent.PercentRelativeLayout>

</LinearLayout>



Example of using PercentFrameLayout:
<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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:padding="@dimen/activity_horizontal_margin"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <android.support.percent.PercentFrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <ImageView
            android:id="@+id/imageview"
            android:layout_gravity="center"
            app:layout_widthPercent="50%"
            app:layout_heightPercent="50%"
            android:src="@mipmap/ic_launcher"
            android:background="#cecece"/>
        <TextView
            android:id="@+id/textview1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_marginStartPercent="25%"
            app:layout_marginEndPercent="25%"
            android:text="PercentFrameLayout example"
            android:background="#bebebe"/>
        <TextView
            android:id="@+id/textview2"
            android:layout_height="wrap_content"
            app:layout_widthPercent="60%"
            android:text="PercentFrameLayout example"
            android:background="#aeaeae"/>

    </android.support.percent.PercentFrameLayout>

</LinearLayout>



RecyclerView + CardView example with ImageView - list available Drawable

Last post show how to "get all available drawable and its value". This example show how to display the drawables, names and values in RecyclerView + CardView.


To use RecyclerView + CardView, we have to "Add Support Libraries of RecyclerView, CardView to Android Studio Project".

Create layout of the CardView, layout/layout_cardview.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    card_view:cardCornerRadius="20sp"
    card_view:cardElevation="5sp">

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

        <ImageView
            android:id="@+id/item_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/item_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18dp"/>
        <TextView
            android:id="@+id/item_value"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="16dp"/>

    </LinearLayout>

</android.support.v7.widget.CardView>


Create our custom MyRecyclerViewAdapter extends RecyclerView.Adapter, com.example.androidlistdrawable.MyRecyclerViewAdapter.java
package com.example.androidlistdrawable;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MyRecyclerViewAdapter extends
        RecyclerView.Adapter<MyRecyclerViewAdapter.ItemHolder> {

    private List<String> itemsName;
    private List<Integer> itemsValue;
    private LayoutInflater layoutInflater;
    private Context context;

    public MyRecyclerViewAdapter(Context context){
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
        itemsName = new ArrayList<String>();
        itemsValue = new ArrayList<Integer>();
    }

    @Override
    public MyRecyclerViewAdapter.ItemHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        CardView itemCardView = (CardView)layoutInflater.inflate(R.layout.layout_cardview, viewGroup, false);
        return new ItemHolder(itemCardView, this);
    }

    @Override
    public void onBindViewHolder(MyRecyclerViewAdapter.ItemHolder itemHolder, int i) {
        itemHolder.setItemName(itemsName.get(i));
        int value = itemsValue.get(i);
        itemHolder.setItemValue(String.valueOf(value));
        Drawable drawable = context.getResources().getDrawable(value);
        itemHolder.setImageView(drawable);
    }

    @Override
    public int getItemCount() {
        return itemsName.size();
    }

    public void add(int location, String iName, int iValue){
        itemsName.add(location, iName);
        itemsValue.add(location, iValue);
        notifyItemInserted(location);
    }

    public void remove(int location){
        if(location >= itemsName.size())
            return;

        itemsName.remove(location);
        itemsValue.remove(location);
        notifyItemRemoved(location);
    }

    public static class ItemHolder extends RecyclerView.ViewHolder{

        private MyRecyclerViewAdapter parent;
        private CardView cardView;
        TextView textItemName;
        TextView textItemValue;
        ImageView imageView;

        public ItemHolder(CardView cView, MyRecyclerViewAdapter parent) {
            super(cView);
            cardView = cView;
            this.parent = parent;
            textItemName = (TextView) cardView.findViewById(R.id.item_name);
            textItemValue = (TextView) cardView.findViewById(R.id.item_value);
            imageView = (ImageView) cardView.findViewById(R.id.item_image);
        }

        public void setItemName(CharSequence name){
            textItemName.setText(name);
        }

        public CharSequence getItemName(){
            return textItemName.getText();
        }

        public void setItemValue(CharSequence val){
            textItemValue.setText(val);
        }

        public CharSequence getItemValue(){
            return textItemValue.getText();
        }

        public void setImageView(Drawable drawable){
            imageView.setImageDrawable(drawable);
        }

    }
}


Modify layout to add RecyclerView, layout/activity_main.xml.
<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:padding="10dp"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/myrecyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>


com.example.androidlistdrawable.MainActivity.java
package com.example.androidlistdrawable;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;

import java.lang.reflect.Field;

public class MainActivity extends AppCompatActivity {

    private RecyclerView myRecyclerView;
    private StaggeredGridLayoutManager staggeredGridLayoutManagerVertical;
    private MyRecyclerViewAdapter myRecyclerViewAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myRecyclerView = (RecyclerView)findViewById(R.id.myrecyclerview);

        staggeredGridLayoutManagerVertical =
                new StaggeredGridLayoutManager(
                        2, //The number of Columns in the grid
                        LinearLayoutManager.VERTICAL);
        myRecyclerViewAdapter = new MyRecyclerViewAdapter(this);
        myRecyclerView.setAdapter(myRecyclerViewAdapter);
        myRecyclerView.setLayoutManager(staggeredGridLayoutManagerVertical);

        prepareItems();
    }

    private void prepareItems(){
        Field[] fieldDrawables = android.R.drawable.class.getFields();
        for(int i=0; i<fieldDrawables.length; i++){
            Field field = fieldDrawables[i];
            try {
                int value = (int) field.get(fieldDrawables);
                myRecyclerViewAdapter.add(
                        myRecyclerViewAdapter.getItemCount(),
                        "R.drawable." + field.getName(),
                        value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }
    }

}




download filesDownload the files (Android Studio Format).


~ More step-by-step examples of RecyclerView + CardView.

Wednesday, August 19, 2015

List all available drawable and its value

Example to list all available Drawable and its value:


package com.example.androidlistdrawable;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.lang.reflect.Field;

public class MainActivity extends AppCompatActivity {

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

        TextView info = (TextView)findViewById(R.id.info);

        Field[] fieldDrawables = android.R.drawable.class.getFields();
        for(int i=0; i<fieldDrawables.length; i++){
            Field field = fieldDrawables[i];
            info.append("R.drawable." + field.getName() + " :\n");
            info.append(field.toString() + "\n");

            try {
                int value = (int) field.get(fieldDrawables);
                info.append("value = " + value + "\n");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

            info.append("\n");

        }
    }

}


<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:padding="10dp"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <TextView
            android:id="@+id/info"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>



Next:
- RecyclerView + CardView example - list available Drawable

Unity 5 for Android Essentials

Unity 5 for Android Essentials

This book is perfect for competent Unity developers who want to learn how to develop, optimize, and publish games for Android devices in a quick and easy manner. This book assumes basic knowledge of game design concepts and/or some experience with other game technologies such as Unreal Engine 4, CryEngine, or GameMaker.


Tuesday, August 18, 2015

Google Play services Face Detection, detect Smiling

With Face Detection of Google Play services, Mobile Vision API, you can detect various facial states; such as Smiling, Left Eye Open or Right Eye Open.


This example show how to detect Smiling face with getIsSmilingProbability() method of com.google.android.gms.vision.face.Face. You can also use getIsLeftEyeOpenProbability() and getIsRightEyeOpenProbability() methods to test if the face's left or right eye is open.


Modify from last post of "Google Play services Face Detection, get Landmarks (eyes, nose, etc.)". Call setClassificationType(FaceDetector.ALL_CLASSIFICATIONS) method when build FaceDetector with FaceDetector.Builder. Then call getIsSmilingProbability() method of the detected faces to check if it is similing.

package com.example.androidfacedetection;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.FaceDetector;
import com.google.android.gms.vision.face.Landmark;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final int RQS_LOADIMAGE = 1;
    private Button btnLoad, btnDetFace;
    private ImageView imgView;
    private Bitmap myBitmap;

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

        btnLoad = (Button)findViewById(R.id.btnLoad);
        btnDetFace = (Button)findViewById(R.id.btnDetectFace);
        imgView = (ImageView)findViewById(R.id.imgview);

        btnLoad.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, RQS_LOADIMAGE);
            }
        });

        btnDetFace.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(myBitmap == null){
                    Toast.makeText(MainActivity.this,
                            "myBitmap == null",
                            Toast.LENGTH_LONG).show();
                }else{
                    detectFace();

                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RQS_LOADIMAGE
                && resultCode == RESULT_OK){

            if(myBitmap != null){
                myBitmap.recycle();
            }

            try {
                InputStream inputStream =
                        getContentResolver().openInputStream(data.getData());
                myBitmap = BitmapFactory.decodeStream(inputStream);
                inputStream.close();
                imgView.setImageBitmap(myBitmap);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /*
    reference:
    https://search-codelabs.appspot.com/codelabs/face-detection
     */
    private void detectFace(){

        //Create a Paint object for drawing with
        Paint myRectPaint = new Paint();
        myRectPaint.setStrokeWidth(5);
        myRectPaint.setColor(Color.GREEN);
        myRectPaint.setStyle(Paint.Style.STROKE);

        Paint landmarksPaint = new Paint();
        landmarksPaint.setStrokeWidth(10);
        landmarksPaint.setColor(Color.RED);
        landmarksPaint.setStyle(Paint.Style.STROKE);

        Paint smilingPaint = new Paint();
        smilingPaint.setStrokeWidth(4);
        smilingPaint.setColor(Color.YELLOW);
        smilingPaint.setStyle(Paint.Style.STROKE);

        boolean somebodySmiling = false;

        //Create a Canvas object for drawing on
        Bitmap tempBitmap = Bitmap.createBitmap(myBitmap.getWidth(), myBitmap.getHeight(), Bitmap.Config.RGB_565);
        Canvas tempCanvas = new Canvas(tempBitmap);
        tempCanvas.drawBitmap(myBitmap, 0, 0, null);

        //Detect the Faces

        //!!!
        //Cannot resolve method setTrackingEnabled(boolean)
        //FaceDetector faceDetector = new FaceDetector.Builder(getApplicationContext()).build();
        //faceDetector.setTrackingEnabled(false);

        FaceDetector faceDetector =
                new FaceDetector.Builder(getApplicationContext())
                .setTrackingEnabled(false)
                        .setLandmarkType(FaceDetector.ALL_LANDMARKS)
                        .setClassificationType(FaceDetector.ALL_CLASSIFICATIONS)
                        .build();

        Frame frame = new Frame.Builder().setBitmap(myBitmap).build();
        SparseArray<Face> faces = faceDetector.detect(frame);

        //Draw Rectangles on the Faces
        for(int i=0; i<faces.size(); i++) {
            Face thisFace = faces.valueAt(i);
            float x1 = thisFace.getPosition().x;
            float y1 = thisFace.getPosition().y;
            float x2 = x1 + thisFace.getWidth();
            float y2 = y1 + thisFace.getHeight();
            tempCanvas.drawRoundRect(new RectF(x1, y1, x2, y2), 2, 2, myRectPaint);

            //get Landmarks for the first face
            List<Landmark> landmarks = thisFace.getLandmarks();
            for(int l=0; l<landmarks.size(); l++){
                PointF pos = landmarks.get(l).getPosition();
                tempCanvas.drawPoint(pos.x, pos.y, landmarksPaint);
            }

            //check if this face is Smiling
            final float smilingAcceptProbability = 0.5f;
            float smilingProbability = thisFace.getIsSmilingProbability();
            if(smilingProbability > smilingAcceptProbability){
                tempCanvas.drawOval(new RectF(x1, y1, x2, y2), smilingPaint);
                somebodySmiling = true;
            }
        }

        imgView.setImageDrawable(new BitmapDrawable(getResources(), tempBitmap));

        if(somebodySmiling){
            Toast.makeText(MainActivity.this,
                    "Done - somebody is Smiling",
                    Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(MainActivity.this,
                    "Done - nobody is Smiling",
                    Toast.LENGTH_LONG).show();
        }
        
    }
}


Other files, AndroidManifest.xml and layout/activity_main.xml, refer to the post "Face Detection with Google Play services, Mobile Vision API".

Sunday, August 16, 2015

Google Play services Face Detection, get Landmarks (eyes, nose, etc.)

getLandmarks() method of com.google.android.gms.vision.face.Face return a list of Landmarks (eyes, nose, etc.) found on the face. A landmark detector must be specified via setLandmarkType(int) to detect landmarks. The landmark detector may not find all possible landmarks on any given face.


This example modify from the post "Face Detection with Google Play services, Mobile Vision API", with fix of "FaceDetector error: Cannot resolve method setTrackingEnabled(boolean)", add the feature to detect landmarks on detected faces.


Sets detect all landmarks, by calling setLandmarkType(FaceDetector.ALL_LANDMARKS) when build FaceDetector with FaceDetector.Builder.

Then call getLandmarks() for each detected faces.

com.example.androidfacedetection.MainActivity.java
package com.example.androidfacedetection;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.FaceDetector;
import com.google.android.gms.vision.face.Landmark;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final int RQS_LOADIMAGE = 1;
    private Button btnLoad, btnDetFace;
    private ImageView imgView;
    private Bitmap myBitmap;

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

        btnLoad = (Button)findViewById(R.id.btnLoad);
        btnDetFace = (Button)findViewById(R.id.btnDetectFace);
        imgView = (ImageView)findViewById(R.id.imgview);

        btnLoad.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, RQS_LOADIMAGE);
            }
        });

        btnDetFace.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(myBitmap == null){
                    Toast.makeText(MainActivity.this,
                            "myBitmap == null",
                            Toast.LENGTH_LONG).show();
                }else{
                    detectFace();
                    Toast.makeText(MainActivity.this,
                            "Done",
                            Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RQS_LOADIMAGE
                && resultCode == RESULT_OK){

            if(myBitmap != null){
                myBitmap.recycle();
            }

            try {
                InputStream inputStream =
                        getContentResolver().openInputStream(data.getData());
                myBitmap = BitmapFactory.decodeStream(inputStream);
                inputStream.close();
                imgView.setImageBitmap(myBitmap);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /*
    reference:
    https://search-codelabs.appspot.com/codelabs/face-detection
     */
    private void detectFace(){

        //Create a Paint object for drawing with
        Paint myRectPaint = new Paint();
        myRectPaint.setStrokeWidth(5);
        myRectPaint.setColor(Color.GREEN);
        myRectPaint.setStyle(Paint.Style.STROKE);

        Paint landmarksPaint = new Paint();
        landmarksPaint.setStrokeWidth(10);
        landmarksPaint.setColor(Color.RED);
        landmarksPaint.setStyle(Paint.Style.STROKE);

        //Create a Canvas object for drawing on
        Bitmap tempBitmap = Bitmap.createBitmap(myBitmap.getWidth(), myBitmap.getHeight(), Bitmap.Config.RGB_565);
        Canvas tempCanvas = new Canvas(tempBitmap);
        tempCanvas.drawBitmap(myBitmap, 0, 0, null);

        //Detect the Faces


        //!!!
        //Cannot resolve method setTrackingEnabled(boolean)
        //FaceDetector faceDetector = new FaceDetector.Builder(getApplicationContext()).build();
        //faceDetector.setTrackingEnabled(false);

        FaceDetector faceDetector =
                new FaceDetector.Builder(getApplicationContext())
                .setTrackingEnabled(false)
                        .setLandmarkType(FaceDetector.ALL_LANDMARKS)
                        .build();

        Frame frame = new Frame.Builder().setBitmap(myBitmap).build();
        SparseArray<Face> faces = faceDetector.detect(frame);

        //Draw Rectangles on the Faces
        for(int i=0; i<faces.size(); i++) {
            Face thisFace = faces.valueAt(i);
            float x1 = thisFace.getPosition().x;
            float y1 = thisFace.getPosition().y;
            float x2 = x1 + thisFace.getWidth();
            float y2 = y1 + thisFace.getHeight();
            tempCanvas.drawRoundRect(new RectF(x1, y1, x2, y2), 2, 2, myRectPaint);

            //get Landmarks for the first face
            List<Landmark> landmarks = thisFace.getLandmarks();
            for(int l=0; l<landmarks.size(); l++){
                PointF pos = landmarks.get(l).getPosition();
                tempCanvas.drawPoint(pos.x, pos.y, landmarksPaint);
            }
        }

        imgView.setImageDrawable(new BitmapDrawable(getResources(),tempBitmap));

    }
}


Other files, AndroidManifest.xml and layout/activity_main.xml, refer to the post "Face Detection with Google Play services, Mobile Vision API".

Next:
Google Play services Face Detection, detect Smiling

Saturday, August 15, 2015

Android NDK Beginners Guide - Second Edition

Discover the native side of Android and inject the power of C/C++ in your applications

Android NDK Beginners Guide - Second Edition

About This Book
  • Create high performance mobile applications with C/C++ and integrate with Java
  • Exploit advanced Android features such as graphics, sound, input, and sensing
  • Port and reuse your own or third-party libraries from the prolific C/C++ ecosystem
Who This Book Is For
Are you an Android Java programmer who needs more performance? Are you a C/C++ developer who doesn't want to bother with the complexity of Java and its out-of-control garbage collector? Do you want to create fast intensive multimedia applications or games? If you've answered yes to any of these questions then this book is for you. With some general knowledge of C/C++ development, you will be able to dive headfirst into native Android development.

What You Will Learn
  • Build your first Android native project from scratch
  • Communicate with Java through Java Native Interfaces
  • Learn the key design intricacies of creating a native OpenGL ES 2.0 graphics application
  • Initialize, play, and record sound and music with OpenSL ES
  • Handle input events and sensors to create different interaction types
  • Port an existing library on Android by compiling most common C++ frameworks on Android
  • Interface and optimize the existing code with RenderScript
  • Combine graphics, sound, input, sensors, and physics in your application
In Detail
Android NDK is all about injecting high-performance and portable code into your mobile apps by exploiting the maximum speed of the device they run on.

This book will show you how to create C/C++-enabled mobile applications and integrate them with Java. The books starts with teaching you how to access native API and port libraries used in some of the most successful Android applications. Next, you will move on to create a real native application project through the complete implementation of a native API and porting existing third-party libraries. Moving forward, you will learn how to access the keyboard and input peripherals and read accelerometer or orientation sensors. Finally, you will dive into more advanced topics such as RenderScript.

Android Application Programming with OpenCV 3

Build Android apps to capture, manipulate, and track objects in 2D and 3D

Android Application Programming with OpenCV 3

About This Book
  • Capture and display real-time videos and still images
  • Manipulate image data using OpenCV and Apache Commons Math
  • A step-by-step guide to building Android and CV applications
Who This Book Is For
If you are a Java developer who is new to computer vision and would like to learn through application development, then this book is for you. You are expected to have a mobile device running Android 2.2 (Froyo) or greater, including a camera. Experience in Java is a must.

What You Will Learn
  • Install OpenCV and an Android development environment on Windows, Mac, or Linux
  • Control a camera and use its perspective in augmented reality
  • Share photos with other apps via Android's MediaStore and Intent classes
  • Create GUIs and handle events using Android activities and OpenCV
  • Train an image recognizer that can locate famous paintings in a scene
  • Apply "curves" and other color transformations to simulate the look of old photos
  • Apply convolution filters that sharpen, blur, emboss, or darken the details of an image
In Detail
Android Application Programming with OpenCV 3 is a practical, hands-on guide to computer vision and mobile app development. It shows how to capture, manipulate, and analyze images while building an application that combines photography and augmented reality. To help the reader become a well-rounded developer, the book covers OpenCV (a computer vision library), Android SDK (a mobile app framework), OpenGL ES (a 3D graphics framework), and even JNI (a Java/C++ interoperability layer).

Now in its second edition, the book offers thoroughly reviewed code, instructions, and explanations. It is fully updated to support OpenCV 3 and Android 5, as well as earlier versions. Although it focuses on OpenCV's Java bindings, this edition adds an extensive chapter on JNI and C++, so that the reader is well primed to use OpenCV in other environments.

Learning Unreal Engine Android Game Development

Tap into the power of Unreal Engine 4 and create exciting games for the Android platform

Learning Unreal Engine Android Game Development

About This Book
  • Dive straight into making fully functional Android games with this hands-on guide
  • Learn about the entire Android pipeline, from game creation to game submission
  • Use Unreal Engine 4 to create a first-person puzzle game
Who This Book Is For
If you are a game developer, designer, artist, or a beginner in the gaming industry and want to make Android games with Unreal Engine 4 efficiently, this book is ideal for you.

What You Will Learn
  • Install, build, and compile UE4 and prepare it for Android development
  • Understand the process of creating an Android game and its requirements
  • Import assets into your game and set their properties
  • Familiarize yourself with classes and how to use them
  • Script using Blueprint, an easy-to-use scripting tool
  • Use Matinee to create cinematics, set pieces, and scripted events
  • Package your game for Android devices and port it to the Google Play Store
In Detail
Have you ever wanted to create games that will get users hooked to their phones? Unreal Engine 4, with all its tools and power, will help make your dreams come true! Designed to get you working with Unreal Engine 4 from the very first page, this book will quickly guide you through the basics in the first two chapters. Once you get the hang of things, we will start developing our game―Bloques!

Bloques is a puzzle game with four rooms. Each room will be more challenging than the previous, and as you develop, you will graduate from movement and character control to AI and spawning. Once you've created the game, you will learn how to port and publish your game to the Google Play Store.

In addition to building an Android game from start to finish, you will also discover how to generate revenue, and how to optimize game performance using the tools and functionalities the engine provides. With this book, you will be inspired to come up with your own great ideas for your future game development projects.

Friday, August 14, 2015

FaceDetector error: Cannot resolve method setTrackingEnabled(boolean)

As mentioned in last post "Face Detection with Google Play services, Mobile Vision API (with demo APK)", calling setTrackingEnabled(false) method of FaceDetector object return error of "Cannot resolve method setTrackingEnabled(boolean)".

After checking reference of com.google.android.gms.vision.face.FaceDetector, setTrackingEnabled(boolean) is not a method of FaceDetector class. It's a method of com.google.android.gms.vision.face.FaceDetector.Builder class.


public FaceDetector.Builder setTrackingEnabled (boolean trackingEnabled)
Enables or disables face tracking, which will maintain a consistent ID for each face when processing consecutive frames. Default: true


If your code uses a MultiProcessor or FocusingProcessor instance, tracking must be enabled. Having tracking enabled is also recommended for handling live video.

Tracking should be disabled for handling a series of non-consecutive still images.


To fix the error, modify the code
        FaceDetector faceDetector = new FaceDetector.Builder(getApplicationContext()).build();
        faceDetector.setTrackingEnabled(false);

to:
        FaceDetector faceDetector =
                new FaceDetector.Builder(getApplicationContext())
                .setTrackingEnabled(false)
                .build();


Face Detection with Google Play services, Mobile Vision API (with demo APK)

With the release of Google Play services 7.8, new Mobile Vision APIs was added, to include a new Face API that finds human faces in images and video. ~ source: Android Developers Blog - Face Detection in Google Play services.

Follow the code lab "Face Detection with the Mobile Vision API", you can create an App to process an image that is already present in your app, to detects faces.

In this exercise, I modify the code lab to add the feature to load photos using Intent of ACTION_GET_CONTENT, such that you can test it with your own photos. APK is available on the bottom of this post.


- Make sure you have Google Play Services 7.8 or higher installed on your testing devices (Check your installed Google Play Services version).

- Create your app of "Blank Activity", with Min Sdk Version of API 17 (Android 4.2.2) or higher.

- Add dependency for Google Play services in Android Studio Project, make sure you have Google Play Services version 26 or higher installed.

- Edit your AndroidManifest.xml to add the statement of <meta-data...>:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidfacedetection" >
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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>
        <meta-data
            android:name="com.google.android.gms.vision.DEPENDENCIES"
            android:value="face" />
    </application>

</manifest>


layout/activity_main.xml
<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="18dp"
        android:text="Face Detection with the Mobile Vision API" />

    <Button
        android:id="@+id/btnLoad"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Load Photo"/>

    <Button
        android:id="@+id/btnDetectFace"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Detect Face" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imgview"/>

</LinearLayout>


com.example.androidfacedetection.MainActivity.java
package com.example.androidfacedetection;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.FaceDetector;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

    private static final int RQS_LOADIMAGE = 1;
    private Button btnLoad, btnDetFace;
    private ImageView imgView;
    private Bitmap myBitmap;

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

        btnLoad = (Button)findViewById(R.id.btnLoad);
        btnDetFace = (Button)findViewById(R.id.btnDetectFace);
        imgView = (ImageView)findViewById(R.id.imgview);

        btnLoad.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, RQS_LOADIMAGE);
            }
        });

        btnDetFace.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(myBitmap == null){
                    Toast.makeText(MainActivity.this,
                            "myBitmap == null",
                            Toast.LENGTH_LONG).show();
                }else{
                    detectFace();
                    Toast.makeText(MainActivity.this,
                            "Done",
                            Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RQS_LOADIMAGE
                && resultCode == RESULT_OK){

            if(myBitmap != null){
                myBitmap.recycle();
            }

            try {
                InputStream inputStream =
                        getContentResolver().openInputStream(data.getData());
                myBitmap = BitmapFactory.decodeStream(inputStream);
                inputStream.close();
                imgView.setImageBitmap(myBitmap);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /*
    reference:
    https://search-codelabs.appspot.com/codelabs/face-detection
     */
    private void detectFace(){

        //Create a Paint object for drawing with
        Paint myRectPaint = new Paint();
        myRectPaint.setStrokeWidth(5);
        myRectPaint.setColor(Color.RED);
        myRectPaint.setStyle(Paint.Style.STROKE);

        //Create a Canvas object for drawing on
        Bitmap tempBitmap = Bitmap.createBitmap(myBitmap.getWidth(), myBitmap.getHeight(), Bitmap.Config.RGB_565);
        Canvas tempCanvas = new Canvas(tempBitmap);
        tempCanvas.drawBitmap(myBitmap, 0, 0, null);

        //Detect the Faces
        FaceDetector faceDetector = new FaceDetector.Builder(getApplicationContext()).build();

        //!!!
        //Cannot resolve method setTrackingEnabled(boolean)
        //skip for now
        //faceDetector.setTrackingEnabled(false);

        Frame frame = new Frame.Builder().setBitmap(myBitmap).build();
        SparseArray<Face> faces = faceDetector.detect(frame);

        //Draw Rectangles on the Faces
        for(int i=0; i<faces.size(); i++) {
            Face thisFace = faces.valueAt(i);
            float x1 = thisFace.getPosition().x;
            float y1 = thisFace.getPosition().y;
            float x2 = x1 + thisFace.getWidth();
            float y2 = y1 + thisFace.getHeight();
            tempCanvas.drawRoundRect(new RectF(x1, y1, x2, y2), 2, 2, myRectPaint);
        }
        imgView.setImageDrawable(new BitmapDrawable(getResources(),tempBitmap));

    }
}


In my trial:
- The calling of faceDetector.setTrackingEnabled(false) report error of "Cannot resolve method setTrackingEnabled(boolean)"! So I skip it in this example.
(fixed in next post: "FaceDetector error: Cannot resolve method setTrackingEnabled(boolean)")

- It work on RedMi 2, running Android 4.4.4, with Google Play services version 7.8.99 installed.
- But cannot detect face on Nexus 7 2012 (WITHOUT front camera) running Android 5.1.1, with the same Google Play services version 7.8.99 installed! with warning of "FaceDetectorHandle﹕ Native face detector not yet available.  Reverting to no-op detection".

Test on RedMi 2, running Android 4.4.4, with Google Play services version 7.8.99 installed.


download filesDownload the files (Android Studio Format).

download filesYou can also Download the APK here, for test without coding.


Next:
FaceDetector error: Cannot resolve method setTrackingEnabled(boolean)
Google Play services Face Detection, get Landmarks (eyes, nose, etc.)
- Detect Smiling
Introducing Face Detection in the Google Vision APIs, from 100 Days of Google Dev