Display available currencies java.util.Currency

This example list available currencies java.util.Currency. Please notice that the methods getAvailableCurrencies() and getDisplayName() used in this example introduced in API Level 19. So android:minSdkVersion in AndroidManifest.xml have to be set ="19".


package com.example.androidcurrency;

import java.util.ArrayList;
import java.util.Currency;
import java.util.List;
import java.util.Set;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

ListView listCurrency;
Set<Currency> availableCurrenciesSet;
List<Currency> availableCurrenciesList;
ArrayAdapter<Currency> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listCurrency = (ListView)findViewById(R.id.currencylist);

//available from API Level 19
availableCurrenciesSet =
Currency.getAvailableCurrencies();

availableCurrenciesList = new ArrayList<Currency>(availableCurrenciesSet);
adapter = new ArrayAdapter<Currency>(
this,
android.R.layout.simple_list_item_1,
availableCurrenciesList);
listCurrency.setAdapter(adapter);

listCurrency.setOnItemClickListener(new OnItemClickListener(){

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Currency currency = (Currency) parent.getItemAtPosition(position);
String currencyCode = currency.getCurrencyCode();
String displayName = currency.getDisplayName();
String symbol = currency.getSymbol();

Toast.makeText(MainActivity.this,
displayName + "\n" +
currencyCode + "\n" +
symbol,
Toast.LENGTH_LONG).show();
}});
}


}

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

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

<ListView
android:id="@+id/currencylist"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

</LinearLayout>



Related:
- Display currency symbols, hard coded.

How to Create a Basic Integrated Gear Application

The tutorial, by Samsung Developers, teaches developers how to build a basic sample application for SAP. This is a three-part series. It also teaches how to test the applications using the Emulator.
  • Part 1 is all about the development on the Android side.
  • Part 2 deals with the development on the Tizen side.
  • Part 3 is about the complete application for SAP, which is basically packaging of the Android part and the Tizen part.
    It also teaches how to test the applications using the Emulator.

Getting started with Qt 5.3.0 for WinRT

This tutorial video goes over the basic usage of Qt Creator and Visual Studio when developing Windows Phone and Windows Store Apps with Qt for WinRT. This includes application packaging steps required for uploading to the Windows Store and Windows Phone Store.

Qt, the leading cross-platform framework:
http://qt.digia.com
http://qt-project.com


Microsoft Surface Pro 3 - Launch Full Event Keynote

Microsoft announces Surface Pro 3 in NY City (Tuesday, May. 20), the tablet that can replace your laptop. It is the thinnest, lightest and most powerful Surface Pro yet.

Keynote with :
Satya Nadella, CEO. Microsoft
Panos Panay, Corp. Vice President, Surface™. Microsoft

Android WebView: display SVG using HTML and Javascript

This example show how to display SVG in WebView, using HTML and Javascript.


Scalable Vector Graphics (SVG) is an XML-based vector image format for two-dimensional graphics with support for interactivity and animation. The SVG specification is an open standard developed by the World Wide Web Consortium (W3C) since 1999. ~ Wikipedia.

You can convert graph file from PNG to SVG using inkscape. Save your svg file in /assets, same level of our html, mypage.html

Modify /assets/mypage.html from the former exercise of WebView.
<!DOCTYPE HTML>
<HTML>
<HEAD>
<script>

var p1;
var p2;
var canvas;
var context;
var cx;
var cy;
var x;
var y;
var canvasOffsetX;
var canvasOffsetY;

var imgSVG = new Image();
imgSVG.src = "test.svg";

function init(){
p1 = document.getElementById('p1');
p2 = document.getElementById('p2');
p1.innerHTML=navigator.userAgent;

canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
canvasOffsetX = canvas.getBoundingClientRect().left;
canvasOffsetY = canvas.getBoundingClientRect().top;

canvas.width = window.innerWidth - (2 * canvasOffsetX);
canvas.height = window.innerHeight - canvasOffsetY - 100;

context.drawImage(imgSVG, 0, 0);

}

</script>
</HEAD>
<BODY onload="init()" style="border:5px solid #000000;">

<p id='p1'>un-init</p>

<canvas id='myCanvas' style="border:1px solid #FF0000;">
Canvas not support!
</canvas>

<p id='p2'></p>

</BODY>
</HTML>

Detect touch and draw circle on Android WebView with Javascript

Last exercise show a simple WebView with touch detection on Android WebView, it's modify to draw circle when user touch and move on HTML canvas.


Modify /assets/mypage.html from last exercise.
<!DOCTYPE HTML>
<HTML>
<HEAD>
<script>

var p1;
var p2;
var canvas;
var context;
var cx;
var cy;
var x;
var y;
var canvasOffsetX;
var canvasOffsetY;

function init(){
p1 = document.getElementById('p1');
p2 = document.getElementById('p2');
p1.innerHTML=navigator.userAgent;

canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
canvasOffsetX = canvas.getBoundingClientRect().left;
canvasOffsetY = canvas.getBoundingClientRect().top;

canvas.width = window.innerWidth - (2 * canvasOffsetX);
canvas.height = window.innerHeight - canvasOffsetY - 100;
canvas.fillStyle="#a0a0a0";

canvas.addEventListener('touchstart', touchstartListener, false);
canvas.addEventListener('touchmove', touchmoveListener, false);
canvas.addEventListener('touchend', touchendListener, false);
canvas.addEventListener('touchenter', touchenterListener, false);
canvas.addEventListener('touchleave', touchleaveListener, false);
canvas.addEventListener('touchcancel', touchcancelListener, false);

}

function touchstartListener(event){
cx = event.changedTouches[0].pageX - canvasOffsetX;
cy = event.changedTouches[0].pageY - canvasOffsetY;
p2.innerHTML= "touchstart - <br/>"
+ cx + ":" + cy;
event.preventDefault();

context.rect(0, 0, canvas.width, canvas.height);
context.fillStyle="white";
context.fill();
}

function touchmoveListener(event){

x = event.changedTouches[0].pageX - canvasOffsetX;
y = event.changedTouches[0].pageY - canvasOffsetY;
var deltax = x-cx;
var deltay = y-cy;
var radius = Math.sqrt(deltax*deltax + deltay*deltay);
context.beginPath();
context.arc(cx, cy, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 1;
context.strokeStyle = '#003300';
context.stroke();

p2.innerHTML= "touchmove - <br/>"
+ x + ":" + y;
event.preventDefault();
}

function touchendListener(event){
p2.innerHTML= "touchend - <br/>"
+ event.changedTouches[0].pageX + ":" + event.changedTouches[0].pageY;
event.preventDefault();
}

function touchenterListener(event){
p2.innerHTML= "touchenter - <br/>"
+ event.changedTouches[0].pageX + ":" + event.changedTouches[0].pageY;
event.preventDefault();
}

function touchleaveListener(event){
p2.innerHTML= "touchleave - <br/>"
+ event.changedTouches[0].pageX + ":" + event.changedTouches[0].pageY;
event.preventDefault();
}

function touchcancelListener(event){
p2.innerHTML= "touchcancel - <br/>"
+ event.changedTouches[0].pageX + ":" + event.changedTouches[0].pageY;
event.preventDefault();
}

</script>
</HEAD>
<BODY onload="init()" style="border:5px solid #000000;">

<p id='p1'>un-init</p>

<canvas id='myCanvas' style="border:1px solid #FF0000;">
Canvas not support!
</canvas>

<p id='p2'></p>

</BODY>
</HTML>

IOIO Android Hardware Interface

IOIO is an open-source board designed for interfacing external hardware with Android.

Android WebView, detect touch events with Javascript.

This example show how to create hybrid web-app, using WebView. And detect the touch events with Javascript.


/assets/mypage.html, it will be loaded in our WebView, to perform the main function.
<!DOCTYPE HTML>
<HTML>
<HEAD>
<script>

var p1;
var p2;

function init(){
p1 = document.getElementById('p1');
p2 = document.getElementById('p2');
p1.innerHTML=navigator.userAgent;
var canvas = document.getElementById('myCanvas');
var canvasOffsetX = canvas.getBoundingClientRect().left;
var canvasOffsetY = canvas.getBoundingClientRect().top;

canvas.width = window.innerWidth - (2 * canvasOffsetX);
canvas.height = window.innerHeight - canvasOffsetY - 100;
canvas.fillStyle="#a0a0a0";

canvas.addEventListener('touchstart', touchstartListener, false);
canvas.addEventListener('touchmove', touchmoveListener, false);
canvas.addEventListener('touchend', touchendListener, false);
canvas.addEventListener('touchenter', touchenterListener, false);
canvas.addEventListener('touchleave', touchleaveListener, false);
canvas.addEventListener('touchcancel', touchcancelListener, false);

}

function touchstartListener(event){
p2.innerHTML= "touchstart - <br/>"
+ event.changedTouches[0].pageX + ":" + event.changedTouches[0].pageY;
event.preventDefault();
}

function touchmoveListener(event){
p2.innerHTML= "touchmove - <br/>"
+ event.changedTouches[0].pageX + ":" + event.changedTouches[0].pageY;
event.preventDefault();
}

function touchendListener(event){
p2.innerHTML= "touchend - <br/>"
+ event.changedTouches[0].pageX + ":" + event.changedTouches[0].pageY;
event.preventDefault();
}

function touchenterListener(event){
p2.innerHTML= "touchenter - <br/>"
+ event.changedTouches[0].pageX + ":" + event.changedTouches[0].pageY;
event.preventDefault();
}

function touchleaveListener(event){
p2.innerHTML= "touchleave - <br/>"
+ event.changedTouches[0].pageX + ":" + event.changedTouches[0].pageY;
event.preventDefault();
}

function touchcancelListener(event){
p2.innerHTML= "touchcancel - <br/>"
+ event.changedTouches[0].pageX + ":" + event.changedTouches[0].pageY;
event.preventDefault();
}

</script>
</HEAD>
<BODY onload="init()" style="border:5px solid #000000;">

<p id='p1'>un-init</p>

<canvas id='myCanvas' style="border:1px solid #FF0000;">
Canvas not support!
</canvas>

<p id='p2'></p>

</BODY>
</HTML>

/res/layout/activity_main.xml, with <WebView>.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
android:background="@android:color/background_dark"
tools:context="com.example.androidhybridwebview.MainActivity" >

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

<WebView
android:id="@+id/mybrowser"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>

</LinearLayout>

package com.example.androidhybridwebview;

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

public class MainActivity extends Activity {

WebView myBrowser;

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

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

}

Next:
Detect touch and draw circle on Android WebView with Javascript

Embed ISS Live video in WebView

Now you can view Live HD video from ISS (International Space Station) from UStream. And we can embed it in WebView. (Link to runnable APK at bottom of this post)




Create /assets/isslive.html
<html>
<head>
<meta name = "viewport" content = "width = device-width, height = device-height" />

<style>
iframe {
width: 100%;
height: 100%;
}
</style>

</head>
<body>

<iframe src="http://www.ustream.tv/embed/17074538?wmode=direct"
style="border: 0 none transparent;"
frameborder="no"></iframe><br />

</body>
</html>

/res/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:orientation="vertical"
tools:context="com.example.androidiss.MainActivity" >

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

<WebView
android:id="@+id/mybrowser"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>

</LinearLayout>

package com.example.androidiss;

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

public class MainActivity extends Activity {

WebView myBrowser;

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

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

Premission of "android.permission.INTERNET" if needed in AndroidManifest.xml.


download filesDownload the files.

Download APK to run on Android device.

Augmented Reality for Android Application Development

Augmented Reality for Android Application Development
Learn how to develop advanced Augmented Reality applications for Android

Augmented Reality for Android Application Development

Overview
  • Understand the main concepts and architectural components of an AR application
  • Step-by-step learning through hands-on programming combined with a background of important mathematical concepts
  • Efficiently and robustly implement some of the main functional AR aspects
In Detail

Augmented Reality offers the magical effect of blending the physical world with the virtual world, which brings applications from your screen into your hands. AR redefines advertising and gaming, as well as education. It will soon become a technology that will have to be mastered as a necessity by mobile application developers.

Augmented Reality for Android Application Development enables you to implement sensor-based and computer vision-based AR applications on Android devices. You will learn about the theoretical foundations and practical details of implemented AR applications, and you will be provided with hands-on examples that will enable you to quickly develop and deploy novel AR applications on your own.

Augmented Reality for Android Application Development will help you learn the basics of developing mobile AR browsers, how to integrate and animate 3D objects easily with the JMonkeyEngine, how to unleash the power of computer vision-based AR using the Vuforia AR SDK, and will teach you about popular interaction metaphors. You will get comprehensive knowledge of how to implement a wide variety of AR apps using hands-on examples.

This book will make you aware of how to use the AR engine, Android layout, and overlays, and how to use ARToolkit. Finally, you will be able to apply this knowledge to make a stunning AR application.

What you will learn from this book
  • Decide which AR approach is right for you: sensor-based or computer vision-based
  • Get camera-access for Android
  • Overlay 3D objects on physical images with the JMonkeyEngine
  • Learn how to use the GPS sensor to locate yourself in the world
  • Master orientation sensors
  • Learn the building blocks of implementing Augmented Reality Browsers
  • Understand the power of the Vuforia SDK for computer vision-based AR
  • Enable user interaction with Augmented Objects
Approach

A step-by-step tutorial-based guide aimed at giving you hands-on practical experience to develop AR applications for Android.

Who this book is written for

Augmented Reality for Android Application Development is for Android mobile application developers who are familiar with Android Development Tools and deployment, JMonkeyEngine, and the Vuforia SDK.

Stacking Notifications For Android Wear Is This Easy

Today’s post on #AndroidWear is from +Wayne Piekarski.





Stacking notifications with the Android Wear Developer Preview is really simple—it requires only a few lines of extra notification code:


Notification wearableNotification =
    new WearableNotifications.Builder(
        notificationCompatBuilder)
    .setGroup(“messages”)
    .build();


A few weeks ago, I published a new DevBytes video which covered how to implement stacking notifications with Android Wear:




In the video, I included a demonstration of what these notifications look like in the emulator, and thought it would be useful to share the code for the demo. If you’re just getting started with stacked notifications, this should be all you need to get up and running right away. So here it is, with some additional instructions below. The wearable-specific code is highlighted and in bold.


Bitmap bitmapMila = BitmapFactory.decodeResource(getResources(), R.drawable.mila128);

// Nuke all previous notifications and generate unique ids
NotificationManagerCompat.from(this).cancelAll();
int notificationId = 0;

// String to represent the group all the notifications will be a part of
final String GROUP_KEY_MESSAGES = "group_key_messages";

// Group notification that will be visible on the phone
NotificationCompat.Builder builderG = new NotificationCompat.Builder(this)
    .setContentTitle("2 Pet Notifications")
    .setContentText("Mila and Dylan both sent messages")
    .setSmallIcon(R.drawable.ic_launcher)
    .setLargeIcon(bitmapMila);
Notification summaryNotification = new WearableNotifications.Builder(builderG)
    .setGroup(GROUP_KEY_MESSAGES, WearableNotifications.GROUP_ORDER_SUMMARY)
    .build();

// Separate notifications that will be visible on the watch
Intent viewIntent1 = new Intent(this, MainActivity.class);
PendingIntent viewPendingIntent1 =
    PendingIntent.getActivity(this, notificationId+1, viewIntent1, 0);
NotificationCompat.Builder builder1 = new NotificationCompat.Builder(this)
    .addAction(R.drawable.ic_action_done, "Treat Fed", viewPendingIntent1)
    .setContentTitle("Message from Mila")
    .setContentText("What's for dinner? "
                    + "Can we have steak?")
    .setSmallIcon(R.drawable.ic_launcher);
Notification notification1 = new WearableNotifications.Builder(builder1)
    .setGroup(GROUP_KEY_MESSAGES)
    .build();

Intent viewIntent2 = new Intent(this, MainActivity.class);
PendingIntent viewPendingIntent2 =
     PendingIntent.getActivity(this, notificationId+2, viewIntent2, 0);
NotificationCompat.Builder builder2 = new NotificationCompat.Builder(this)
    .addAction(R.drawable.ic_action_done, "Water Filled", viewPendingIntent2)
    .setContentTitle("Message from Dylan")
    .setContentText("Can you refill our water bowl?")
    .setSmallIcon(R.drawable.ic_launcher);
Notification notification2 = new WearableNotifications.Builder(builder2)
    .setGroup(GROUP_KEY_MESSAGES)
    .build();

// Issue the group notification
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId+0, summaryNotification);

// Issue the separate wear notifications
notificationManager.notify(notificationId+2, notification2);
notificationManager.notify(notificationId+1, notification1);


Using the code is really simple:



  1. First, make sure you’ve followed the Android Wear Developer Preview instructions to get your IDE set up correctly.

  2. Once the IDE is ready, create a new Android project with all the defaults. Make sure it compiles and runs before you continue to make fixing any problems easier.

  3. Add the necessary support libraries by following the installation instructions so that your project supports wearable notifications.

  4. Create a method in your main activity called showTheNotifications(), and paste all the code into it.

  5. Call showTheNotifications() from your activity’s onCreate method to show the notifications automatically at startup. Alternatively, add a button that calls the method on click.

  6. Add the below imports, or just have your IDE auto-add the missing imports.
    import android.support.v4.app.NotificationCompat;
    import android.app.Notification;
    import android.app.PendingIntent;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.preview.support.v4.app.NotificationManagerCompat;
    import android.preview.support.wearable.notifications.WearableNotifications;
  7. Add the images on the right to your drawable directories.



    res/drawable-xxhdpi/ic_action_done.png



    res/drawable-nodpi/mila128.jpg


  8. Build the project. If there are any compile issues try a clean build of the project.

  9. You can now run the application on your phone, and see the results on the wearable.


And that’s basically it, it’s really simple! Once you have a good feel for how the code works, make sure to check out the stacking notifications documentation to learn more. Make sure to also familiarize yourself with the Android Wear Design Principles, which explain more about the types of icons that should be used for actions. For the picture of the dog, it’s important you use an image that is quite small, and not straight from a digital camera, since there are limits to the size of the images that can be handled by the API.


I hope this post is useful in helping you to get started with Android Wear notifications!

Learning Android Canvas

Learning Android Canvas
Develop and deploy graphics-rich Android applications using Android Canvas

Learning Android Canvas

Overview
  • Understand user interactions and respond to those actions
  • Discover how to work with graphics in Android from scratch
  • Using a step by step approach, create a graphics-rich, fully functional application
  • Use Nine-Patch image
In Detail

When you're writing an application in which you would like to perform specialized drawing and/or control the animation of graphics, you should do so by drawing through a canvas. A canvas works for you as an interface to the actual surface upon which your graphics will be drawn-it holds all of your "draw" calls. Via the Android Canvas, your drawing is actually performed on an underlying Bitmap, which is placed into the window.

Learning Android Canvas is a practical guide, which will help you develop applications that contain rich 2D graphics like backgrounds, buttons, and even some small games with static 2D graphics. The book is full of step-by-step lessons and practical examples. This book helps you develop rich graphical applications and some simple games.

Learning Android Canvas will help you understand everything that is required to develop an Android application that involves creating 2D graphics from scratch to a fully functional complete application. You will start with zero knowledge of using graphics within Android applications and will then go step by step to learn about different objects and techniques. In the end you will be able to develop a complete application fully loaded with graphics and functions.

The book will give you a detailed practical explanation of Nine-Patch images and its importance in designing layouts and backgrounds. We will also take a detailed look at user interactions such as touch, capturing the action, and responding to them accordingly. Finally we will have a working, fully functional graphic application that uses all the knowledge that we have acquired previously.

What you will learn from this book
  • Create a drawable thread to take away the load from the main thread
  • Develop important drawables and shapes
  • Understand the actions performed by users, capturing them, and responding to them
  • Unfold the basics of nested layouts
  • Design your own View classes and use them in the main class
  • Discover the graphics used as backgrounds of the whole screen or controls like buttons
  • Draw on the Android Canvas and Views
  • Set up the listener for touch events
Approach

This book is a fast-paced, practical, step-by-step tutorial guide full of examples that are easy to follow and implement.

Who this book is written for

This book is a great resource for developers who have basic Android development knowledge and want to work on graphics-rich applications and games but are totally new to working with graphics and Android Canvas.

Get touch pressure

MotionEvent provide getPressure() and getPressure(int pointerIndex) to get the touch pressure.

Example:

MyView.java
package com.example.androiddrawinview;

import java.util.ArrayList;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class MyView extends View {

private ArrayList<xy> drawList;
private boolean touching = false;

Paint paintTouchPointer_ONE;
Paint paintTouchPointer;

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

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

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

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(
MeasureSpec.getSize(widthMeasureSpec),
MeasureSpec.getSize(heightMeasureSpec));
}

private void init(){
paintTouchPointer = new Paint();
paintTouchPointer.setColor(Color.RED);
paintTouchPointer.setStyle(Paint.Style.FILL);

paintTouchPointer_ONE = new Paint();
paintTouchPointer_ONE.setColor(Color.BLUE);
paintTouchPointer_ONE.setStyle(Paint.Style.STROKE);
}

@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.GRAY);
if(touching){
for(xy pt : drawList){

float PRESSURE_ONE_RADIUS = 50;
float radius = pt.getPressure() * PRESSURE_ONE_RADIUS;

canvas.drawCircle(
pt.getX(),
pt.getY(),
radius,
paintTouchPointer);

canvas.drawCircle(
pt.getX(),
pt.getY(),
PRESSURE_ONE_RADIUS,
paintTouchPointer_ONE);
}
}
}

@Override
public boolean onTouchEvent(MotionEvent event) {

int action = event.getAction() & MotionEvent.ACTION_MASK;
switch(action){
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_DOWN:

ArrayList<xy> touchList = new ArrayList<xy>();
int pointerCount = event.getPointerCount();

for(int i=0; i < pointerCount; i++){
touchList.add(
new xy(
event.getX(i),
event.getY(i),
event.getPressure(i)));
}
drawList = touchList;
touching = true;
break;
default:
touching = false;
}

invalidate();
return true;
}

class xy{
float x;
float y;
float pressure;

public xy(float x, float y, float pressure){
this.x = x;
this.y = y;
this.pressure = pressure;
}

public float getX(){
return x;
}

public float getY(){
return y;
}

public float getPressure(){
return pressure;
}
}

}

/res/layout/fragment_main.xml, to include MyView in layout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android: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.androiddrawinview.MainActivity$PlaceholderFragment" >

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

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

<com.example.androiddrawinview.MyView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_margin="10dp" />
</LinearLayout>

</LinearLayout>

MainActivity.java, actually it is the default generated by Eclipse.
package com.example.androiddrawinview;

import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

public class MainActivity extends ActionBarActivity {

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

if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {

public PlaceholderFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}

}

/res/layout/activity_main.xml, auto generated by Eclipse.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.androiddrawinview.MainActivity"
tools:ignore="MergeRootFrame" />

download filesDownload the files.

Helping You Go Global with More Seamless Google Play Payments


By Ibrahim Elbouchikhi, Google Play Product Manager



Sales of apps and games on Google Play are up by more than 300 percent over the past year. And today, two-thirds of Google Play purchases happen outside of the United States, with international sales continuing to climb. We’re hoping to fuel this momentum by making Google Play payments easier and more convenient for people around the world.








PayPal support



Starting today, we're making it possible for people to choose PayPal for their Google Play purchases in 12 countries, including the U.S., Germany, and Canada. When you make a purchase on Google Play in these countries, you'll find PayPal as an option in your Google Wallet; just enter your PayPal account login and you'll easily be able to make purchases. Our goal is to provide users with a frictionless payment experience, and this new integration is another example of how we work with partners from across the payments industry to deliver this to the user.




Carrier billing and Google Play gift cards in more countries



Carrier billing—which lets people charge purchases in Google Play directly to their phone bill—continues to be a popular way to pay. We’ve just expanded coverage to seven more countries for a total of 24, including Singapore, Thailand and Taiwan. That means almost half of all Google Play users have this option when making their purchases.



We’ve also made Google Play gift cards available to a total of 13 countries, including Japan and Germany.




Support for developer sales in more countries



Developers based in 13 new countries can now sell apps on Google Play (with new additions such as Indonesia, Malaysia and Turkey), bringing the total to 45 countries with support for local developers. We’ve also increased our buyer currency support to 28 new countries, making it even easier for you to tailor your pricing in 60 countries.




Nothing for you to do!



Of course, as developers, when it comes to payments, there’s nothing for you to do; we process all payments, reconcile all currencies globally, and make a monthly deposit in your designated bank account. This means you get to focus on what you do best: creating beautiful and engaging apps and games.



Visit developer.android.com for more information.


Per-country availability of forms of payment is summarized here.




Voice Application Development for Android

A practical guide to develop advanced and exciting voice applications for Android using open source software

Voice Application Development for Android

Overview
  • A comprehensive guide containing all the best practices for voice application development for Android
  • Progress quickly from basic apps to more advanced topics
  • Written in an easy-to-follow style with detailed descriptions of the included code examples to help you learn quickly and efficiently
  • You can download the updated code here

In Detail

Speech technology has been around for some time now. However, it has only more recently captured the imagination of the general public with the advent of personal assistants on mobile devices that you can talk to in your own language. The potential of voice apps is huge as a novel and natural way to use mobile devices.

Voice Application Development for Android is a practical, hands-on guide that provides you with a series of clear, step-by-step examples which will help you to build on the basic technologies and create more advanced and more engaging applications. With this book, you will learn how to create useful voice apps that you can deploy on your own Android device in no time at all.

This book introduces you to the technologies behind voice application development in a clear and intuitive way. You will learn how to use open source software to develop apps that talk and that recognize your speech. Building on this, you will progress to developing more complex apps that can perform useful tasks, and you will learn how to develop a simple voice-based personal assistant that you can customize to suit your own needs.

For more interesting information about the book, visit http://lsi.ugr.es/zoraida/androidspeechbook.

What you will learn from this book

  • Use text-to-speech synthesis so that your device can talk to you
  • Enable your device to recognize your speech
  • Create simple voice interactions to get information and carry out commands
  • Develop a voice app that engages in a dialogue with you to collect the information required to perform a transaction
  • Use grammars to enable your app to understand the meaning behind your words
  • Make use of different languages in your apps
  • Add multimodal interaction to your apps as an alternative to speech
  • Build a voice-based personal assistant using an open source development platform for chatbots

Approach

This book will give beginners an introduction to building voice-based applications on Android. It will begin by covering the basic concepts and will build up to creating a voice-based personal assistant. By the end of this book, you should be in a position to create your own voice-based applications on Android from scratch in next to no time.

Who this book is written for

Voice Application Development for Android is for all those who are interested in speech technology and for those who, as owners of Android devices, are keen to experiment with developing voice apps for their devices. It will also be useful as a starting point for professionals who are experienced in Android application development but who are not familiar with speech technologies and the development of voice user interfaces. Some background in programming in general, particularly in Java, is assumed.

Xiaomi Tablet

Android NDK Game Development Cookbook

Android NDK Game Development Cookbook

Over 70 exciting recipes to help you develop mobile games for Android in C++

Overview
  • Tips and tricks for developing and debugging mobile games on your desktop
  • Enhance your applications by writing multithreaded code for audio playback, network access, and asynchronous resource loading
  • Enhance your game development skills by using modern OpenGL ES and develop applications without using an IDE
  • Features two ready-to-run Android games
In Detail

Android NDK is used for multimedia applications which require direct access to a system's resources. Android NDK is also the key for portability, which in turn provides a reasonably comfortable development and debugging process using familiar tools such as GCC and Clang toolchains. If your wish to build Android games using this amazing framework, then this book is a must-have.

This book provides you with a number of clear step-by-step recipes which will help you to start developing mobile games with Android NDK and boost your productivity debugging them on your computer. This book will also provide you with new ways of working as well as some useful tips and tricks that will demonstrably increase your development speed and efficiency.

This book will take you through a number of easy-to-follow recipes that will help you to take advantage of the Android NDK as well as some popular C++ libraries. It presents Android application development in C++ and shows you how to create a complete gaming application.

You will learn how to write portable multithreaded C++ code, use HTTP networking, play audio files, use OpenGL ES, to render high-quality text, and how to recognize user gestures on multi-touch devices. If you want to leverage your C++ skills in mobile development and add performance to your Android applications, then this is the book for you.

What you will learn from this book
  • Port popular C++ libraries to Android
  • Write portable multithreaded code
  • Play audio with OpenAL
  • Implement gesture recognition
  • Render text with FreeType
  • Use OpenGL ES to port and abstract APIs from the game code to develop games on a desktop PC
  • Debug mobile applications on your desktop
  • Access Flickr and Picasa web services from C++
  • Extract resources from APK archives
  • Develop Android applications without an IDE
Approach

A systematic guide consisting of over 70 recipes which focus on helping you build portable mobile games and aims to enhance your game development skills with clear instructions.

Who this book is written for

If you are a C++ developer who wants to jump into the world of Android game development and who wants to use the power of existing C++ libraries in your existing Android Java applications, then this book is for you. You need to have basic knowledge of C or C++ including pointer manipulation, multithreading, and object-oriented programming concepts as well as some experience developing applications without using an IDE.

Multi-Device Hybrid Apps (Preview) for Visual Studio released

Multi-Device Hybrid Apps giving you the ability to build hybrid apps in HTML, CSS, and JavaScript that work beautifully on Android, iOS, Windows Phone, and Windows Store. All of this is done inside Visual Studio itself.

read more: Multi-Device Hybrid Apps (Preview)

Cannot detect MotionEvent.ACTION_MOVE and ACTION_UP

Refer to former exercises, "Detect single touch on custom View to draw icon on canvas" and "Detect multi touch on custom View to draw icons on canvas"; true is return from onTouchEvent() method of the custom view, indicate that the event was handled.

If false is returned from onTouchEvent() method, indicate that your code will not handle the events, and the system will not pass you the subsequent events such as MotionEvent.ACTION_MOVE and MotionEvent.ACTION_UP.

This example show two custome View, MyView on left side and MyView2 on right side. MyView handle user touch and display icon in onTouchEvent() method and return true. MyView2 do the same job by extending MyView, but return false in onTouchEvent() method. It can be noticed that MyView2 on right side can detect MotionEvent.ACTION_DOWN only, not MotionEvent.ACTION_MOVE and MotionEvent.ACTION_UP.


Modify from last the exercise "Detect multi touch on custom View to draw icons on canvas", create MyView2.java extends MyView, override onTouchEvent() to return false.

package com.example.androiddrawinview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class MyView2 extends MyView {

public MyView2(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

public MyView2(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}

public MyView2(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}

@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
return false;
}

}

Modify /res/layout/fragment_main.xml to replace the MyView on right hand side to MyView2.
<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.androiddrawinview.MainActivity$PlaceholderFragment" >

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

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

<com.example.androiddrawinview.MyView
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_margin="10dp" />
<com.example.androiddrawinview.MyView2
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_margin="10dp" />
</LinearLayout>

</LinearLayout>


download filesDownload the files.

Android SoundPool example

This example show how to use SoundPool to load ogg audio file, in /res/raw/piano117.ogg, implement android.media.SoundPool.OnLoadCompleteListener and play specified sound within SoundPool.


The sample ogg file, piano117.ogg, I download from https://archive.org/details/SynthesizedPianoNotes. Download to your /res/raw folder in your project. Remember to rename it as all in low-case character.

MainActivity.java
package com.example.androidsoundpool;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

Button btnPlay;
SoundPool soundPool;
AudioManager audioManager;
int soundId;

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

btnPlay = (Button)findViewById(R.id.play);
btnPlay.setEnabled(false);
btnPlay.setOnClickListener(btnPlayOnClickListener);

audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);

//the maximum number of simultaneous streams for this SoundPool object
int maxStreams = 4;
//the audio stream type as described in AudioManager
int streamType = AudioManager.STREAM_MUSIC;
//the sample-rate converter quality. Currently has no effect. Use 0 for the default.
int srcQuality = 0;

soundPool = new SoundPool(maxStreams, streamType, srcQuality);
soundPool.setOnLoadCompleteListener(soundPoolOnLoadCompleteListener);
soundId = soundPool.load(this, R.raw.piano117, 1);

}

OnLoadCompleteListener soundPoolOnLoadCompleteListener =
new OnLoadCompleteListener(){

@Override
public void onLoadComplete(SoundPool soundPool,
int sampleId, int status) {
if(status==0){
btnPlay.setEnabled(true);
}else{
Toast.makeText(MainActivity.this,
"SoundPool.load() fail",
Toast.LENGTH_LONG).show();
}

}
};

OnClickListener btnPlayOnClickListener =
new OnClickListener(){

@Override
public void onClick(View v) {
float vol = audioManager.getStreamVolume(
AudioManager.STREAM_MUSIC);
float maxVol = audioManager.getStreamMaxVolume(
AudioManager.STREAM_MUSIC);
float leftVolume = vol/maxVol;
float rightVolume = vol/maxVol;
int priority = 1;
int no_loop = 0;
float normal_playback_rate = 1f;
soundPool.play(soundId,
leftVolume,
rightVolume,
priority,
no_loop,
normal_playback_rate);
}
};

}

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

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

<Button
android:id="@+id/play"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=" - PLAY - " />

</LinearLayout>


"the import android.support.v7.app cannot be resolved" after updated

If you have the error of "the import android.support.v7.app cannot be resolved" after Android SDK and ADT updated in Eclipse. Try to Clean all projects, include appcompat_... libs.

Project (on Eclipse menu) -> Clean... -> select Clean all projects... then OK.


Robotium Automated Testing for Android

Robotium Automated Testing for Android

Efficiently automate test cases for Android applications using Robotium

Overview

  • Integrate Robotium with Maven to perform test case execution during build
  • Learn different steps to connect to a remote client from an android using Robotium
  • Understand the benefits of Robotium over other test frameworks


In Detail

Automation testing on mobile devices has been around for a number of years, although it has really taken off with the advent of the Robotium Framework. With the help of automating test cases, business components are extensively reused and complex test cases are executed. Due to a number of different key features added to the Robotium Framework, it has become the world's leading Android test automation framework and most of the industry experts and professionals are using this framework for testing their Android business applications.

This practical guide will help you to create and execute automated test cases. You will also learn how to take advantage of the real power behind the Robotium Framework and all of its features, while being provided with a good grounding in how to use it in your Android test project.

Starting with learning how to set up an Android environment for using Robotium, this book will then look at the various features of the Robotium framework, and take you through numerous examples that will help you to take advantage of the new features in Robotium, quickly and painlessly.

This book will guide you through setting up the Android environment that is necessary to create a test project. You will also learn the benefits of using Robotium over other test frameworks, as well as solutions to the most common issues faced by users in this domain.

What you will learn from this book

  • Get to grips with the Robotium Framework
  • Create a test project using Robotium
  • Get acquainted with Robotium API calls and their usage
  • Access web views in Android via Web Support in Robotium
  • Compare Robotium with other testing frameworks
  • Utilize the remote control feature in Robotium
  • Implement different Robotium utilities
  • Use Robotium with Maven


Approach

This is a step-by-step, example-oriented tutorial aimed at illustrating the various test scenarios and automation capabilities of Robotium.

Who this book is written for

If you are an Android developer who is learning how to create test cases to test their application, and are looking to get a good grounding in different features in Robotium, this book is ideal for you. It's assumed that you have some experience in Android development, as well be familiar with the Android test framework, as Robotium is a wrapper to Android test framework.

Detect multi touch on custom View to draw icons on canvas

Last exercise show how to "Detect single touch on custom View to draw icon on canvas". It is now modified to detect multi touch, to display multi icons.


MyView.java
package com.example.androiddrawinview;

import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class MyView extends View {

private ArrayList<xy> drawList;
private float offsetX, offsetY;
private boolean touching = false;
private Bitmap bm;

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

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

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

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(
MeasureSpec.getSize(widthMeasureSpec),
MeasureSpec.getSize(heightMeasureSpec));
}

private void init(){
bm = BitmapFactory.decodeResource(
getResources(),
R.drawable.ic_launcher);
offsetX = bm.getWidth()/2;
offsetY = bm.getHeight()/2;
}

@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.GRAY);
if(touching){
for(xy pt : drawList){
canvas.drawBitmap(bm,
pt.getX()-offsetX,
pt.getY()-offsetY,
null);
}
}
}

@Override
public boolean onTouchEvent(MotionEvent event) {

int action = event.getAction() & MotionEvent.ACTION_MASK;
switch(action){
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_DOWN:

ArrayList<xy> touchList = new ArrayList<xy>();
int pointerCount = event.getPointerCount();

for(int i=0; i < pointerCount; i++){
touchList.add(
new xy(
event.getX(i),
event.getY(i)));
}
drawList = touchList;
touching = true;
break;
default:
touching = false;
}

invalidate();
return true;
}

class xy{
float x;
float y;

public xy(float x, float y){
this.x = x;
this.y = y;
}

public float getX(){
return x;
}

public float getY(){
return y;
}
}

}

/res/layout/fragment_main.xml, MainActivity.java and /res/layout/activity_main.xml, refer to last exercise.

download filesDownload the files.

Related:
Cannot detect MotionEvent.ACTION_MOVE and ACTION_UP

ic_launcher cannot be resolved or is not a field

Sometimes you will face with error of "ic_launcher cannot be resolved or is not a field", one of the possible reason is import android.R incorrectly.

Note: Eclipse sometimes likes to add an import android.R statement at the top of your files that use resources, especially when you ask eclipse to sort or otherwise manage imports. This will cause your make to break. Look out for these erroneous import statements and delete them.
http://source.android.com/source/using-eclipse.html

Detect single touch on custom View to draw icon on canvas

This example implement custom View, override onTouchEvent() and onDraw() to draw bitmap on canvas when user touch. In this implementation, only one touch point is detected.


Our custom View, MyView.java
package com.example.androiddrawinview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class MyView extends View {

private float x, y;
private float offsetX, offsetY;
private boolean touching = false;
private Bitmap bm;

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

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

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

private void init(){
bm = BitmapFactory.decodeResource(
getResources(),
R.drawable.ic_launcher);
offsetX = bm.getWidth()/2;
offsetY = bm.getHeight()/2;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(
MeasureSpec.getSize(widthMeasureSpec),
MeasureSpec.getSize(heightMeasureSpec));
}


@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.GRAY);
if(touching){
canvas.drawBitmap(bm, x-offsetX, y-offsetY, null);
}
}

@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();

switch(action){
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_DOWN:
x = event.getX();
y = event.getY();
touching = true;
break;
default:
touching = false;
}
invalidate();

return true;
}

}

Modify /res/layout/fragment_main.xml to add <com.example.androiddrawinview.MyView>.
<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.androiddrawinview.MainActivity$PlaceholderFragment" >

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

<com.example.androiddrawinview.MyView
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

</LinearLayout>

Keep using the auto generated MainActivity.java and /res/layout/activity_main.xml.

MainActivity.java
package com.example.androiddrawinview;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;

public class MainActivity extends ActionBarActivity {

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

if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {

public PlaceholderFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}

}

/res/layout/activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.androiddrawinview.MainActivity"
tools:ignore="MergeRootFrame" />


download filesDownload the files.

Multi single touch View

Modify /res/layout/fragment_main.xml to have two <com.example.androiddrawinview.MyView>.
<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.androiddrawinview.MainActivity$PlaceholderFragment" >

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

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

<com.example.androiddrawinview.MyView
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_margin="10dp" />
<com.example.androiddrawinview.MyView
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_margin="10dp" />
</LinearLayout>

</LinearLayout>

Now we have two single touch view together.


Next:
Detect multi touch on custom View to draw icons on canvas
Cannot detect MotionEvent.ACTION_MOVE and ACTION_UP

How to generate APK in Eclipse of Android-adt

To generate APK using Eclipse of Android-adt:

Right click your project -> Android Tools -> Export Signed Application Package...

follow the video:


Please keep (strongly recommand to make a copy) the keystore file. If you publish your apps in Google Play, and you have to update it, you need to update APK using original keystore.

Google Play services 4.4

gps

A new release of Google Play services has now been rolled out to the world, and as usual we have a number of features that can make your apps better than before. This release includes a major enhancement to Maps with the introduction of Street View, as well as new features in Location, Games Services, Mobile Ads, and Wallet API.



Here are the highlights of Google Play services release 4.4:



Google Maps Android API

Starting with a much anticipated announcement for the Google Maps Android API: Introducing Street View. You can now embed Street View imagery into an activity enabling your users to explore the world through panoramic 360-degree views. Programmatically control the zoom and orientation (tilt and bearing) of the Street View camera, and animate the camera movements over a given duration. Here is an example of what you can do with the API, where the user navigates forward one step:

We've also added more features to the Indoor Maps feature of the API. You can turn the default floor picker off - useful if you want to build your own. You can also detect when a new building comes into focus, and find the currently-active building and floor. Great if you want to show custom markup for the active level, for example.



Activity Recognition

And while we are on the topic of maps, let’s turn to some news in the Location API. For those of you that have used this API, you may have seen the ability already there to detect if the device is in a vehicle, on a bicycle, on foot, still, or tilting.



In this release, two new activity detectors have been added: Running, and Walking. So a great opportunity to expand your app to be even more responsive to your users. And for you that have not worked with this capability earlier, we hardly need to tell the cool things you can do with it. Just imagine combining this capability with features in Maps, Games Services, and other parts of Location...



Games Services Update

In the 4.3 release we introduced Game Gifts, which allows you to request gifts or wishes. And although there are no external API changes this time, the default requests sending UI has been extended to now allow the user to select multiple Game Gifts recipients. For your games this means more collaboration and social engagement between your players.



Mobile Ads

For Mobile Ads, we’ve added new APIs for publishers to display in-app promo ads, which enables users to purchase advertised items directly. We’re offering app developers control of targeting specific user segments with ads, for example offering high-value users an ad for product A, or new users with an ad for product B, etc.



With these extensions, users can conveniently purchase in-app items that interest them, advertisers can reach consumers, and your app connects the dots; a win-win-win in other words.



Wallet Fragments

For the Instant Buy API, we’ve now reduced the work involved to place a Buy With Google button in an app. The WalletFragment API introduced in this release makes it extremely easy to integrate Google Wallet Instant Buy with an existing app. Just configure these fragments and add them to your app.

And that’s another release of Google Play services. The updated Google Play services SDK is now available through the Android SDK manager. Coming up in June is Google I/O, no need to say more…



For the release video, please see:

DevBytes: Google Play services 4.4



For details on the APIs, please see:

New Features in Google Play services 4.4





AMD bridges x86 and ARM chips with 'Project SkyBridge'

AMD has unveiled a bold new plan to bridge the worlds of x86 and ARM through a development effort called Project Skybridge.

Using Intent.ACTION_OPEN_DOCUMENT, for KitKat API 19 or higher

Android 4.4 KitKat, API 19, introduce new Intent.ACTION_OPEN_DOCUMENT, allow the user to select and return one or more existing documents. When invoked, the system will display the various DocumentsProvider instances installed on the device, letting the user interactively navigate through them. These documents include local media, such as photos and video, and documents provided by installed cloud storage providers.

Each document is represented as a content://

This example show how to select image file by calling startActivityForResult() with Intent of ACTION_OPEN_DOCUMENT, then load it in ImageView from the returned Uri.
  • To load image Intent.ACTION_OPEN_DOCUMENT, setType("image/*")
  • This example haven't handle resize of the image, so may be fail if load ImageView with large image.
  • If the app run on pre-KitKat devices, it will use old Intent.ACTION_GET_CONTENT.


package com.example.androidkitkatdocument;

import java.io.FileNotFoundException;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

public class MainActivity extends Activity {

private static final int RQS_OPEN_IMAGE = 1;

Button buttonOpen;
TextView textUri;
ImageView imageView;

Uri targetUri = null;

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

buttonOpen = (Button) findViewById(R.id.opendocument);
buttonOpen.setOnClickListener(buttonOpenOnClickListener);

textUri = (TextView) findViewById(R.id.texturi);
textUri.setOnClickListener(textUriOnClickListener);

imageView = (ImageView)findViewById(R.id.image);
}

OnClickListener buttonOpenOnClickListener =
new OnClickListener() {

@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public void onClick(View v) {
Intent intent = new Intent();

if (Build.VERSION.SDK_INT >=
Build.VERSION_CODES.KITKAT) {
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
} else {
intent.setAction(Intent.ACTION_GET_CONTENT);
}

intent.addCategory(Intent.CATEGORY_OPENABLE);

// set MIME type for image
intent.setType("image/*");

startActivityForResult(intent, RQS_OPEN_IMAGE);
}

};

OnClickListener textUriOnClickListener =
new OnClickListener(){

@Override
public void onClick(View v) {
if (targetUri != null){
Bitmap bm;
try {
bm = BitmapFactory.decodeStream(
getContentResolver()
.openInputStream(targetUri));
imageView.setImageBitmap(bm);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

};

@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {

if (resultCode == Activity.RESULT_OK) {

Uri dataUri = data.getData();

if (requestCode == RQS_OPEN_IMAGE) {
targetUri = dataUri;
textUri.setText(dataUri.toString());
}
}

}

}

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

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

<Button
android:id="@+id/opendocument"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open Document of Image" />

<TextView
android:id="@+id/texturi"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<ImageView
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

</LinearLayout>

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

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

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

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

</manifest>


download filesDownload the files.