Nov 8, 2013

ANDROID : SIMPLE HAND DRAWING ON CANVAS WITH ERASER.

Sometimes we may need to create scratchpad in our Android application.
We can create it on CANVAS
First, create a main layout file for your activity.
<LinearLayout
         xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/drawing_question"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="40dp"
                android:layout_marginRight="30dp"
                android:background="#FFFFFF"
                android:orientation="horizontal" >

                <com.swap.handdrawing.DrawingView
                    android:id="@+id/drawing"
                    android:layout_width="0dp"
                    android:layout_height="fill_parent"
                    android:layout_marginBottom="10dp"
                    android:layout_marginRight="5dp"
                    android:layout_weight="1" >
                </com.swap.handdrawing.DrawingView>

                <LinearLayout
                    android:id="@+id/eraserView"
                    android:layout_width="50dp"
                    android:layout_height="fill_parent"
                    android:layout_marginBottom="10dp"
                    android:background="@drawable/custom_edit_text"
                    android:padding="5dp" >

                    <ImageView
                        android:id="@+id/eraser"
                        android:layout_width="40dp"
                        android:layout_height="40dp"
                        android:layout_gravity="center"
                        android:src="@drawable/eraser" />
                </LinearLayout>
</LinearLayout>
Next, create DrawingView class extending View & implementing OnTouchListener.

 
package com.swap.handdrawing;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class DrawingView extends View implements OnTouchListener {
 private Canvas m_Canvas;

 private Path m_Path;

 private Paint m_Paint;

 ArrayList<Pair> paths = new ArrayList<Pair>();
 
 private float mX, mY;

 private static final float TOUCH_TOLERANCE = 4;

 public static boolean isEraserActive = false; 

 public DrawingView(Context context, AttributeSet attr) {
  super(context);
  setFocusable(true);
  setFocusableInTouchMode(true);

  setBackgroundColor(Color.WHITE);

  this.setOnTouchListener(this);

  onCanvasInitialization();
 }

 public void onCanvasInitialization() {
  m_Paint = new Paint();
  m_Paint.setAntiAlias(true);
  m_Paint.setDither(true);
  m_Paint.setColor(Color.parseColor("#000000")); 
  m_Paint.setStyle(Paint.Style.STROKE);
  m_Paint.setStrokeJoin(Paint.Join.ROUND);
  m_Paint.setStrokeCap(Paint.Cap.ROUND);
  m_Paint.setStrokeWidth(2);

  m_Canvas = new Canvas();
 
  m_Path = new Path();
  Paint newPaint = new Paint(m_Paint);
  paths.add(new Pair(m_Path, newPaint));
 
 }

 @Override
 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
  super.onSizeChanged(w, h, oldw, oldh);
 }

 public boolean onTouch(View arg0, MotionEvent event) {
  float x = event.getX();
  float y = event.getY();

  switch (event.getAction()) {
  case MotionEvent.ACTION_DOWN:
   touch_start(x, y);
   invalidate();
   break;
  case MotionEvent.ACTION_MOVE:
   touch_move(x, y);
   invalidate();
   break;
  case MotionEvent.ACTION_UP:
   touch_up();
   invalidate();
   break;
  }
  return true;
 }

 @Override
 protected void onDraw(Canvas canvas) {
  for (Pair p : paths) {
   canvas.drawPath(p.first, p.second);
  }
 }

 private void touch_start(float x, float y) {

  if (isEraserActive) {
   m_Paint.setColor(Color.WHITE);
   m_Paint.setStrokeWidth(6);
   Paint newPaint = new Paint(m_Paint); // Clones the mPaint object
   paths.add(new Pair(m_Path, newPaint));
  } else { 
   m_Paint.setColor(Color.BLACK);
   m_Paint.setStrokeWidth(2);
   Paint newPaint = new Paint(m_Paint); // Clones the mPaint object
   paths.add(new Pair(m_Path, newPaint));
  }
 
  m_Path.reset();
  m_Path.moveTo(x, y);
  mX = x;
  mY = y;
 }

 private void touch_move(float x, float y) {
  float dx = Math.abs(x - mX);
  float dy = Math.abs(y - mY);
  if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
   m_Path.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
   mX = x;
   mY = y;
  }
 }

 private void touch_up() {
  m_Path.lineTo(mX, mY);

  // commit the path to our offscreen
  m_Canvas.drawPath(m_Path, m_Paint);

  // kill this so we don't double draw
  m_Path = new Path();
  Paint newPaint = new Paint(m_Paint); // Clones the mPaint object
  paths.add(new Pair(m_Path, newPaint));
 }   
} 
 
Then access DrawingView in your MainActivity. Toggle between eraser & pencil by changing isEraserActive & it’s image.
package com.swap.handdrawing;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

public class MainActivity extends Activity {

 private ImageView eraser;


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

  final DrawingView drawingView = (DrawingView) findViewById(R.id.drawing);

  eraser = (ImageView) findViewById(R.id.eraser);
  eraser.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {

    if (drawingView.isEraserActive) {
     drawingView.isEraserActive = false;

     eraser.setImageResource(R.drawable.eraser);

    } else {
     drawingView.isEraserActive = true;

     eraser.setImageResource(R.drawable.pencil);
    }

   }
  });

 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

}

 
You can get resources & drawables used in above tutorial by downloading source code. You can add colors to your drawing by changing color of path.
Any suggestions are always welcome.

Download Source Code

Oct 16, 2013

How to load Android app from Eclipse to my Android phone instead of AVD


  1. For TAB 3 Download Samsung Kies


  1. First you need to enable USB debugging on your phone, then connect it to your computer via USB. Then eclipse should automatically start debugging on your phone instead of the AVD.

    3 : After install Kies Restart Your system .
    4: Go to Run Configuration





You can see three Columns Android,Target and Common.
Step5
Select the Target
Step 6
Choose Always prompt to pick device.Click Ok
Step 7


Now run your project you should see the emulator and your device. Select your device and click ok. 


Hope it helps.


Sep 1, 2013

Android Architecture – The Key Concepts of Android OS



In the earlier post on Android Development, we’ve learned how to install and setup a complete Android development environment. Now, before we start development, you should know the Android architecture in detail.

Being an Android user you may know how the basic functions such as making a call, sending a text message, changing the system settings, install or uninstall apps etc. Well! All Android users know these, but not enough for a developer. Then what else details are a developer required to know about Android, I’ll explain. To be a developer, you should know all the key concepts of Android. That is, you should know all the nuts and bolts of Android OS.

Here we start:
Android Architecture Diagram:



The above figure shows the diagram of Android Architecture. The Android OS can be referred to as a software stack of different layers, where each layer is a group of sveral program components. Together it includes operating system, middleware and important applications. Each layer in the architecture provides different services to the layer just above it. We will examine the features of each layer in detail.
Linux Kernel

The basic layer is the Linux kernel. The whole Android OS is built on top of the Linux 2.6 Kernel with some further architectural changes made by Google. It is this Linux that interacts with the hardware and contains all the essential hardware drivers. Drivers are programs that control and communicate with the hardware. For example, consider the Bluetooth function. All devices has a Bluetooth hardware in it. Therefore the kernel must include a Bluetooth driver to communicate with the Bluetooth hardware. The Linux kernel also acts as an abstraction layer between the hardware and other software layers. Android uses the Linux for all its core functionality such as Memory management, process management, networking, security settings etc. As the Android is built on a most popular and proven foundation, it made the porting of Android to variety of hardware, a relatively painless task.
Libraries

The next layer is the Android’s native libraries. It is this layer that enables the device to handle different types of data. These libraries are written in c or c++ language and are specific for a particular hardware.

Some of the important native libraries include the following:

Surface Manager: It is used for compositing window manager with off-screen buffering. Off-screen buffering means you cant directly draw into the screen, but your drawings go to the off-screen buffer. There it is combined with other drawings and form the final screen the user will see. This off screen buffer is the reason behind the transparency of windows.

Media framework: Media framework provides different media codecs allowing the recording and playback of different media formats

SQLite: SQLite is the database engine used in android for data storage purposes

WebKit: It is the browser engine used to display HTML content

OpenGL: Used to render 2D or 3D graphics content to the screen
Android Runtime

Android Runtime consists of Dalvik Virtual machine and Core Java libraries.

Dalvik Virtual Machine

It is a type of JVM used in android devices to run apps and is optimized for low processing power and low memory environments. Unlike the JVM, the Dalvik Virtual Machine doesn’t run .class files, instead it runs .dex files. .dex files are built from .class file at the time of compilation and provides hifger efficiency in low resource environments. The Dalvik VM allows multiple instance of Virtual machine to be created simultaneously providing security, isolation, memory management and threading support. It is developed by Dan Bornstein of Google.

Core Java Libraries
These are different from Java SE and Java ME libraries. However these libraries provides most of the functionalities defined in the Java SE libraries.
Application Framework

These are the blocks that our applications directly interacts with. These programs manage the basic functions of phone like resource management, voice call management etc. As a developer, you just consider these are some basic tools with which we are building our applications.

Important blocks of Application framework are:

Activity Manager: Manages the activity life cycle of applications

Content Providers: Manage the data sharing between applications

Telephony Manager: Manages all voice calls. We use telephony manager if we want to access voice calls in our application.

Location Manager: Location management, using GPS or cell tower

Resource Manager: Manage the various types of resources we use in our Application
Applications

Applications are the top layer in the Android architecture and this is where our applications are gonna fit. Several standard applications comes pre-installed with every device, such as:
SMS client app
Dialer
Web browser
Contact manager

As a developer we are able to write an app which replace any existing system app. That is, you are not limited in accessing any particular feature. You are practically limitless and can whatever you want to do with the android (as long as the users of your app permits it). Thus Android is opening endless opportunities to the developer.