Thursday, February 26, 2015

Sharpen and blur bitmap, convolution using ScriptIntrinsicConvolve3x3

This example show how to create sharpen and blur bitmap, by convolution using ScriptIntrinsicConvolve3x3.


package com.example.androidimageview;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicConvolve3x3;
import android.support.v7.app.ActionBarActivity;
import android.widget.ImageView;

public class MainActivity extends ActionBarActivity {

 ImageView imageA1, imageA2, imageB1, imageB2, imageC1, imageC2;

 Bitmap bitmapOriginal, bitmapBlur, bitmapSharpen;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  imageA1 = (ImageView) findViewById(R.id.imagea1);
  imageA2 = (ImageView) findViewById(R.id.imagea2);
  imageB1 = (ImageView) findViewById(R.id.imageb1);
  imageB2 = (ImageView) findViewById(R.id.imageb2);
  imageC1 = (ImageView) findViewById(R.id.imagec1);
  imageC2 = (ImageView) findViewById(R.id.imagec2);

  bitmapOriginal = BitmapFactory.decodeResource(getResources(),
    R.drawable.ic_launcher);

  imageA1.setImageBitmap(bitmapOriginal);
  imageA2.setImageBitmap(bitmapOriginal);
  
  // create sharpen bitmap from blur bitmap
  bitmapSharpen = createBitmap_convolve(bitmapOriginal, matrix_sharpen);
  imageB1.setImageBitmap(bitmapSharpen);
  imageB2.setImageBitmap(bitmapSharpen);

  // create blur bitmap from original bitmap
  bitmapBlur = createBitmap_convolve(bitmapOriginal, matrix_blur);
  imageC1.setImageBitmap(bitmapBlur);
  imageC2.setImageBitmap(bitmapBlur);

 }
 
 float[] matrix_blur = 
  { 1.0f/9.0f, 1.0f/9.0f, 1.0f/9.0f,
    1.0f/9.0f, 1.0f/9.0f, 1.0f/9.0f,
    1.0f/9.0f, 1.0f/9.0f, 1.0f/9.0f};
 
 float[] matrix_sharpen = 
  { 0, -1, 0,
    -1, 5, -1,
    0, -1, 0};

 private Bitmap createBitmap_convolve(Bitmap src, float[] coefficients) {

  Bitmap result = Bitmap.createBitmap(src.getWidth(),
    src.getHeight(), src.getConfig());

  RenderScript renderScript = RenderScript.create(this);

  Allocation input = Allocation.createFromBitmap(renderScript, src);
  Allocation output = Allocation.createFromBitmap(renderScript, result);

  ScriptIntrinsicConvolve3x3 convolution = ScriptIntrinsicConvolve3x3
    .create(renderScript, Element.U8_4(renderScript));
  convolution.setInput(input);
  convolution.setCoefficients(coefficients);
  convolution.forEach(output);

  output.copyTo(result);
  renderScript.destroy();
  return result;
 }

}

<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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidimageview.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" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" >

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical" >

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

            <ImageView
                android:id="@+id/imagea2"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical" >

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

            <ImageView
                android:id="@+id/imageb2"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical" >

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

            <ImageView
                android:id="@+id/imagec2"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>
    </LinearLayout>

</LinearLayout>

Next:
interactive exercise of ScriptIntrinsicConvolve3x3

Wednesday, February 25, 2015

Create blur bitmap using RenderScript and ScriptIntrinsicBlur

ScriptIntrinsicBlur, added in API Level 17, is a Intrinsic Gausian blur filter. Applies a gaussian blur of the specified radius to all elements of an allocation.

Here is a example show how to create blur bitmap with RenderScript and ScriptIntrinsicBlur.


package com.example.androidimageview;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.support.v7.app.ActionBarActivity;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

 TextView textTitle;
 ImageView image1, image2, image3;
 SeekBar seekbarBlurRadius;
 
 Bitmap bitmapOriginal;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  textTitle = (TextView) findViewById(R.id.title);
  image1 = (ImageView) findViewById(R.id.image1);
  image2 = (ImageView) findViewById(R.id.image2);
  image3 = (ImageView) findViewById(R.id.image3);

  bitmapOriginal = BitmapFactory.decodeResource(getResources(),
    R.drawable.ic_launcher);

  image1.setImageBitmap(bitmapOriginal);

  // create blur bitmaps
  image2.setImageBitmap(createBitmap_ScriptIntrinsicBlur(bitmapOriginal, 25.0f));
  image3.setImageBitmap(createBitmap_ScriptIntrinsicBlur(bitmapOriginal, 25.0f));
  
  seekbarBlurRadius = (SeekBar)findViewById(R.id.blurradius);

  seekbarBlurRadius.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){

   @Override
   public void onProgressChanged(SeekBar seekBar, int progress,
     boolean fromUser) {
    
   }

   @Override
   public void onStartTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
    
   }

   @Override
   public void onStopTrackingTouch(SeekBar seekBar) {
    float radius = (float)seekbarBlurRadius.getProgress();
    image2.setImageBitmap(createBitmap_ScriptIntrinsicBlur(bitmapOriginal, radius));
    image3.setImageBitmap(createBitmap_ScriptIntrinsicBlur(bitmapOriginal, radius));
   }});

 }

 private Bitmap createBitmap_ScriptIntrinsicBlur(Bitmap src, float r) {
  
  //Radius range (0 < r <= 25)
  if(r <= 0){
   r = 0.1f;
  }else if(r > 25){
   r = 25.0f;
  }

  Bitmap bitmap = Bitmap.createBitmap(
    src.getWidth(), src.getHeight(),
    Bitmap.Config.ARGB_8888);

  RenderScript renderScript = RenderScript.create(this);

  Allocation blurInput = Allocation.createFromBitmap(renderScript, src);
  Allocation blurOutput = Allocation.createFromBitmap(renderScript, bitmap);

  ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(renderScript,
    Element.U8_4(renderScript));
  blur.setInput(blurInput);
  blur.setRadius(r);
  blur.forEach(blurOutput);

  blurOutput.copyTo(bitmap);
  renderScript.destroy();
  return bitmap;
 }

}

<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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidimageview.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" />
    
    <SeekBar
        android:id="@+id/blurradius"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="25"
        android:progress="25" />

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

    <ImageView
        android:id="@+id/image3"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />


</LinearLayout>


Tuesday, February 24, 2015

Home Automation For Dummies

The easy way to control your home appliances

Home Automation For Dummies

Do you want to control common household appliances and amenities from your smartphone or tablet, wherever you happen to be? Home Automation For Dummies guides you through installing and setting up app-controlled devices in your home, such as heating and air conditioning, lighting, multimedia systems, game consoles, and security and monitoring devices—and even suggests popular products to consider.

The saturation of the mobile market with smart devices has led to an upsurge in domestic devices, such as thermostats, refrigerators, smoke detectors, security systems, among others, that can be controlled by those devices. Both Google and Apple offer fully-integrated solutions for connecting mobile devices to home theater and audio systems, and now Google has branched out into smart thermostats and smoke detectors. If you've caught the bug and want to get your feet wet in this cool new phenomenon, Home Automation For Dummies gives you plain-English, step-by-step instructions for tech-ifying your home without breaking a sweat.
  • Provides clear instructions on remotely controlling your home appliances
  • Shows you how to set preferences to automatically adjust lighting or temperature
  • Explores digital "life hacks" that explain how non-app-ready appliances can be controlled via smart phones using third-party go-betweens
  • Covers an emerging segment of the industry that was one of the primary focuses of this year's Consumer Electronic Show
If you're looking to find new ways to simplify and better control your home environment using app-driven devices, your phone, or tablet, Home Automation For Dummies makes it easier.

Chinese Phone and Tablet Beginners User Guide: All Android Versions 4.0 Thru 5.0 Lollipop: Asus Cubot Huawei Iocean Jiayu Lenovo Oppo Oneplus Star THL Xiaomi Zopo ZTE & Others

Chinese Phone & Tablet Beginners User Guide: All Android Versions 4.0 Thru 5.0 Lollipop: Asus Cubot Huawei Iocean Jiayu Lenovo Oppo Oneplus Star THL Xiaomi Zopo ZTE & Others

This new guide is packed with all the essentials you will need, and contains almost 250 icons and illustrations to help a beginner use an android tablet or phone. The LOOK INSIDE feature previews extracts from throughout the guide, not only the beginning, to give you a better idea of the contents.

This new guide is covers all current android versions starting at version 4.0, released in 2011, right through to the latest version A.0, codenamed lollipop, which was launched in November 2014 and is being updated to millions of handsets.

There is also a section on leading Chinese phone models, advising website names, where you can obtain technical specifications and reviews, and some of the pitfalls of purchasing direct from China.

The guide is aimed at readers who have never operated any Android device previously, and is styled on my existing guide- Android User Guide for android versions 4.0 - 4.4 , which sold almost 900 copies through only two outlets in the last year with an almost 100% feedback. Feedback included words such as- a lifesaver, worth every penny, just right for beginners, well written, clear instructions, brilliant book. The most critical information, which a beginner needs, is explained in detail, click by click, generally in the order that the reader needs it, in the early parts of the guide, plus many links are provided to other external user guides for selected apps, which the reader can consult later. At the end of the guide is a three page summary of the icons and controls used in navigating the Android system, to serve as a reference chart for future use.

Most readers running version 4.4 KitKat will receive a free update to version 5.0, lollipop in any case, so this guide will give them a good idea of what to expect, when their device updates, and readers using the older versions of android- 4.0 - 4.3 will be able to get a feel for this brand new android version, if they are contemplating buying a new device.


ABOUT THE AUTHOR Having retired 2 years ago, after 30 years in export sales, marketing and IT, I looked around for something to fill in my time. I love technology and having owned countless unbranded Android smart phones, tablets and Android TV units, I felt there was a need for beginners' user guides, so I wrote this. I do hope that you will consider purchasing it. Thanks

CONTENTS
INTRODUCTION
PART A -BASIC CONTROLS & SWITCHING ON-ALL ANDROID VERSIONS
THE MAIN ICONS & NAVIGATION CONTROLS
GETTING TO KNOW YOUR DEVICE
SWITCHING ON FOR THE FIRST TIME
OVERCOMING THE SCREEN LOCK
CONNECTING TO YOUR WIRELESS NETWORK
ADJUSTING YOUR MOST IMPORTANT SETTINGS
OVERVIEW OF EMAIL & IMPORTING CONTACTS
PART B - APPLIES TO ANDROID 4 ONLY
LOCK SCREEN - ANDROID 4
QUICK SETTINGS MENU- ANDROID 4
DESKTOP SCREENS - ANDROID 4
CUSTOMISATION - ANDROID 4
CONTACTS APP - ANDROID 4
PHONE APP - ANDROID 4
TEXT MESSAGING APP - ANDROID 4
PART C - APPLIES TO ANDROID 5 LOLLIPOP ONLY
LOCK SCREEN - ANDROID 5
NOTIFICATION SETTINGS - ANDROID 5
QUICK SETTINGS MENU- ANDROID 5
DESKTOP SCREENS - ANDROID 5
CONTACTS APP USER GUIDE - ANDROID 5
MESSENGER APP USER GUIDE - ANDROID 5
PHONE APP USER GUIDE - ANDROID 5
PART D - APPLIES TO ALL ANDROID VERSIONS
GMAIL APP - UPDATED VERSION - USER GUIDE
K-9 MAIL USER GUIDE
TRANSFERRING DATA FROM WINDOWS PC TO YOUR DEVICE
CLOUD STORAGE
FILE MANAGEMENT
GOOGLE PLAY STORE
SOME OF THE BEST APPS
ANTIVIRUS
GOOGLE CALENDAR
MICROSOFT OFFICE
MUSIC PLAYER
PHOTOS
PRINTER
TASKS
VIDEO PLAYER
WEB BROWSERS
CREATING WEB PAGE DESKTOP SHORTCUTS
SMARTPHONES- AVOIDING EXCESS DATA CHARGES
SMARTPHONES - PREVENTING UNAUTHORISED USE
SMARTPHONES - LOST OR STOLEN
NAVIGATION CONTROL ICONS SUMMARY

Invert bitmap using ColorMatrix

Example to create inverted bitmap using ColorMatrix.


package com.example.androidimageview;

import android.support.v7.app.ActionBarActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

 TextView textTitle;
 ImageView image1, image2, image3, image4;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  textTitle = (TextView) findViewById(R.id.title);
  image1 = (ImageView) findViewById(R.id.image1);
  image2 = (ImageView) findViewById(R.id.image2);
  image3 = (ImageView) findViewById(R.id.image3);
  image4 = (ImageView) findViewById(R.id.image4);

  Bitmap bm = BitmapFactory.decodeResource(getResources(),
    R.drawable.ic_launcher);

  image1.setImageBitmap(bm);
  
  //invert
  image2.setImageBitmap(createInvertedBitmap(bm));
  image3.setImageBitmap(
    createInvertedBitmap(bm));
  
  //invert and invert
  image4.setImageBitmap(
    createInvertedBitmap(createInvertedBitmap(bm)));

 }

 private Bitmap createInvertedBitmap(Bitmap src) {
  ColorMatrix colorMatrix_Inverted = 
   new ColorMatrix(new float[] {
     -1,  0,  0,  0, 255,
     0, -1,  0,  0, 255,
     0,  0, -1,  0, 255,
     0,  0,  0,  1,   0});

  ColorFilter ColorFilter_Sepia = new ColorMatrixColorFilter(
    colorMatrix_Inverted);

  Bitmap bitmap = Bitmap.createBitmap(src.getWidth(), src.getHeight(),
    Bitmap.Config.ARGB_8888);
  Canvas canvas = new Canvas(bitmap);

  Paint paint = new Paint();

  paint.setColorFilter(ColorFilter_Sepia);
  canvas.drawBitmap(src, 0, 0, paint);

  return bitmap;
 }

}

<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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidimageview.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" />

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

    <ImageView
        android:id="@+id/image3"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
    
    <ImageView
        android:id="@+id/image4"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>

Monday, February 23, 2015

Create Sepia bitmap using ColorMatrix

Example to create spedia bitmap uwing ColorMatrix.


package com.example.androidimageview;

import android.support.v7.app.ActionBarActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

 TextView textTitle;
 ImageView image1, image2, image3;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  textTitle = (TextView) findViewById(R.id.title);
  image1 = (ImageView) findViewById(R.id.image1);
  image2 = (ImageView) findViewById(R.id.image2);
  image3 = (ImageView) findViewById(R.id.image3);

  Bitmap bm = BitmapFactory.decodeResource(getResources(),
    R.drawable.ic_launcher);

  image1.setImageBitmap(bm);
  image2.setImageBitmap(createSepia(bm));
  image3.setImageBitmap(createSepia(bm));

 }

 private Bitmap createSepia(Bitmap src) {
  ColorMatrix colorMatrix_Sepia = new ColorMatrix();
  colorMatrix_Sepia.setSaturation(0);
  
  ColorMatrix colorScale = new ColorMatrix();
  colorScale.setScale(1, 1, 0.8f, 1);
  
  colorMatrix_Sepia.postConcat(colorScale);
  
  ColorFilter ColorFilter_Sepia = new ColorMatrixColorFilter(
    colorMatrix_Sepia);

  Bitmap bitmap = Bitmap.createBitmap(src.getWidth(), src.getHeight(),
    Bitmap.Config.ARGB_8888);
  Canvas canvas = new Canvas(bitmap);

  Paint paint = new Paint();

  paint.setColorFilter(ColorFilter_Sepia);
  canvas.drawBitmap(src, 0, 0, paint);

  return bitmap;
 }

}

<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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidimageview.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" />

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

    <ImageView
        android:id="@+id/image3"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Create grayscale bitmap using ColorMatrix

Example to create grayscale bitmap uwing ColorMatrix.


package com.example.androidimageview;

import android.support.v7.app.ActionBarActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

 TextView textTitle;
 ImageView image1, image2, image3;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  textTitle = (TextView) findViewById(R.id.title);
  image1 = (ImageView) findViewById(R.id.image1);
  image2 = (ImageView) findViewById(R.id.image2);
  image3 = (ImageView) findViewById(R.id.image3);

  Bitmap bm = BitmapFactory.decodeResource(getResources(),
    R.drawable.ic_launcher);

  image1.setImageBitmap(bm);
  image2.setImageBitmap(createGrayscale(bm));
  image3.setImageBitmap(createGrayscale(bm));

 }

 private Bitmap createGrayscale(Bitmap src) {
  ColorMatrix colorMatrix_Sat0 = new ColorMatrix();
  colorMatrix_Sat0.setSaturation(0);
  ColorFilter ColorFilter_Grayscale = new ColorMatrixColorFilter(
    colorMatrix_Sat0);

  Bitmap bitmap = Bitmap.createBitmap(src.getWidth(), src.getHeight(),
    Bitmap.Config.ARGB_8888);
  Canvas canvas = new Canvas(bitmap);

  Paint paint = new Paint();

  paint.setColorFilter(ColorFilter_Grayscale);
  canvas.drawBitmap(src, 0, 0, paint);

  return bitmap;
 }

}

<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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidimageview.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" />

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

    <ImageView
        android:id="@+id/image3"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Android Hardware Interfacing with the BeagleBone Black

Design and implement Android apps that interface with your own custom hardware circuits and the BeagleBone Black

Android Hardware Interfacing with the BeagleBone Black

About This Book
  • Design custom apps that interact with the outside world via BeagleBone Black
  • Modify Android to recognize, configure, and communicate with sensors, LEDs, memory, and more
  • A step-by-step guide full of practical Android app examples that will help the users to create Android controlled devices that will use BeagleBone as hardware
Who This Book Is For
If you are an Android app developer who wants to experiment with the hardware capabilities of the BeagleBone Black platform, then this book is ideal for you. You are expected to have basic knowledge of developing Android apps but no prior hardware experience is required.

In Detail
This book explores using the Android OS on the BeagleBone Black hardware platform and provides an introduction to Android's unique approach to hardware interfacing. You'll be walked through the process of installing and configuring Android on your BeagleBone Black, as well as preparing your PC development environment to create Android applications that directly interface with hardware devices. Several example projects within this book introduce you to using the GPIO, SPI, and I2C hardware interfaces of the BeagleBone Black.

You'll create Android apps that communicate directly with actual hardware components such as sensors, memory chips, switches, and LEDs. Step-by-step guidance through both the software and hardware portions of these projects is provided. Combining all of the previous projects into a single project that uses GPIO, SPI, and I2C together, you will explore the details of creating an advanced hardware interfacing app. Finally, you'll be provided with information on transitioning prototype code into code suitable for deployment on an Android-based device. With a variety of example apps that demonstrate key hardware communication concepts, this book will help you become an Android hardware interfacing pro in no time.

Saturday, February 21, 2015

Various effect of PorterDuff.Mode when using setColorFilter() on ImageView

Last post show a simple example to "Colorize ImageView, using setColorFilter() with Mode.MULTIPLY".  Actually, we have a number of other PorterDuff.Mode. This example show the effects of various PorterDuff.Mode.


package com.example.androidimageview;

import android.support.v7.app.ActionBarActivity;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {
 
 TextView textTitle;
 ImageView image1;
 SeekBar barR, barG, barB, barAlpha;
 Spinner spinnerMode;
 
 Mode[] modeValues;
 String[] modeName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textTitle = (TextView)findViewById(R.id.title);
        image1 = (ImageView)findViewById(R.id.image1);
     barR = (SeekBar)findViewById(R.id.r);
     barG = (SeekBar)findViewById(R.id.g);
     barB = (SeekBar)findViewById(R.id.b);
     barAlpha = (SeekBar)findViewById(R.id.alpha);
     
     barR.setOnSeekBarChangeListener(myOnSeekBarChangeListener);
     barG.setOnSeekBarChangeListener(myOnSeekBarChangeListener);
     barB.setOnSeekBarChangeListener(myOnSeekBarChangeListener);
     barAlpha.setOnSeekBarChangeListener(myOnSeekBarChangeListener);
     
     //default color
     int defaultColor = barAlpha.getProgress() * 0x1000000
    + barR.getProgress() * 0x10000
    + barG.getProgress() * 0x100
    + barB.getProgress();
  image1.setColorFilter(defaultColor, Mode.MULTIPLY);
  
  prepareMode();
  spinnerMode = (Spinner) findViewById(R.id.selmode);
  ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
    android.R.layout.simple_spinner_item, modeName);
  adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  spinnerMode.setAdapter(adapter);
  spinnerMode.setOnItemSelectedListener(myOnItemSelectedListener);
    }
    
    OnItemSelectedListener myOnItemSelectedListener = new OnItemSelectedListener(){

  @Override
  public void onItemSelected(AdapterView<?> parent, View view,
    int position, long id) {
   updateMode();
  }

  @Override
  public void onNothingSelected(AdapterView<?> parent) {}};

    OnSeekBarChangeListener myOnSeekBarChangeListener = new OnSeekBarChangeListener(){

  @Override
  public void onProgressChanged(SeekBar seekBar, int progress,
    boolean fromUser) {
   updateMode();
  }

  @Override
  public void onStartTrackingTouch(SeekBar seekBar) {}

  @Override
  public void onStopTrackingTouch(SeekBar seekBar) {} 
    };
    
    private void updateMode(){
     int selectedModePos = spinnerMode.getSelectedItemPosition();
     Mode selectedMode = modeValues[selectedModePos];
     //Colorize ImageView
  int newColor = barAlpha.getProgress() * 0x1000000
    + barR.getProgress() * 0x10000
    + barG.getProgress() * 0x100
    + barB.getProgress();
  image1.setColorFilter(newColor, selectedMode);
    }
    
    private void prepareMode(){
     
     modeValues = PorterDuff.Mode.values();
     
     modeName = new String[modeValues.length];
  
  for(int i=0; i<modeValues.length; i++){
   modeName[i] = modeValues[i].name();
  }
    }
}

<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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidimageview.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" />
    
    <Spinner
        android:id="@+id/selmode"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <SeekBar
        android:id="@+id/r"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="255" />

    <SeekBar
        android:id="@+id/g"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="255" />

    <SeekBar
        android:id="@+id/b"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="255" />

    <SeekBar
        android:id="@+id/alpha"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="255" />

    <ImageView
        android:id="@+id/image1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/ic_launcher" />

</LinearLayout>


download filesDownload the files.

Wednesday, February 18, 2015

Colorize ImageView, using setColorFilter()

This example show how to colorize ImageView, using setColorFilter() and android.graphics.PorterDuff.Mode.MULTIPLY.



package com.example.androidimageview;

import android.support.v7.app.ActionBarActivity;
import android.graphics.PorterDuff.Mode;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {
 
 TextView textTitle;
 ImageView image1;
 SeekBar barR, barG, barB, barAlpha;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textTitle = (TextView)findViewById(R.id.title);
        image1 = (ImageView)findViewById(R.id.image1);
     barR = (SeekBar)findViewById(R.id.r);
     barG = (SeekBar)findViewById(R.id.g);
     barB = (SeekBar)findViewById(R.id.b);
     barAlpha = (SeekBar)findViewById(R.id.alpha);
     
     barR.setOnSeekBarChangeListener(myOnSeekBarChangeListener);
     barG.setOnSeekBarChangeListener(myOnSeekBarChangeListener);
     barB.setOnSeekBarChangeListener(myOnSeekBarChangeListener);
     barAlpha.setOnSeekBarChangeListener(myOnSeekBarChangeListener);
     
     //default color
     int defaultColor = barAlpha.getProgress() * 0x1000000
    + barR.getProgress() * 0x10000
    + barG.getProgress() * 0x100
    + barB.getProgress();
  image1.setColorFilter(defaultColor, Mode.MULTIPLY);
    }

    OnSeekBarChangeListener myOnSeekBarChangeListener = new OnSeekBarChangeListener(){

  @Override
  public void onProgressChanged(SeekBar seekBar, int progress,
    boolean fromUser) {

   //Colorize ImageView
   int newColor = barAlpha.getProgress() * 0x1000000
     + barR.getProgress() * 0x10000
     + barG.getProgress() * 0x100
     + barB.getProgress();
   image1.setColorFilter(newColor, Mode.MULTIPLY);
  }

  @Override
  public void onStartTrackingTouch(SeekBar seekBar) {}

  @Override
  public void onStopTrackingTouch(SeekBar seekBar) {} 
    };
}


<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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidimageview.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" />

    <SeekBar
        android:id="@+id/r"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="255" />

    <SeekBar
        android:id="@+id/g"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="255" />

    <SeekBar
        android:id="@+id/b"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="255" />

    <SeekBar
        android:id="@+id/alpha"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="255" />

    <ImageView
        android:id="@+id/image1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/ic_launcher" />

</LinearLayout>


Next:
Various effect of PorterDuff.Mode when using setColorFilter() on ImageView

Tuesday, February 17, 2015

Android Recipes: A Problem-Solution Approach for Android 5.0

Android Recipes: A Problem-Solution Approach for Android 5.0 offers more than 100 down-to-earth code recipes, and guides you step-by-step through a wide range of useful topics using complete and real-world working code examples. This book is updated to include the Android 5.0 SDK, as well as earlier releases.

Instead of abstract descriptions of complex concepts, in Android Recipes, you'll find live code examples. When you start a new project you can consider copying and pasting the code and configuration files from this book and then modifying them for your own customization needs.

Crammed with insightful instruction and helpful examples, this fourth edition of Android Recipes is your guide to writing apps for one of today’s hottest mobile platforms. It offers pragmatic advice that will help you get the job done quickly and well. This can save you a great deal of work over creating a project from scratch!

Android continues to be one of the leading mobile OS and development platforms driving today's mobile innovations and the apps ecosystem. Android appears complex, but offers a variety of organized development kits to those coming into Android with differing programming language skill sets.

What you’ll learn
  • Code for Android smartphones and tablets
  • Use external libraries to save time and effort
  • Boost app performance by using the Android NDK and RenderScript
  • Design apps for performance, responsiveness, and seamlessness
  • Send data between devices and other external hardware
  • Persist application data and share it between applications
  • Capture and play back various device media items
  • Communicate with web services
  • Get the most out of your user interface
Who this book is for
This book is a handy reference for all Android app developers.

Table of Contents
1. Layouts and Views
2. User Interaction
3. Communications and Networking
4. Interacting with Device Hardware and Media
5. Persisting Data
6. Interacting with the System
7. Graphics and Drawing
8. Working with Android NDK and Renderscript

Pro Android Games, 3rd edition, - covers Android 5.0

Pro Android Games

Combining actionable, real-world source code with graphics, Pro Android Games, Third Edition shows you how to build more sophisticated and addictive Android game apps with minimum effort. Harness the power of the latest Android 5.0 SDK to bring countless legendary, action-packed PC games to the Android platform.

With actionable real-world source code, this one of a kind book shows you how to build more sophisticated and addictive Android game apps, by leveraging the power of the recent advancements found in the new Android 5.0 software development kit as well as those you've counted on in earlier releases.

Multi-touch code gives these games and their players dynamic input and exchange ability, for a more realistic arcade game experience. Faster and better performance offers Android game players a more seamless, fun arcade experience like never before. There is also improved native C/C++ integration with Android's NDK as well, which makes coding, compiling, and converting both productive and efficient with gains in app performance.

Pro Android Games, Third Edition features the following improvements:
  • Updates to the latest version of the Android SDK, NDK, plus the latest Android Studio and Eclipse IDEs
  • Greater focus on tablets, ever changing device resolutions, and hardware specs
  • Native game development and hardware accelerated graphics
  • Bigger and better real world engines, such as Quake I and II plus an oldie from the previous edition: Doom
  • Coverage of the new Android TV SDK APIs, UI, UX, multi-touch and multi-tasking features available with the Android 5.0 release
  • Advanced techniques for improving your game playing experience including better multi-tasking, improved performance optimization, battery management and more
  • A "Quake 3D"-like game app case study
You’ll definitely have fun, and perhaps you’ll even make some money. Enjoy!

In the last few years, Android has progressed with the debut of better fonts, new User Interface and Experience (UI/UX) APIs, tablet considerations, multi-touch capabilities, multi-tasking, faster performance, improved battery management techniques, and now the new Android TV SDK Apps for the Android game app developer repertoire.

What you’ll learn
  • How to develop and port game apps for the Android platform
  • What are some special tricks for Android smartphones and tablets
  • How to build a complex 2D game app for Android
  • What are some gaming tricks using OpenGL and JNI
  • How to integrate efficient graphics and create portability with latest OpenGL ES
  • How to build a 3D shooter game app that resembles the popular and once best-selling games Doom, Quake and Quake II
  • How to create fun experience using Bluetooth and Android Wear-based controllers
  • How to design and port using Android TV SDK
Who this book is for
This book is for savvy Android app developers who are looking for professional or advanced techniques for porting, augmenting and building 3D game apps that are complex, fun and lucrative.

Table of Contents
1. Welcome to Android Gaming
2. Gaming Tricks for Phones or Tablets
3. More Gaming Tricks with OpenGL and JNI
4. Efficient Graphics and Portability with OpenGL ES 2.0
5. 3D Shooters for Doom
6. 3D Shooters for Quake
7. 3D Shooters for Quake II
8. Fun With Bluetooth Controllers
9. Designing and Porting to Android TV
10. Deployment and Compilation Tips
11. Discovering Android Wear

Hello App Inventor!: Android programming for kids and the rest of us

Hello App Inventor!: Android programming for kids and the rest of us

Hello App Inventor! introduces creative young readers to the world of mobile programming—no experience required! Featuring more than 30 fun invent-it-yourself projects, this full-color, fun-to-read book starts with the building blocks you need to create a few practice apps. Then you'll learn the skills you need to bring your own app ideas to life.

Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications.

About the Book

Have you ever wondered how apps are made? Do you have a great idea for an app that you want to make reality? This book can teach you how to create apps for any Android device, even if you have never programmed before. With App Inventor, if you can imagine it, you can create it. Using this free, friendly tool, you can decide what you want your app to do and then click together colorful jigsaw-puzzle blocks to make it happen. App Inventor turns your project into an Android app that you can test on your computer, run on your phone, share with your friends, and even sell in the Google Play store.

Hello App Inventor! introduces young readers to the world of mobile programming. It assumes no previous experience. Featuring more than 30 invent-it-yourself projects, this book starts with basic apps and gradually builds the skills you need to bring your own ideas to life. We've provided the graphics and sounds to get you started right away. And a special Learning Points feature connects the example you're following to important computing concepts you'll use in any programming language.

App Inventor is developed and maintained by MIT.

What's Inside

- Covers MIT App Inventor 2
- How to create animated characters, games, experiments, magic tricks, and a Zombie Alarm clock
- Use advanced phone features like:
  • Movement sensors
  • Touch screen interaction
  • GPS
  • Camera
  • Text
  • Web connectivity
About the Authors

Paula Beerand Carl Simmons are professional educators and authors who spend most of their time training new teachers and introducing children to programming.

Table of Contents
  • Getting to know App Inventor
  • Designing the user interface
  • Using the screen: layouts and the canvas
  • Fling, touch, and drag: user interaction with the touch screen
  • Variables, decisions, and procedures
  • Lists and loops
  • Clocks and timers
  • Animation
  • Position sensors
  • Barcodes and scanners
  • Using speech and storing data on your phone
  • Web-enabled apps
  • Location-aware apps
  • From idea to app
  • Publishing and beyond

Monday, February 16, 2015

Set opacity (Alpha) of ImageView and background

This example show how to change opacity (Alpha) of ImageView and its background.


package com.example.androidimageview;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {
 
 TextView textTitle;
 ImageView image1, image2, image3;
 SeekBar opacityBar, backgroundOpacityBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textTitle = (TextView)findViewById(R.id.title);
        image1 = (ImageView)findViewById(R.id.image1);
        image2 = (ImageView)findViewById(R.id.image2);
        image3 = (ImageView)findViewById(R.id.image3);
     opacityBar = (SeekBar)findViewById(R.id.opacity);
     backgroundOpacityBar = (SeekBar)findViewById(R.id.backgroundopacity);
     
     image1.setBackgroundColor(0xFFff0000);
     image2.setBackgroundColor(0xFFff0000);
     image3.setBackgroundColor(0xFFff0000);
     
     opacityBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){

   @Override
   public void onProgressChanged(SeekBar seekBar, int progress,
     boolean fromUser) {
    //setAlpha (float alpha)
    //alpha between 0 and 1
    textTitle.setAlpha((float)progress/255);
    
    image1.setAlpha((float)progress/255);
    
    //setAlpha (int alpha) deprecated in API level 16.
    image2.setAlpha(progress);

    //require API level 16
    image3.setImageAlpha(progress);
   }

   @Override
   public void onStartTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
    
   }

   @Override
   public void onStopTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
    
   }});
     
     backgroundOpacityBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){

   @Override
   public void onProgressChanged(SeekBar seekBar, int progress,
     boolean fromUser) {
    
    int backgroundOpacity = progress * 0x01000000;
    
    image1.setBackgroundColor(backgroundOpacity + 0xff0000);
       image2.setBackgroundColor(backgroundOpacity + 0xff0000);
       image3.setBackgroundColor(backgroundOpacity + 0xff0000);
   }

   @Override
   public void onStartTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
    
   }

   @Override
   public void onStopTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
    
   }});
    }

}

<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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidimageview.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" />

    <SeekBar
        android:id="@+id/opacity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="255" />
    
    <SeekBar
        android:id="@+id/backgroundopacity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="255" />

    <ImageView
        android:id="@+id/image1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />
    <ImageView
        android:id="@+id/image2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />
    <ImageView
        android:id="@+id/image3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

</LinearLayout>


Next:
Colorize ImageView, using setColorFilter()

Change opacity of ImageView programmatically

This example show how to change opacity of ImageView, using setAlpha(float), deprecated setAlpha(int) and API 16's setImageAlpha(int).


package com.example.androidimageview;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {
 
 TextView textTitle;
 ImageView image1, image2, image3;
 SeekBar opacityBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textTitle = (TextView)findViewById(R.id.title);
        image1 = (ImageView)findViewById(R.id.image1);
        image2 = (ImageView)findViewById(R.id.image2);
        image3 = (ImageView)findViewById(R.id.image3);
     opacityBar = (SeekBar)findViewById(R.id.opacity);
     
     opacityBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){

   @Override
   public void onProgressChanged(SeekBar seekBar, int progress,
     boolean fromUser) {
    //setAlpha (float alpha)
    //alpha between 0 and 1
    textTitle.setAlpha((float)progress/255);
    
    image1.setAlpha((float)progress/255);
    
    //setAlpha (int alpha) deprecated in API level 16.
    image2.setAlpha(progress);

    //require API level 16
    image3.setImageAlpha(progress);
   }

   @Override
   public void onStartTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
    
   }

   @Override
   public void onStopTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub
    
   }});
    }

}

<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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidimageview.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" />

    <SeekBar
        android:id="@+id/opacity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="255" />

    <ImageView
        android:id="@+id/image1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />
    <ImageView
        android:id="@+id/image2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />
    <ImageView
        android:id="@+id/image3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

</LinearLayout>


Next:
Set opacity (Alpha) of ImageView and background

Google Compute Engine

Google Compute Engine

Learn how to run large-scale, data-intensive workloads with Compute Engine, Google’s cloud platform. Written by Google engineers, this tutorial walks you through the details of this Infrastructure as a Service by showing you how to develop a project with it from beginning to end. You’ll learn best practices for using Compute Engine, with a focus on solving practical problems.

With programming examples written in Python and JavaScript, you’ll also learn how to use Compute Engine with Docker containers and other platforms, frameworks, tools, and services. Discover how this IaaS helps you gain unparalleled performance and scalability with Google’s advanced storage and computing technologies.
  • Access and manage Compute Engine resources with a web UI, command-line interface, or RESTful interface
  • Configure, customize, and work with Linux VM instances
  • Explore storage options: persistent disk, Cloud Storage, Cloud SQL (MySQL in the cloud), or Cloud Datastore NoSQL service
  • Use multiple private networks, and multiple instances on each network
  • Build, deploy, and test a simple but comprehensive cloud computing application step-by-step
  • Use Compute Engine with Docker, Node.js, ZeroMQ, Web Starter Kit, AngularJS, WebSocket, and D3.js

Friday, February 13, 2015

Arduino Android Blueprints

Get the best out of Arduino by interfacing it with Android to create engaging interactive projects

Arduino Android Blueprints

About This Book
  • Learn how to interface with and control Arduino using Android devices
  • Discover how you can utilize the combined power of Android and Arduino for your own projects
  • Practical, step-by-step examples to help you unleash the power of Arduino with Android
Who This Book Is For
This book is for those who want to learn how to build exciting Arduino projects by interfacing it with Android. You will need to have some basic experience in electronics and programming. However, you don't need to have any previous experience with the Arduino or Android platforms.

In Detail
Arduino is an open source microcontroller built on a single-circuit board that is capable of receiving sensory input from the environment and controlling interactive physical objects.

The first few projects of this book will focus on displaying tweets within your app by connecting to Twitter, controlling basic functions of the Arduino board, and connecting an Arduino-powered weather station to an Android phone via Bluetooth. Next, you will learn how to use the Arduino Yun board to connect a standard USB camera to a local Wi-Fi network. At the end of the book, you will build a simple mobile robot, connect it to an Arduino board and a Bluetooth module, then control the robot from an Android phone using Bluetooth.

Each project is explained in a step-by-step fashion, always starting with the choice of components and the assembly of the hardware.

Tuesday, February 10, 2015

Visible DTMF Piano: Visualizer + ToneGenerator

Last post show a example of Visualizer for MediaPlayer, combine with the DTMF Piano using ToneGenerator, here is a Visible DTMF Piano, using Visualizer + ToneGenerator.

In this example, Visualizer is created with session 0, to make the audio output mix is visualized; permission MODIFY_AUDIO_SETTINGS is needed.



VisualizerView.java, extends View.
package com.example.androidaudiovisualizer;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

public class VisualizerView extends View {

 private byte[] mBytes;
 private float[] mPoints;
 private Rect mRect = new Rect();
 private Paint mForePaint = new Paint();

 public VisualizerView(Context context) {
  super(context);
  init();
 }

 public VisualizerView(Context context, AttributeSet attrs) {
  super(context, attrs);
  init();
 }

 public VisualizerView(Context context, AttributeSet attrs, int defStyleAttr) {
  super(context, attrs, defStyleAttr);
  init();
 }

 private void init() {
  mBytes = null;
  mForePaint.setStrokeWidth(1f);
  mForePaint.setAntiAlias(true);
  mForePaint.setColor(Color.rgb(0, 128, 255));
 }

 public void updateVisualizer(byte[] bytes) {
  mBytes = bytes;
  invalidate();
 }

 @Override
 protected void onDraw(Canvas canvas) {
  super.onDraw(canvas);
  if (mBytes == null) {
   return;
  }
  if (mPoints == null || mPoints.length < mBytes.length * 4) {
   mPoints = new float[mBytes.length * 4];
  }
  mRect.set(0, 0, getWidth(), getHeight());
  for (int i = 0; i < mBytes.length - 1; i++) {
   mPoints[i * 4] = mRect.width() * i / (mBytes.length - 1);
   mPoints[i * 4 + 1] = mRect.height() / 2
     + ((byte) (mBytes[i] + 128)) * (mRect.height() / 2) / 128;
   mPoints[i * 4 + 2] = mRect.width() * (i + 1) / (mBytes.length - 1);
   mPoints[i * 4 + 3] = mRect.height() / 2
     + ((byte) (mBytes[i + 1] + 128)) * (mRect.height() / 2)
     / 128;
  }
  canvas.drawLines(mPoints, mForePaint);
 }

}

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

    <TextView
        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" />
    
    <com.example.androidaudiovisualizer.VisualizerView
        android:id="@+id/myvisualizerview"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
    
    <GridView
        android:id="@+id/gridView"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:columnWidth="50dp"
        android:gravity="center"
        android:numColumns="3"
        android:stretchMode="columnWidth" >
    </GridView>

</LinearLayout>

MainActivity.java
package com.example.androidaudiovisualizer;

import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.media.audiofx.Visualizer;
import android.os.Bundle;

/*
 * needed in AndroidManifest.xml
 * android:minSdkVersion="9"
 * uses-permission of "android.permission.RECORD_AUDIO"
 * and "android.permission.MODIFY_AUDIO_SETTINGS"
 * 
 * reference: Android demo example -
 * ApiDemos > Media > AudioTx
 */

public class MainActivity extends ActionBarActivity {

 VisualizerView mVisualizerView;
 GridView DTMFPianoView;
 static final String[] numbers = new String[] { "1", "2", "3", "4", "5",
   "6", "7", "8", "9", "*", "0", "#" };

 static final int[] toneTypes = new int[] { ToneGenerator.TONE_DTMF_1,
   ToneGenerator.TONE_DTMF_2, ToneGenerator.TONE_DTMF_3,
   ToneGenerator.TONE_DTMF_4, ToneGenerator.TONE_DTMF_5,
   ToneGenerator.TONE_DTMF_6, ToneGenerator.TONE_DTMF_7,
   ToneGenerator.TONE_DTMF_8, ToneGenerator.TONE_DTMF_9,
   ToneGenerator.TONE_DTMF_S, ToneGenerator.TONE_DTMF_0, 
   ToneGenerator.TONE_DTMF_P
 };

 private Visualizer mVisualizer;

 int streamType;
 int volume;
 int durationMs;
 ToneGenerator toneGenerator;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  mVisualizerView = (VisualizerView) findViewById(R.id.myvisualizerview);

  initAudio();

  DTMFPianoView = (GridView) findViewById(R.id.gridView);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
          this, android.R.layout.simple_list_item_1, numbers);
        
        DTMFPianoView.setAdapter(adapter);
        
        DTMFPianoView.setOnItemClickListener(new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {
    toneGenerator.startTone(toneTypes[position], durationMs);
    
   }});
        
 }

 @Override
 protected void onPause() {
  super.onPause();
  if (isFinishing()) {
   mVisualizer.release();
  }
 }

 private void initAudio() {

  streamType = AudioManager.STREAM_MUSIC;
  volume = 50;
  durationMs = 500;
  toneGenerator = new ToneGenerator(streamType, volume);

  setupVisualizerFxAndUI();
  mVisualizer.setEnabled(true);

 }

 private void setupVisualizerFxAndUI() {

  // Creating a Visualizer on the output mix (audio session 0)
  // need permission MODIFY_AUDIO_SETTINGS
  mVisualizer = new Visualizer(0);

  mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
  mVisualizer.setDataCaptureListener(
    new Visualizer.OnDataCaptureListener() {
     public void onWaveFormDataCapture(Visualizer visualizer,
       byte[] bytes, int samplingRate) {
      mVisualizerView.updateVisualizer(bytes);
     }

     public void onFftDataCapture(Visualizer visualizer,
       byte[] bytes, int samplingRate) {
     }
    }, Visualizer.getMaxCaptureRate() / 2, true, false);

 }

}

Permission of "android.permission.RECORD_AUDIO" and "android.permission.MODIFY_AUDIO_SETTINGS" are needed in AndroidManifest.xml.


download filesDownload the files.

Monday, February 9, 2015

Create audio Visualizer for MediaPlayer

This example create audio Visualizer for MediaPlayer, reference Android demo example: ApiDemos > Media > AudioTx. Permission android.permission.RECORD_AUDIO is needed,  to use visualizer.

remark@2016-10-18:
I found that the example code removed from Android Studio examples list, may be it is  NOT work now.



Create custom VisualizerView extends View, VisualizerView.java
package com.example.androidaudiovisualizer;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

public class VisualizerView extends View {

 private byte[] mBytes;
 private float[] mPoints;
 private Rect mRect = new Rect();
 private Paint mForePaint = new Paint();

 public VisualizerView(Context context) {
  super(context);
  init();
 }

 public VisualizerView(Context context, AttributeSet attrs) {
  super(context, attrs);
  init();
 }

 public VisualizerView(Context context, AttributeSet attrs, int defStyleAttr) {
  super(context, attrs, defStyleAttr);
  init();
 }

 private void init() {
  mBytes = null;
  mForePaint.setStrokeWidth(1f);
  mForePaint.setAntiAlias(true);
  mForePaint.setColor(Color.rgb(0, 128, 255));
 }

 public void updateVisualizer(byte[] bytes) {
  mBytes = bytes;
  invalidate();
 }

 @Override
 protected void onDraw(Canvas canvas) {
  super.onDraw(canvas);
  if (mBytes == null) {
   return;
  }
  if (mPoints == null || mPoints.length < mBytes.length * 4) {
   mPoints = new float[mBytes.length * 4];
  }
  mRect.set(0, 0, getWidth(), getHeight());
  for (int i = 0; i < mBytes.length - 1; i++) {
   mPoints[i * 4] = mRect.width() * i / (mBytes.length - 1);
   mPoints[i * 4 + 1] = mRect.height() / 2
     + ((byte) (mBytes[i] + 128)) * (mRect.height() / 2) / 128;
   mPoints[i * 4 + 2] = mRect.width() * (i + 1) / (mBytes.length - 1);
   mPoints[i * 4 + 3] = mRect.height() / 2
     + ((byte) (mBytes[i + 1] + 128)) * (mRect.height() / 2)
     / 128;
  }
  canvas.drawLines(mPoints, mForePaint);
 }

}

Add <com.example.androidaudiovisualizer.VisualizerView> to layout file, 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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.androidaudiovisualizer.MainActivity" >

    <TextView
        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" />
    
    <com.example.androidaudiovisualizer.VisualizerView
        android:id="@+id/myvisualizerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

MainActivity.java
package com.example.androidaudiovisualizer;

import android.support.v7.app.ActionBarActivity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.audiofx.Visualizer;
import android.os.Bundle;

/*
 * Copy test.mp3 to /res/raw/ folder
 * 
 * needed in AndroidManifest.xml
 * android:minSdkVersion="9"
 * uses-permission of "android.permission.RECORD_AUDIO"
 * 
 * reference: Android demo example -
 * ApiDemos > Media > AudioTx
 */

public class MainActivity extends ActionBarActivity {

 VisualizerView mVisualizerView;

 private MediaPlayer mMediaPlayer;
 private Visualizer mVisualizer;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  mVisualizerView = (VisualizerView) findViewById(R.id.myvisualizerview);

  initAudio();
 }

 @Override
 protected void onPause() {
  super.onPause();
  if (isFinishing() && mMediaPlayer != null) {
   mVisualizer.release();
   mMediaPlayer.release();
   mMediaPlayer = null;
  }
 }

 private void initAudio() {
  setVolumeControlStream(AudioManager.STREAM_MUSIC);
  mMediaPlayer = MediaPlayer.create(this, R.raw.test);

  setupVisualizerFxAndUI();
  // Make sure the visualizer is enabled only when you actually want to
  // receive data, and
  // when it makes sense to receive data.
  mVisualizer.setEnabled(true);
  // When the stream ends, we don't need to collect any more data. We
  // don't do this in
  // setupVisualizerFxAndUI because we likely want to have more,
  // non-Visualizer related code
  // in this callback.
  mMediaPlayer
    .setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
     public void onCompletion(MediaPlayer mediaPlayer) {
      mVisualizer.setEnabled(false);
     }
    });
  mMediaPlayer.start();

 }

 private void setupVisualizerFxAndUI() {

  // Create the Visualizer object and attach it to our media player.
  mVisualizer = new Visualizer(mMediaPlayer.getAudioSessionId());
  mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
  mVisualizer.setDataCaptureListener(
    new Visualizer.OnDataCaptureListener() {
     public void onWaveFormDataCapture(Visualizer visualizer,
       byte[] bytes, int samplingRate) {
      mVisualizerView.updateVisualizer(bytes);
     }

     public void onFftDataCapture(Visualizer visualizer,
       byte[] bytes, int samplingRate) {
     }
    }, Visualizer.getMaxCaptureRate() / 2, true, false);
 }

}


Next example:
Visible DTMF Piano: Visualizer + ToneGenerator

Saturday, February 7, 2015

ProgressDialog and AsyncTask

Example of ProgressDialog, work with AsyncTask.



package com.example.android_er.androidprogressdialog;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {

    Button btnStart;

    MyAsyncTask myAsyncTask;

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

        btnStart=(Button)findViewById(R.id.start);
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this,
                        "- Start -",
                        Toast.LENGTH_LONG).show();

                myAsyncTask = new MyAsyncTask();
                myAsyncTask.execute();

            }
        });
    }

    class MyAsyncTask extends AsyncTask<Void, Integer, Void>{

        boolean running;
        ProgressDialog progressDialog;

        @Override
        protected Void doInBackground(Void... params) {
            int i = 10;
            while(running){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if(i-- == 0){
                    running = false;
                }

                publishProgress(i);

            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            progressDialog.setMessage(String.valueOf(values[0]));
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            running = true;

            progressDialog = ProgressDialog.show(MainActivity.this,
                    "ProgressDialog",
                    "Wait!");

            progressDialog.setCanceledOnTouchOutside(true);
            progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    running = false;
                }
            });

            Toast.makeText(MainActivity.this,
                    "Progress Start",
                    Toast.LENGTH_LONG).show();
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            Toast.makeText(MainActivity.this,
                    "Progress Ended",
                    Toast.LENGTH_LONG).show();

            progressDialog.dismiss();
        }

    }

}


<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:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

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

    <Button
        android:id="@+id/start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start"/>

</LinearLayout>


more:
Too busy in background thread of AsyncTask