Nov 8, 2013

Some Android Advance Concept Links

1) Android Content Providers :

http://tutorials-android.blogspot.in/2012/04/create-custom-or-own-content-provider.html

Details Explanation about Content providers :



2). Drawing with XML. 

Drawing with XML means create Some Custom Button with user defined colors and user defined Back grounds using XML 



3) CANVAS Drawing Example ( this is Some sample project )




4)  Working with Google maps Extensions. ( this is Sample Basic Application )



5) Managing HTTP Calls. 


6)

A)  Make phone call 



b) Send SMS 



C) Check Network Connection 


How To Send SMS Message In Android

In Android, you can use SmsManager API or device’s Built-in SMS application to send a SMS message. In this tutorial, we show you two basic examples to send SMS message :
  1. SmsManager API
    	SmsManager smsManager = SmsManager.getDefault();
    	smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
  2. Built-in SMS application
    	Intent sendIntent = new Intent(Intent.ACTION_VIEW);
    	sendIntent.putExtra("sms_body", "default content"); 
    	sendIntent.setType("vnd.android-dir/mms-sms");
    	startActivity(sendIntent);
Of course, both need SEND_SMS permission.
<uses-permission android:name="android.permission.SEND_SMS" />
P.S This project is developed in Eclipse 3.7, and tested with Samsung Galaxy S2 (Android 2.3.3).
Note
The Built-in SMS application solution is the easiest way, because you let device handle everything for you.

1. SmsManager Example

Android layout file to textboxes (phone no, sms message) and button to send the SMS message.
File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <TextView
        android:id="@+id/textViewPhoneNo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Phone Number : "
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
    <EditText
        android:id="@+id/editTextPhoneNo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:phoneNumber="true" >
    </EditText>
 
    <TextView
        android:id="@+id/textViewSMS"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter SMS Message : "
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
    <EditText
        android:id="@+id/editTextSMS"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:lines="5"
        android:gravity="top" />
 
    <Button
        android:id="@+id/buttonSend"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send" />
 
</LinearLayout>
File : SendSMSActivity.java – Activity to send SMS via SmsManager.
package com.mkyong.android;
 
import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
public class SendSMSActivity extends Activity {
 
	Button buttonSend;
	EditText textPhoneNo;
	EditText textSMS;
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
 
		buttonSend = (Button) findViewById(R.id.buttonSend);
		textPhoneNo = (EditText) findViewById(R.id.editTextPhoneNo);
		textSMS = (EditText) findViewById(R.id.editTextSMS);
 
// main Logic to Send SMS 
buttonSend.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String phoneNo = textPhoneNo.getText().toString(); String sms = textSMS.getText().toString(); try { SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(phoneNo, null, sms, null, null); Toast.makeText(getApplicationContext(), "SMS Sent!",Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText(getApplicationContext(),"SMS faild, please try again later!",Toast.LENGTH_LONG).show(); } } }); }
}
File : AndroidManifest.xml , need SEND_SMS permission.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mkyong.android"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk android:minSdkVersion="10" />
 
    <uses-permission android:name="android.permission.SEND_SMS" />
 
    <application
        android:debuggable="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".SendSMSActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>
See demo :

To call Built in Application in Your Activity


try {
Intent sendIntent = new Intent(Intent.ACTION_VIEW); sendIntent.putExtra("sms_body", "default content"); sendIntent.setType("vnd.android-dir/mms-sms"); startActivity(sendIntent);
} catch (Exception e) { Toast.makeText(getApplicationContext(),"SMS faild, please try again later!",
Toast.LENGTH_LONG).show(); e.printStackTrace(); }

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.

Aug 29, 2013

How to Intercept HOME Key in Android?


The solution is:

The prevailing wisdom says it cannot be done

public static final int KEYCODE_HOME 
Key code constant: Home key. This key is handled by the framework and is never delivered to applications.
Maybe the below code would work the way we want it to. But I don't think you can trap the Home key absolutely.


Below method works for me. Hope this will work for you also....

Override below method in your activity. 

@Override
   public void onAttachedToWindow() {
   super.onAttachedToWindow();
   this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);           
  }


After overriding above method, now you can easily listen HOME Key press in your activity using onKeyDown() method.

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {     
     if(keyCode == KeyEvent.KEYCODE_HOME)
        {
           //The Code Want to Perform. 
        }
    });
 
 

Detect home button press in android and Notify when Our app is Closed

In this Code I am explaining how to Notify when app is closed using Home button or Exit Button 

From ICS to android not Supporting major Events when app is closed , so we can not now beofre application close , but using activity manager we can get Running app Package name and Its contained Activity class 

use below code in your onPause so When ever your application close it returns true 

// Method  to Check Our app is running or Not
public static boolean isAppSentToBackground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
Log.w(" YES TRUE ", "isAppSentToBackground ");
return true;
}
   }
Log.w(" YES FALSE ", "isAppSentToBackground ");
return false;
}


// Checking while App is closed in Onpause or onStart or OnDestroy 

mCtx=getApplicationContext();

@Override
protected void onPause() {
super.onPause();
if (isAppSentToBackground(mCtx)) {
// Do what ever you want after app close 
// simply Close session 
 }
}

Session idle timeout in Google Android

Control_Activity.java

package com.eae.time_out_application;
import android.app.Application;
import android.content.Intent;
import android.os.CountDownTimer;
import android.util.Log;

public class Control_Activity extends Application{

int count=0;
MyCounter timer;

private static final String TAG=Control_Activity.class.getName();

@Override
 public void onCreate()
 {
     super.onCreate();
      timer = new MyCounter(30000,1000);
      timer.start();
  }

  public void touch()
  {
     timer.start();
  }

   public class MyCounter extends CountDownTimer{
  
   public MyCounter(long millisInFuture, long countDownInterval) {
    super(millisInFuture, countDownInterval);
    }

   @Override
    public void onFinish() {
            System.out.println("Timer Completed.");
            Log.e("finish is called", "finish is called");
            Intent intent = new Intent();
            intent.setClass(Control_Activity.this, Login_Page.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
   }

   @Override
    public void onTick(long millisUntilFinished) {
           System.out.println("Timer  : " + (millisUntilFinished/1000));
        }
   }
  
  }

Control_Application.java

package com.eae.time_out_application;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.RelativeLayout;

public class Control_Application extends Activity {

RelativeLayout mylayout;
private static final String TAG = Control_Application.class.getName();

 /**
     * Gets reference to global Application
     * @return must always be type of ControlApplication! See AndroidManifest.xml
  */
   public Control_Activity getApp()
    {
        return (Control_Activity )this.getApplication();
    }
   
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  //setContentView(R.layout.activity_control__application);
  
 }

 @Override
 protected void onDestroy() {
  // TODO Auto-generated method stub
  super.onDestroy();
  
 }

 @Override
  public void onUserInteraction()
  {
        super.onUserInteraction();
        getApp().touch();
        Log.d(TAG, "User interaction to "+this.toString());
        Log.e("My Activity Touched", "My Activity Touched");
   }

}

Login Page.java

package com.eae.time_out_application;

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

public class Login_Page  extends Activity{

@Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.login_page);
 }

}


main.xml


<RelativeLayout 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"
    tools:context=".Control_Application" 
    android:id="@+id/totallayout">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="88dp"
        android:layout_marginTop="44dp"
        android:text="Button" />

    <RatingBar
        android:id="@+id/ratingBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="55dp" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_alignParentTop="true"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>



loginpage.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

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

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName" >

        <requestFocus />
    </EditText>

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

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip"
        android:text="Login" />

</LinearLayout>


Manifest.xml

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

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

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

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

</manifest>



Simply copy and past the code and run it.

If u have any doubts please reply to me 

Thank You