Monday 30 March 2015

Run repeatedly task using timer class in android.

Performing repeated tasks in a Service

Besides performing long-running tasks in a service, you might also perform some repeated tasks in a service. For example, you may write an alarm clock service that runs persistently in the background. In this case, your service may need to periodically execute some code to check whether a prescheduled time has been reached so that an alarm can be sounded. To execute a block of code to be executed at a regular time interval, you can use the Timer class within your service.

The following Example shows you how.

Running Repeated Tasks Using the Timer Class

1 . Using the same project created in the previous post, add the following statements in bold to the MyService.java file:

package ​com.emergingandroidtech.Services;
import ​android.app.Service;
import​ android.content.Intent;
import​ android.os.AsyncTask;
import​ android.os.IBinder;
import​ android.util.Log;
import​ android.widget.Toast;
import ​java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

public ​class ​MyService​ extends​ Service​
{
​​​​int counter = 0;
​​​​static final int UPDATE_INTERVAL = 1000;
​​​​private Timer timer = new Timer();
​​​​
@Override
​​​​public​ IBinder ​onBind(Intent ​arg0)
​{
​​​​​​​​return ​null;
​​​​}
​​​​
@Override
​​​​public ​int ​onStartCommand(Intent ​intent,​int ​flags,​int ​startId)​
{
​​​​​​​​//​We ​want​ this ​service​ to ​continue​r unning ​until ​it ​is ​explicitly
​​​​​​​​//​stopped,​so​r eturn ​sticky. ​
​​​​​​​Toast.makeText(this,​“Service​Started”,​Toast.LENGTH_LONG).show();
​​​​​​​​
doSomethingRepeatedly();
​​​​​​​​
return ​START_STICKY; ​​​​
}
​​​​
private void doSomethingRepeatedly()
{
​​​​​​​​timer.scheduleAtFixedRate( new TimerTask()
{
​​​​​​​​​​​​public void run()
{
​​​​​​​​​​​​​​​​Log.d(“MyService”, String.valueOf(++counter));
​​​​​​​​​​​​}
​​​​​​​​},
0,
UPDATE_INTERVAL);
​​​​}
​​​​
@Override
​​​​public ​void ​onDestroy()​
{ ​
​​​​​​​super.onDestroy();
​​​​​​​​if (timer != null)
{
​​​​​​​​​​​​timer.cancel(); ​
​​​​​​​}
​​​​​​​​Toast.makeText(this,​“Service​Destroyed”,​Toast.LENGTH_LONG).show(); ​​
​​}
}

2 . Click the Start Service button. 

3 . Observe the output displayed in the LogCat window: 

01-16​15:12:04.364:​DEBUG/MyService(495):​1
01-16​15:12:05.384:​DEBUG/MyService(495):​2
01-16​15:12:06.386:​DEBUG/MyService(495):​3
01-16​15:12:07.389:​DEBUG/MyService(495):​4
01-16​15:12:08.364:​DEBUG/MyService(495):​5
01-16​15:12:09.427:​DEBUG/MyService(495):​6
01-16​15:12:10.374:​DEBUG/MyService(495):​7

How It Works

In this example, you created a Timer object and called its scheduleAtFixedRate() method inside the doSomethingRepeatedly() method that you have defined:

​​​​private ​void ​doSomethingRepeatedly()​
{
​​​​​​​​timer.scheduleAtFixedRate(new​TimerTask()​
{
​​​​​​​​​​​​public ​void ​run()​
{
​​​​​​​​​​​​​​​​Log.d(“MyService”,​String.valueOf(++counter));
​​​​​​​​​​​​}
​​​​​​​​},
​0,
​UPDATE_INTERVAL);
​​​​}

You passed an instance of the TimerTask class to the scheduleAtFixedRate() method so that  you can execute the block of code within the run() method repeatedly. The second parameter to the scheduleAtFixedRate() method specifies the amount of time, in milliseconds, before first execution. The third parameter specifies the amount of time, in milliseconds, between subsequent executions. In the preceding example, you essentially print out the value of the counter every one second (1,000 milliseconds). The service repeatedly prints the value of counter until the service is terminated:

​​​​@Override ​
​​​public ​void ​onDestroy()​
{
​​​​​​​​super.onDestroy();
​​​​​​​​if​(timer​!=​null)
{
​​​​​​​​​​​​timer.cancel(); ​​​
​​​​​} ​
​​​​​​​Toast.makeText(this,​“Service​Destroyed”,​Toast.LENGTH_LONG).show(); ​​
​​}

For the scheduleAtFixedRate() method, your code is executed at fixed time intervals, regardless of how long each task takes. For example, if the code within your run() method takes two seconds to complete, then your second task will start immediately after the first task has ended. Similarly, if your delay is set to three seconds and the task takes two seconds to complete, then the second task will wait for one second before starting.

How to use Async Task in a Service in android ?

Performing Tasks in a Service Asynchronously


1 . Using the same project created in the previous post, add the following statements in bold to the MyService.java file:
 

package ​com.emergingandroidtech.Services;
import ​android.app.Service;
import​ android.content.Intent;
import​ android.os.IBinder;
import ​android.util.Log;
import​ android.widget.Toast;
import​ java.net.MalformedURLException;
import​ java.net.URL;
import android.os.AsyncTask;

public​ class ​MyService ​extends​ Service​
{
​​​​@Override
​​​​public​ IBinder ​onBind(Intent​ arg0)​
{
​​​​​​​​return ​null;
​​​​}
​​​​
@Override ​
​​​public​ int ​onStartCommand(Intent ​intent,​int​ flags,​int ​startId)​
{
​​​​​​​​
//​We​ want ​this ​service ​to ​continue ​running ​until​ it ​is ​explicitly
​​​​​​​​//​stopped,​so​ return ​sticky. ​​​​​​​​
Toast.makeText(this,​“Service​Started”,​Toast.LENGTH_LONG).show();
​​​​​​​​try
{
​​​​​​​​​​​​new DoBackgroundTask().execute(
​​​​​​​​​​​​​​​​​​​​new URL(“http://www.amazon.com/somefiles.pdf”),
​​​​​​​​​​​​​​​new URL(“http://www.google.com/somefiles.pdf”),
​​​​​​​​​​​​​​​​​​​​new URL(“http://emergingandroidtech.blogspot.in”)); ​​​​​​​​
}
catch (MalformedURLException e)
{
​​​​​​​​​​​​e.printStackTrace();
​​​​​​​​}
​​​​​​​​return ​START_STICKY; ​
​​​}
​​​​
@Override
​​​​public ​void ​onDestroy()
​{
​​​​​​​​super.onDestroy();
​​​​​​​​Toast.makeText(this,​“Service​Destroyed”,​Toast.LENGTH_LONG).show(); ​​​
​} ​​​​

​​​​private ​int ​DownloadFile(URL​ url)
​{
​try​
{
​​​​​​​​​​​​//---simulate​ taking ​some​time ​to ​download ​a​ file--- ​​​​​​​​​​​​
Thread.sleep(5000);
​​​​​​​​}
​catch​(InterruptedException ​e)​
{
​​​​​​​​​​​​e.printStackTrace(); ​
​​​​​​​}
​​​​​​​​//---return ​an ​arbitrary ​number​ representing ​
​​​​​​//​the ​size​ of ​the ​file ​downloaded--- ​
​​​​​​​return​ 100; ​
​​​}
​​​​
private class DoBackgroundTask extends AsyncTask<URL, Integer, Long>
{
​​​​​​​​protected Long doInBackground(URL... urls)
{
 ​​​​​​​​​​​​int count = urls.length;
​​​​​​​​​​​​long totalBytesDownloaded = 0;
​​​​​​​​​​​​for (int i = 0; i < count; i++)
{
​​​​​​​​​​​​​​​​totalBytesDownloaded += DownloadFile(urls[i]);

​​​​​​​​​​​​​​​​//---calculate percentage downloaded and
​​​​​​​​​​​​​​​​// report its progress--- ​
​​​​​​​​​​​​​​​publishProgress((int) (((i+1) / (float) count) * 100)); ​
​​​​​​​​​​​}
​​​​​​​​​​​​return totalBytesDownloaded; ​​
​​​​​​}
​​​​​​​​
protected void onProgressUpdate(Integer... progress)
{
​​​​​​​​​​​​Log.d(“Downloading files”, ​​​​​​​​​​​​​​​​​​​​String.valueOf(progress[0]) + “% downloaded”); ​​​​​​​​​​​​

Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​String.valueOf(progress[0]) + “% downloaded”, ​​​​​​​​​​​​​​​​Toast.LENGTH_LONG).show(); ​​​​​​​​
}
​​​​​​​​
protected void onPostExecute(Long result)
{
​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​“Downloaded “ + result + “ bytes”, ​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_LONG).show(); ​​
​​​​​​​​​​stopSelf();
​​​​​​​​} ​
​​​}
}

2. Click the Start Service button. 
The Toast class will display a message indicating what percentage of the download is completed. 
You should see four of them: 25%, 50%, 75%, and 100%.  

3 . You will also observe the following output in the LogCat window: 

01-16​02:56:29.051:​DEBUG/Downloading​files(8844):​25%​downloaded
01-16​02:56:34.071:​DEBUG/Downloading​files(8844):​50%​downloaded
01-16​02:56:39.106:​DEBUG/Downloading​files(8844):​75%​downloaded
01-16​02:56:44.173:​DEBUG/Downloading​files(8844):​100%​downloaded

How It Works

This example illustrates one way in which you can execute a task asynchronously within your service. You do so by creating an inner class that extends the AsyncTask class. The AsyncTask class enables you to perform background execution without needing to manually handle threads and handlers. The DoBackgroundTask class extends the AsyncTask class by specifying three generic types:

​​​​private ​class ​DoBackgroundTask ​extends ​AsyncTask<URL,​Integer,​Long>​{

In this case, the three types specified are URL, Integer and Long. These three types specify the data type used by the following three methods that you implement in an AsyncTask class:

doInBackground()— This method takes an array of the first generic type specified earlier. In this case, the type is URL. This method is executed in the background thread and is where you put your long-running code. To report the progress of your task, you call the publishProgress() method, which invokes the next method, onProgressUpdate(), which you implement in an AsyncTask class. The return type of this method takes the third generic type specified earlier, which is Long in this case.

onProgressUpdate()— This method is invoked in the UI thread and is called when you call the publishProgress() method. It takes an array of the second generic type specified earlier. In this case, the type is Integer. Use this method to report the progress of the background task to the user.

onPostExecute()— This method is invoked in the UI thread and is called when the doInBackground() method has finished execution. This method takes an argument of the third generic type specified earlier, which in this case is a Long.

To download multiple files in the background, you created an instance of the DoBackgroundTask class and then called its execute() method by passing in an array of URLs:

​​​​​​​​try
​{
​​​​​​​​​​​​new​DoBackgroundTask().execute(
​​​​​​​​​​​​​​​​​​​​new​URL(“http://www.amazon.com/somefiles.pdf”),​
​​​​​​​​​​​​​​new​URL(“http://www.google.com/somefiles.pdf”),
​​​​​​​​​​​​​​​​​​​​new​URL(“http://emergingandroidtech.blogspot.in”)); ​​​​​​​​
}
​catch​(MalformedURLException ​e)
​{
​​​​​​​​​​​​//​TODO​ Auto-generated ​catch ​block ​​
​​​​​​​​​​e.printStackTrace(); ​
​​​​​​​}

The preceding causes the service to download the files in the background, and reports the progress as a percentage of files downloaded. More important, the activity remains responsive while the files are downloaded in the background, on a separate thread.
Note that when the background thread has finished execution, you need to manually call the stopSelf() method to stop the service:

​​​​​​​​protected ​void ​onPostExecute(Long​ result)
​{
​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​“Downloaded​“​+​result​+​“​bytes”,​ ​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_LONG).show(); ​​​​​​​​​​​​stopSelf(); ​​​​​​​​
}

The stopSelf() method is the equivalent of calling the stopService() method to stop the service.

Friday 27 March 2015

How to create your own service in android ?

Creating your Own Services

The best way to understand how a service works is by creating one. The following example shows you the steps to create a simple service.  
For now, you will learn how to start and stop a service.
 

Creating a Simple Service


1 . Using Eclipse, create a new Android project and name it Services.

2 . Add a new class file to the project and name it MyService.java. Populate it with the following code:

package ​com.emergingandroidtech.Services;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {
​​​​
@Override
​​​​public IBinder onBind(Intent arg0)
{
​​​​​​​​return null;
​​​​}
​​​​
@Override ​
​​​public int onStartCommand(Intent intent, int flags, int startId)
{ ​
​​​​​​​// We want this service to continue running until it is explicitly
​​​​​​​​// stopped, so return sticky.
​​​​​​​​Toast.makeText(this, “Service Started”, Toast.LENGTH_LONG).show();
​​​​​​​​return START_STICKY; ​​​​
} ​​​​

​​​​@Override ​
​​​public void onDestroy()
{
​​​​​​​​super.onDestroy();
​Toast.makeText(this, “Service Destroyed”, Toast.LENGTH_LONG).show(); ​
​​​}
}

3 . In the AndroidManifest.xml file, add the following statement in bold: 

<?xml ​version=”1.0”​encoding=”utf-8”?>
<manifest​
xmlns:android=”http://schemas.android.com/apk/res/android”
​​​​​​package=”com.emergingandroidtech.Services”
​​​​​​android:versionCode=”1”
​​​​​​android:versionName=”1.0”> ​

​​​<application​
android:icon=”@drawable/icon”
​android:label=”@string/app_name”>

​​​​​​​​<activity
 ​android:name=”.MainActivity”
​​​​​​​​​​​​​​​​​​android:label=”@string/app_name”> ​​

​​​​​​​​​​<intent-filter> ​
​​​​​​​​​​​​​​​<action ​android:name=”android.intent.action.MAIN”​/>
​​​​​​​​​​​​​​​​<category​ android:name=”android.intent.category.LAUNCHER”​/> ​​​
​​​​​​​​​</intent-filter>

​​​​​​​​</activity>

​​​​​​​​      <service android:name=”.MyService” />
​​​​</application>
​​​​<uses-sdk​
android:minSdkVersion=”9”​/>

</manifest>

4 . In the main.xml file, add the following statements in bold:

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

<Button
android:id=”@+id/btnStartService”
​​​​android:layout_width=”fill_parent”
​​​​android:layout_height=”wrap_content” ​​
​​android:text=”Start Service” />

<Button
android:id=”@+id/btnStopService”
​​​​android:layout_width=”fill_parent”
​​​​android:layout_height=”wrap_content” ​
​​​android:text=”Stop Service” />

</LinearLayout>

5 . Add the following statements in bold to the MainActivity.java file:

package​ com.emergingandroidtech.Services;
import​ android.app.Activity;
import​ android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.Button;

public ​class​ MainActivity​ extends​ Activity
​{

​​​​/**​ Called​ when​ the ​activity ​is ​first ​created.​*/

​​​​@Override
​public ​void​ onCreate(Bundle​ savedInstanceState)
​{
​​​​​​​​super.onCreate(savedInstanceState);
​​​​​​​​setContentView(R.layout.main);
​​​​​​​​
Button btnStart = (Button) findViewById(R.id.btnStartService); ​
​​​​​​​btnStart.setOnClickListener(new View.OnClickListener()
{
​​​​​​​​​​​​public void onClick(View v)
{
​​​​​​​​​​​​​​​​startService(new Intent(getBaseContext(), MyService.class)); ​
​​​​​​​​​​​}
​​​​​​​​});
​​​​​​​​
Button btnStop = (Button) findViewById(R.id.btnStopService); ​
​​​​​​​btnStop.setOnClickListener(new View.OnClickListener()
{ ​​​​​​
​​​​​​public void onClick(View v)
{
​​​​​​​​​​​​​​​​stopService(new Intent(getBaseContext(), MyService.class));
​​​​​​​​​​​​}
​​​​​​​​});

​​​​}
}

6 . Clicking the Start Service button will start the service. To stop the service, click the Stop Service button.

Monday 23 March 2015

GridView in Android.

GridView 

The GridView shows items in a two-dimensional scrolling grid. You can use the GridView together with an ImageView to display a series of images.
The following example demonstrates how.

1 . Using Eclipse, create a new Android project and name it Grid. 

2 . Drag and drop a series of images into the res/drawable-mdpi folder. When a dialog is displayed, check the copy option and click OK.

3 . Populate the main.xml file with the following content: 

<?xml​ version=”1.0”​encoding=”utf-8”?>
<GridView
xmlns:android=”http://schemas.android.com/apk/res/android” ​​​​
android:id=”@+id/gridview”
​​​​android:layout_width=”fill_parent”
​​​​android:layout_height=”fill_parent” ​​​​
android:numColumns=”auto_fit”
​​​​android:verticalSpacing=”10dp” ​​​​
android:horizontalSpacing=”10dp”
​​​​android:columnWidth=”90dp”
​​​​android:stretchMode=”columnWidth”
​​​​android:gravity=”center” />

4 . Add the following statements in bold to the MainActivity.java file: 

package com.emergingandroidtech.Grid;

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

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
    //---the images to display---
    Integer[] imageIDs = {
            R.drawable.pic1,
            R.drawable.pic2,
            R.drawable.pic3,
            R.drawable.pic4,
            R.drawable.pic5,
            R.drawable.pic6,
            R.drawable.pic7                   
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        GridView gridView = (GridView) findViewById(R.id.gridview);
        gridView.setAdapter(new ImageAdapter(this));

        gridView.setOnItemClickListener(new OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent,
            View v, int position, long id)
            {               
                Toast.makeText(getBaseContext(),
                        "pic" + (position + 1) + " selected",
                        Toast.LENGTH_SHORT).show();
            }
        });       
    }
   
    public class ImageAdapter extends BaseAdapter
    {
        private Context context;

        public ImageAdapter(Context c)
        {
            context = c;
        }

        //---returns the number of images---
        public int getCount() {
            return imageIDs.length;
        }

        //---returns the ID of an item---
        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        //---returns an ImageView view---
        public View getView(int position, View convertView, ViewGroup parent)
        {
            ImageView imageView;
            if (convertView == null) {
                imageView = new ImageView(context);
                imageView.setLayoutParams(new GridView.LayoutParams(185, 185));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(5, 5, 5, 5);
            } else {
                imageView = (ImageView) convertView;
            }
            imageView.setImageResource(imageIDs[position]);
            return imageView;
        }
    }   
}

5 . It shows the GridView displaying all the images.

How It Works 

Like the Gallery and ImageSwitcher example, you implement the ImageAdapter class and then bind it to the GridView:

​​​​​​​​GridView ​gridView​ = ​(GridView)​findViewById(R.id.gridview); ​​​​​​​​
gridView.setAdapter(new​ImageAdapter(this));
​​​​​​​​gridView.setOnItemClickListener(new​OnItemClickListener()
​{
​​​​​​​​​​​​public​ void ​onItemClick(AdapterView<?>​ parent, ​​​​​​​​​​​​View ​v,​int​ position,​long ​id) ​​​​​​​​​​​​
{ ​​​​​​​​​​​​​​​​
Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​​​​​“pic”​+​(position​+​1)​+​“​selected”, ​​​​​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_SHORT).show(); ​​​​​​​​​​​​} ​​​​​​​​
});

When an image is selected, you display a Toast message indicating the image selected. Within the GridView, you can specify the size of the images and how images are spaced out in the GridView by setting the padding for each image:

​​​​​​​​//---returns​ an ​ImageView ​view--- ​​​​​​​​
public ​View ​getView(int​ position,​View​ convertView, ​​​​​​​​ViewGroup​ parent)
​​​​​​​​{ ​​​​​​​​​​​​
ImageView ​imageView;
​​​​​​​​​​​​if​(convertView​==​null)​
{
​​​​​​​​​​​​​​​​imageView​=​new​ImageView(context); ​​​​​​​​​​​​​​​​
imageView.setLayoutParams(new ​​​​​​​​​​​​​​​​​​​​GridView.LayoutParams(85, 85));
​​​​​​​​​​​​​​​​imageView.setScaleType( ​​​​​​​​​​​​​​​​​​​​ImageView.ScaleType.CENTER_CROP);
​​​​​​​​​​​​​​​​imageView.setPadding(5, 5, 5, 5); ​​​​​​​​​​​​
}
​else
​{
 ​​​​​​​​​​​​​​​​imageView​=​(ImageView)​convertView; ​​​​​​​​​​​​
}
​​​​​​​​​​​​imageView.setImageResource(imageIDs[position]); ​​​​​​​​​​​​
return ​imageView;
​​​​​​​​}

Friday 20 March 2015

Android Download Image from URL.

Downloading Binary data 

 

One of the common tasks you need to perform is downloading binary data from the Web. For example, you may want to download an image from a server so that you can display it in your application.
The following Example shows how this is done.
 
1 .Add the following statements in bold to the main.xml file: 

<?xml ​version=”1.0”​encoding=”utf-8”?>

<LinearLayout​
xmlns:android=”http://schemas.android.com/apk/res/android”
​​​​android:orientation=”vertical”
​​​​android:layout_width=”fill_parent” ​​
​​android:layout_height=”fill_parent” ​​​​>

<ImageView ​​​​android:id=”@+id/img” ​
​​​android:layout_width=”wrap_content”
​​​​android:layout_height=”wrap_content” ​
​​​android:layout_gravity=”center” />

</LinearLayout>

2 . Add the following statements in bold to the MainActivity.java file: 

public ​class ​MainActivity​ extends​ Activity​
{
​​​​ImageView img;
​​​​
private​ InputStream ​OpenHttpConnection(String ​urlString) ​​​​throws​IOException
​​​​{
​​​​​​​​//...
​​​​}
​​​​
private Bitmap DownloadImage(String URL) ​​​​
{
​​​​​​​​Bitmap bitmap = null;
​​​​​​​​InputStream in = null; ​
​​​​​​​try
{
​​​​​​​​​​​​in = OpenHttpConnection(URL);
​​​​​​​​​​​​bitmap = BitmapFactory.decodeStream(in);
​​​​​​​​​​​​in.close(); ​​​​​​​​
}
catch (IOException e1)
{
​​​​​​​​​​​​Toast.makeText(this, e1.getLocalizedMessage(), ​​​​​​​​​​​​​​​​Toast.LENGTH_LONG).show();
​​​​​​​​​​​​e1.printStackTrace(); ​​​​​​​​
}
​​​​​​​​return bitmap;
​​​​}
​​​​
/**​Called​ when ​the ​activity ​is ​first ​created.​*/
​​​​@Override
​​​​public ​void ​onCreate(Bundle ​savedInstanceState)​
{
​​​​​​​​super.onCreate(savedInstanceState); ​​
​​​​​​setContentView(R.layout.main);
​​​​​​​​
//---download an image---
​​​​​​​​Bitmap bitmap = ​​​​​​​​​​​​DownloadImage( ​​​​​​​​​​​​“http://www.streetcar.org/mim/cable/images/cable-01.jpg”); ​
​​​​​​​img = (ImageView) findViewById(R.id.img);
​​​​​​​​img.setImageBitmap(bitmap);
​​​​}
}

How It Works 

The DownloadImage() method takes the URL of the image to download and then opens the connection to the server using the OpenHttpConnection() method that you have defined earlier. Using the InputStream object returned by the connection, the decodeStream() method from the BitmapFactory class is used to download and decode the data into a Bitmap object. The DownloadImage() method returns a Bitmap object.

* The image is then displayed using an ImageView view.

Wednesday 18 March 2015

How to implement spinner in Android ?

The SpinnerView displays one item at a time from a list and enables users to choose among them.
The following Example shows how you can use the SpinnerView in your activity.

Using the SpinnerView to Display an item at a Time 

1 . Using Eclipse, create an Android project and name it as SpinnerView.

2 . Modify the main.xml file located in the res/layout folder as shown here: 

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

<Spinner ​​​​android:id=”@+id/spinner1” ​
​​​android:layout_width=”wrap_content”
​​​​android:layout_height=”wrap_content” ​​​
​android:drawSelectorOnTop=”true” />

</LinearLayout>

3 . Add the following lines in bold to the strings.xml file located in the res/values folder: 

<?xml ​version=”1.0”​encoding=”utf-8”?>
<resources>
​​​​
<string​name=”hello”>Hello​World,​MainActivity!</string> ​
​​​<string​name=”app_name”>SpinnerView</string>
​​​​
<string-array name=”presidents_array”> ​​
​​​​​​
<item>Dwight D. Eisenhower</item> ​
​​​​​​​<item>John F. Kennedy</item> ​
​​​​​​​<item>Lyndon B. Johnson</item>
​​​​​​​​<item>Richard Nixon</item> ​
​​​​​​​<item>Gerald Ford</item> ​​
​​​​​​<item>Jimmy Carter</item>
​​​​​​​​<item>Ronald Reagan</item> ​​
​​​​​​<item>George H. W. Bush</item> ​​
​​​​​​<item>Bill Clinton</item>
​​​​​​​​<item>George W. Bush</item> ​​
​​​​​​<item>Barack Obama</item> ​​​

​</string-array>

</resources>

4 . Add the following statements in bold to the MainActivity.java file:

package com.emergingandroidtech.SpinnerView;

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

import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {
   
    String[] presidents;   
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        presidents =
            getResources().getStringArray(R.array.presidents_array);
        Spinner s1 = (Spinner) findViewById(R.id.spinner1);
       
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_dropdown_item, presidents);

        s1.setAdapter(adapter);
        s1.setOnItemSelectedListener(new OnItemSelectedListener()
        {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
            {
                int index = arg0.getSelectedItemPosition();
                Toast.makeText(getBaseContext(),
                    "You have selected item : " + presidents[index],
                    Toast.LENGTH_SHORT).show();               
            }

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

5 .Click on the SpinnerView and you will see a pop-up displaying the list of presidents’ names. Clicking on an item will display a message showing you the item selected.

Monday 16 March 2015

ImageSwitcher in Android

ImageSwitcher


The previous post http://emergingandroidtech.blogspot.in/2015/03/gallery-in-android.html
demonstrated how to use the Gallery view together with an ImageView to display a series of thumbnail images so that when one is selected, the selected image is displayed in the ImageView.
However, sometimes you don’t want an image to appear abruptly when the user selects it in the Gallery view — you might, for example, want to apply some animation to the image when it transits from one image to another. In this case, you need to use the ImageSwitcher together with the Gallery view.

The following Try It Out shows you how.

Using the imageSwitcher View



1 . Using Eclipse, create a new Android project and name it as ImageSwitcher. 

2 . Modify the main.xml file by adding the following statements in bold: 

<?xml​ version=”1.0”​encoding=”utf-8”?>
<RelativeLayout​
xmlns:android=”http://schemas.android.com/apk/res/android” ​
​​​android:orientation=”vertical”
​​​​android:layout_width=”fill_parent”
​​​​android:layout_height=”fill_parent” ​
​​​android:background=”#ff000000”​>

<Gallery
​​​​android:id=”@+id/gallery1” ​
​​​android:layout_width=”fill_parent”
​​​​android:layout_height=”wrap_content” />

<ImageSwitcher ​​​​
android:id=”@+id/switcher1” ​​​​
android:layout_width=”fill_parent” ​​​​
android:layout_height=”fill_parent” ​​
​​android:layout_alignParentLeft=”true” ​​​
​android:layout_alignParentRight=”true” ​​​
​android:layout_alignParentBottom=”true” />

</RelativeLayout>

3 . Right-click on the res/values folder and select New ➪ File. Name the file attrs.xml. 

4 . Populate the attrs.xml file as follows: 

<?xml version=”1.0” encoding=”utf-8”?>
<resources> ​
​​​<declare-styleable
name=”Gallery1”> ​​​
​​​​​<attr name=”android:galleryItemBackground” /> ​​​
​</declare-styleable>
</resources>

5 . Drag and drop a series of images into the res/drawable-mdpi folder When a dialog is displayed, check the copy option and click OK.

6 . Add the following bold statements to the MainActivity.java file: 

package com.emergingandroidtech.ImageSwitcher;

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

import android.content.Context;
import android.content.res.TypedArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery;
import android.widget.ViewSwitcher.ViewFactory;
import android.widget.ImageSwitcher;
import android.widget.ImageView;

public class MainActivity extends Activity implements ViewFactory {   
    //---the images to display---
    Integer[] imageIDs = {
            R.drawable.pic1,
            R.drawable.pic2,
            R.drawable.pic3,
            R.drawable.pic4,
            R.drawable.pic5,
            R.drawable.pic6,
            R.drawable.pic7                   
    };
   
    private ImageSwitcher imageSwitcher;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        imageSwitcher = (ImageSwitcher) findViewById(R.id.switcher1);
        imageSwitcher.setFactory(this);
        imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.slide_in_left));
        imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.slide_out_right));
       
        Gallery gallery = (Gallery) findViewById(R.id.gallery1);
        gallery.setAdapter(new ImageAdapter(this));
        gallery.setOnItemClickListener(new OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent,
            View v, int position, long id)
            {               
                imageSwitcher.setImageResource(imageIDs[position]);
            }
        }); 
    }
   
    public View makeView()
    {
        ImageView imageView = new ImageView(this);
        imageView.setBackgroundColor(0xFF000000);
        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        imageView.setLayoutParams(new
                ImageSwitcher.LayoutParams(
                        LayoutParams.FILL_PARENT,
                        LayoutParams.FILL_PARENT));
        return imageView;
    }

    public class ImageAdapter extends BaseAdapter
    {
        private Context context;
        private int itemBackground;

        public ImageAdapter(Context c)
        {
            context = c;

            //---setting the style---               
            TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
            itemBackground = a.getResourceId(
                    R.styleable.Gallery1_android_galleryItemBackground, 0);
            a.recycle();                                                   
        }

        //---returns the number of images---
        public int getCount()
        {
            return imageIDs.length;
        }

        //---returns the ID of an item---
        public Object getItem(int position)
        {
            return position;
        }

        public long getItemId(int position)
        {
            return position;
        }

        //---returns an ImageView view---
        public View getView(int position, View convertView, ViewGroup parent)
        {
            ImageView imageView = new ImageView(context);
           
            imageView.setImageResource(imageIDs[position]);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
            imageView.setBackgroundResource(itemBackground);
           
            return imageView;
        }
    }   
}

 7 . Run the application it shows the Gallery and ImageSwitcher views, with both the collection of images as well as the image selected.

Friday 13 March 2015

Gallery in Android

The Gallery is a view that shows items (such as images) in a center-locked, horizontal scrolling list.

The following example shows you how to use the Gallery view to display a set of images.

Using the Gallery View


1 . Using Eclipse, create a new Android project

2 . Modify the main.xml file as shown in bold:

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

<TextView ​​​​
android:layout_width=”fill_parent”
​​​​android:layout_height=”wrap_content” ​​​​
android:text=”Images of San Francisco” />

<Gallery
​​​​android:id=”@+id/gallery1”
​​​​android:layout_width=”fill_parent” ​​
​​android:layout_height=”wrap_content” />

<ImageView ​​​
​android:id=”@+id/image1” ​
​​​android:layout_width=”320px” ​​
​​android:layout_height=”250px” ​​​
​android:scaleType=”fitXY” />

</LinearLayout>

3 . Right-click on the res/values folder and select New ➪ File. Name the file attrs.xml. 

4 . Populate the attrs.xml file as follows: 

<?xml version=”1.0” encoding=”utf-8”?>
<resources>
​​​​<declare-styleable name=”Gallery1”>
​​​​​​​​<attr name=”android:galleryItemBackground” /> ​
​​​</declare-styleable>
</resources>

5 . Prepare a series of images and name them pic1.png, pic2.png, and so on.

6 . Add the following statements in bold to the MainActivity.java file:  

package com.emergingandroidtech.Gallery;

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

import android.content.Context;
import android.content.res.TypedArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {   
    //---the images to display---
    Integer[] imageIDs = {
            R.drawable.pic1,
            R.drawable.pic2,
            R.drawable.pic3,
            R.drawable.pic4,
            R.drawable.pic5,
            R.drawable.pic6,
            R.drawable.pic7                   
    };
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        Gallery gallery = (Gallery) findViewById(R.id.gallery1);
       
        gallery.setAdapter(new ImageAdapter(this));       
        gallery.setOnItemClickListener(new OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id)
            {               
                Toast.makeText(getBaseContext(),
                        "pic" + (position + 1) + " selected",
                        Toast.LENGTH_SHORT).show();
               
                //---display the images selected---
                ImageView imageView = (ImageView) findViewById(R.id.image1);               
                imageView.setImageResource(imageIDs[position]);
            }
        });
    }
   
    public class ImageAdapter extends BaseAdapter
    {
        private Context context;
        private int itemBackground;

        public ImageAdapter(Context c)
        {
            context = c;
            //---setting the style---
            TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
            itemBackground = a.getResourceId(
                R.styleable.Gallery1_android_galleryItemBackground, 0);
            a.recycle();                   
        }

        //---returns the number of images---
        public int getCount() {
            return imageIDs.length;
        }
       
        //---returns the ID of an item---
        public Object getItem(int position) {
            return position;
        }           
       
        //---returns the ID of an item---        
        public long getItemId(int position) {
            return position;
        }
 
        //---returns an ImageView view---
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView = new ImageView(context);
            imageView.setImageResource(imageIDs[position]);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
            imageView.setBackgroundResource(itemBackground);
            return imageView;
        }
    }   
}

7 . Shows the Gallery view displaying the series of images. 

8 . You can swipe the images to view the entire series of images. Observe that as you click on an image, the Toast class will display its name.



9 . To display the selected image in the ImageView, add the following statements in bold to the MainActivity.java file:

​​​​/**​Called ​when​ the ​activity ​is ​first ​created.​*/
​​​​@Override
​​​​public ​void​ onCreate(Bundle​savedInstanceState)
​{
​​​​​​​​super.onCreate(savedInstanceState);
​​​​​​​​setContentView(R.layout.main); ​​​​​​​​
​​​​​​​​Gallery ​gallery​=​(Gallery)​findViewById(R.id.gallery1); ​​​​​​​​
​​​​​​​​gallery.setAdapter(new​ImageAdapter(this));
​​​​​​​​gallery.setOnItemClickListener(new​OnItemClickListener() ​​
​​​​​​{ ​
​​​​​​​​​​​public ​void ​onItemClick(AdapterView<?> ​parent,​View ​v, ​​​​​​​​​​​​int ​position,​long ​id)
​​​​​​​​​​​​{ ​
​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(),​ ​​​​​​​​​​​​​​​​​​​​​​​​“pic”​+​(position​+​1)​+​“​selected”, ​​​​​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_SHORT).show();
​​​​​​​​​​​​​​​​
//---display the images selected---
​​​​​​​​​​​​​​​​ImageView imageView = (ImageView) findViewById(R.id.image1); ​​​​​​​​​​​​​​​​imageView.setImageResource(imageIDs[position]); ​​​
​​​​​​​​​} ​
​​​​​​​});
​​​​}

10 . This time, you will see the image selected in the ImageView.



Wednesday 11 March 2015

Android WebView Example

Webview 


The WebView enables you to embed a web browser in your activity. This is very useful if your appli- cation needs to embed some web content, such as maps from some other providers, and so on. The following Try It Out shows how you can programmatically load the content of a web page and dis- play it in your activity.

Using the WebView View


1 . Using Eclipse, create a new Android project and name it as WebView.

2 . Add the following statements to the main.xml file:

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

<WebView
android:id=”@+id/webview1” ​​
​​android:layout_width=”wrap_content” ​
​​​android:layout_height=”wrap_content” />

</LinearLayout>

3 . In the MainActivity.java file, add the following statements in bold:

package​ com.emergingandroidtech.WebView;
import​ android.app.Activity;
import ​android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;

public ​class ​MainActivity​ extends​ Activity
​{
​​​​
/**​Called​ when​ the ​activity ​is ​first ​created.​*/

​@Override ​​
​​public ​void ​onCreate(Bundle​savedInstanceState)​
{
​​​​​​​​super.onCreate(savedInstanceState);
​setContentView(R.layout.main);
​​​​​​​​
WebView wv = (WebView) findViewById(R.id.webview1);
​​​​​​​​WebSettings webSettings = wv.getSettings(); ​​
​​​​​​webSettings.setBuiltInZoomControls(true);
​​​​​​​​wv.loadUrl( ​​​​​​​​“www.google.com”);
​​​​}
}

Tuesday 10 March 2015

How to create notifications in android ?

Displaying Notifications


So far, you have been using the Toast class to display messages to the user. While the Toast class is a handy way to show users alerts, it is not persistent. It flashes on the screen for a few seconds and then disappears. If it contains important information, users may easily miss it if they are not looking at the screen. For messages that are important, you should use a more persistent method. In this case, you should use the NotificationManager to display a persistent message at the top of the device, commonly known as the status bar (sometimes also referred to as the notification bar).

Displaying notifications on the Status Bar


1 . Using Eclipse, create a new Android project and name it Notifications. 

2 . Add a new class file named NotificationView.java to the src folder of the project.
In addition, add a new notification.xml file to the res/layout folder as well.

3 . Populate the notification.xml file as follows:

<?xml ​version=”1.0”​encoding=”utf-8”?>

<LinearLayout​
xmlns:android=”http://schemas.android.com/apk/res/android”
​​​​android:orientation=”vertical”
​​​​android:layout_width=”fill_parent”
​android:layout_height=”fill_parent”​>

<TextView
​​​​android:layout_width=”fill_parent”
​​​​android:layout_height=”wrap_content” ​
​​​android:text=”Here are the details for the notification...” />

</LinearLayout>

4 . Populate the NotificationView.java file as follows:

package​ com.emergingandroidtech.Notifications;
import android.app.Activity;
import android.app.NotificationManager;
import android.os.Bundle;

public class NotificationView extends Activity
{
​​​​@Override
​​​​public void onCreate(Bundle savedInstanceState)
​​​​{
​​​​​​​​super.onCreate(savedInstanceState);
​​​​​​​​setContentView(R.layout.notification); ​​​​​​​​​​​​

​​​​​​​​//---look up the notification manager service---
​​​​​​​​NotificationManager nm = (NotificationManager) ​​​​​​​​​​​​getSystemService(NOTIFICATION_SERVICE);
​​​​​​​​
//---cancel the notification that we started
 ​​​​​​​​nm.cancel(getIntent().getExtras().getInt(“notificationID”)); ​​​​
}
}

5 . Add the following statements in bold to the AndroidManifest.xml file:

<?xml​ version=”1.0”​encoding=”utf-8”?>
<manifest​
xmlns:android=”http://schemas.android.com/apk/res/android” ​​​​​​package=”com.emergingandroidtech.Notifications” ​​​​​​
android:versionCode=”1” ​
​​​​​android:versionName=”1.0”> ​

​​​<application​
android:icon=”@drawable/icon”
​android:label=”@string/app_name”>
​​​​​​​​
<activity
​android:name=”.MainActivity” ​​​​​​​​​​​​​​​​​​
android:label=”@string/app_name”> ​​
​​​​​​​​​​<intent-filter> ​​​​​​​​​​​​​​​​<action ​android:name=”android.intent.action.MAIN”​/> ​​
​​​​​​​​​​​​​​<category ​android:name=”android.intent.category.LAUNCHER”​/> ​​​
​​​​​</intent-filter>
​​​​​​​​</activity>

 ​​​​​​​​<activity
android:name=”.NotificationView” ​​
​​​​​​​​​​android:label=”Details of notification”> ​
​​​​​​​​​​​<intent-filter>
​​​​​​​​​​​​​​​​<action android:name=”android.intent.action.MAIN” /> ​
​​​​​​​​​​​​​​​<category android:name=”android.intent.category.DEFAULT” /> ​​
​​​​​​​​​​</intent-filter>
​​​​​​​​</activity>
​​​​</application> ​​​
​<uses-sdk​
android:minSdkVersion=”9”​/>

​<uses-permission​
android:name=”android.permission.VIBRATE”​/>

</manifest>

6 . Add the following statements in bold to the main.xml file:

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

<Button ​​​​android:id=”@+id/btn_displaynotif”
​​​​android:layout_width=”fill_parent”
​​​​android:layout_height=”wrap_content” ​​​
​android:text=”Display Notification” />

</LinearLayout>

7 . Finally, add the following statements in bold to the MainActivity.java file:

package ​com.emergingandroidtech.Notifications;
import​ android.app.Activity;
import ​android.os.Bundle;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.View;
import android.widget.Button;

public ​class ​MainActivity ​extends​ Activity​
{
​​​​int notificationID = 1;

​​​​/**​Called ​when ​the ​activity ​is ​first ​created.​*/
​​​​@Override
​​​​public ​void ​onCreate(Bundle​savedInstanceState)​
{
​​​​​​​​super.onCreate(savedInstanceState);
​​​​​​​​setContentView(R.layout.main); ​​​​​​​​
​​​​​​​​Button button = (Button) findViewById(R.id.btn_displaynotif); ​​
​​​​​​button.setOnClickListener(new Button.OnClickListener()
{
​​​​​​​​​​​​public void onClick(View v)
{
​​​​​​​​​​​​​​​​displayNotification(); ​
​​​​​​​​​​​}
​​​​​​​​});
​​​​}
​​​​
protected void displayNotification() ​
​​​{
​​​​​​​​//---PendingIntent to launch activity if the user selects ​​​​​​​
​// this notification--- ​​​​
​​​​Intent i = new Intent(this, NotificationView.class); ​​​​
​​​​i.putExtra(“notificationID”, notificationID);
​​​​​​​​
PendingIntent pendingIntent = ​​​​​​​​​​​​PendingIntent.getActivity(this, 0, i, 0);
​​NotificationManager nm = (NotificationManager) ​​​​​​​​​​​​getSystemService(NOTIFICATION_SERVICE);
​​​​​​​​Notification notif = new Notification( ​​​​​​​​​​​​R.drawable.icon, ​​​​​​​​​​​​“Reminder: Meeting starts in 5 minutes”, ​​​​​​​​​​​​System.currentTimeMillis());

​​​​​​​​CharSequence from = “System Alarm”;
​​​​​​​​CharSequence message = “Meeting with customer at 3pm...”; ​​​​​​​​
​​​​​​​​notif.setLatestEventInfo(this, from, message, pendingIntent);
​​​​​​
​​//---100ms delay, vibrate for 250ms, pause for 100 ms and
​​​​​​​​// then vibrate for 500ms--- ​​​​
​​​​notif.vibrate = new long[] { 100, 250, 100, 500}; ​​​
​​​​​nm.notify(notificationID, notif);​​​​​​​​
​​​​}
}

8 . Click the Display Notification button and a notification will appear on the status bar. 

9 . Clicking and dragging the status bar down will reveal the notification . 

10 . Clicking on the notification will reveal the NotificationView activity. This also causes the notification to be dismissed from the status bar.





How It Works 

To display a notification, you first created an Intent object to point to the NotificationView class:

​​​​​​​​//---PendingIntent ​to​ launch​ activity ​if ​the ​user ​selects
​​​​​​​​//​this ​notification--- ​​
​​​​​​Intent ​i​=​new​Intent(this,​NotificationView.class);
​​​​​​​​i.putExtra(“notificationID”,​notificationID);

This intent will be used to launch another activity when the user selects a notification from the list of notifications. In this example, you added a key/value pair to the Intent object so that you can tag the notification ID, identifying the notification to the target activity. This ID will be used to dismiss the notifications later. You would also need to create a PendingIntent object. A PendingIntent object helps you to perform an action on your application’s behalf, often at a later time, regardless of whether your application is running or not. In this case, you initialized it as follows:
​​​​​​
​​PendingIntent ​pendingIntent​= ​​​​​​​​​​​​PendingIntent.getActivity(this,​0,​i,​0);

The getActivity() method retrieves a PendingIntent object and you set it using the following arguments:

➤context — Application context
➤ request code — Request code for the intent
➤ intent — The intent for launching the target activity
➤ flags — The flags in which the activity is to be launched

You then obtain an instance of the NotificationManager class and create an instance of the Notification class:

​​​​​​​​NotificationManager nm = (NotificationManager) ​​​​​​​​​​​​getSystemService(NOTIFICATION_SERVICE);
​​​​​​​​Notification notif = new Notification( ​​​​​​​​​​​​R.drawable.icon, ​​​​​​​​​​​​“Reminder: Meeting starts in 5 minutes”, ​​​​​​​​​​​​System.currentTimeMillis());

The Notification class enables you to specify the notification’s main information when the notification first appears on the status bar. The second argument to the Notification constructor sets the “ticker text” on the status bar.

Next, you set the details of the notification using the setLatestEventInfo() method:
​​​​​​​​
CharSequence from = “System Alarm”;
​​​​​​​​CharSequence message = “Meeting with customer at 3pm...”;
​​​​​​​​notif.setLatestEventInfo(this, from, message, pendingIntent);

​​​​​​​​//---100ms delay, vibrate for 250ms, pause for 100 ms and ​​
​​​​​​// then vibrate for 500ms--- ​​​
​​​​​notif.vibrate = new long[] { 100, 250, 100, 500};

The preceding also sets the notification to vibrate the phone. Finally, to display the notification you use the notify() method:
​​​​​​​​
nm.notify(notificationID, notif);

When the user clicks on the notification, the NotificationView activity is launched. Here, you dismiss the notification by using the cancel() method of the NotificationManager object and passing it the ID of the notification (passed in via the Intent object):
​​​​​​​​
//---look up the notification manager service---
​​​​​​​​NotificationManager nm = (NotificationManager) ​​​​​​​​​​​​getSystemService(NOTIFICATION_SERVICE);
​​​​​​​​
//---cancel the notification that we started
​​​​​​​​nm.cancel(getIntent().getExtras().getInt(“notificationID”));


Monday 9 March 2015

Android Custom dialog example

Displaying a dialog Window 

There are times where you need to display a dialog window to get a confirmation from the user. In this case, you can override the onCreateDialog() protected method defined in the base Activity class to display a dialog window.

The following Try It Out shows you how.

Displaying a Dialog Window Using an Activity


1 . Using Eclipse, create a new Android project and name it Dialog. 

2 . Add the following statements in bold to the main.xml file: 

<?xml ​version=”1.0”​encoding=”utf-8”?>

<LinearLayout​
xmlns:android=”http://schemas.android.com/apk/res/android” ​​​
​android:orientation=”vertical”
​​​​android:layout_width=”fill_parent” ​
​​​android:layout_height=”fill_parent”​>

<TextView ​​​​android:layout_width=”fill_parent”​ ​​
​​android:layout_height=”wrap_content”​
​​​​android:text=”@string/hello”​/>

<Button ​​​​android:id=”@+id/btn_dialog” ​​
​​android:layout_width=”fill_parent” ​​​​
android:layout_height=”wrap_content”
​​​​android:text=”Click to display a dialog” />

</LinearLayout>

3 . Add the following statements in bold to the MainActivity.java file:

package ​com.emergingandroidtech.Dialog;
import ​android.app.Activity;
import​ android.os.Bundle;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public ​class ​MainActivity ​extends​ Activity
​{
​​​​CharSequence[] items = { “Google”, “Apple”, “Microsoft” }; ​
​​​boolean[] itemsChecked = new boolean [items.length];
​​​
​/**​Called​ when​ the​ activity ​is ​first ​created.​*/ ​
​​​@Override
​​​​public ​void​ onCreate(Bundle​savedInstanceState)​
{ ​
​​​​​​​super.onCreate(savedInstanceState);
​​​​​​​​setContentView(R.layout.main);
​​​​​​​​
Button btn = (Button) findViewById(R.id.btn_dialog); ​​​
​​​​​btn.setOnClickListener(new View.OnClickListener()
{
​​​​​​​​​​​​public void onClick(View v)
{
​​​​​​​​​​​​​​​​showDialog(0); ​​​
​​​​​​​​​} ​
​​​​​​​});
​​​​}
​​​​
@Override
​​​​protected Dialog onCreateDialog(int id)
{
​​​​​​​​switch (id)
{ ​
​​​​​​​case 0: ​​​​​​​​​​​​
return new AlertDialog.Builder(this) ​​​​​​​​​​​​.setIcon(R.drawable.icon) ​​​​​​​​​​​​.setTitle(“This is a dialog with some simple text...”) ​​​​​​​​​​​​.setPositiveButton(“OK”, new ​​​​​​​​​​​​​​​​DialogInterface.OnClickListener()
{
​​​​​​​​​​​​​​​​public void onClick(DialogInterface dialog, ​​​​​​​​​​​​​​​​int whichButton) ​​​
​​​​​​​​​​​​​{ ​
​​​​​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​​​​​ “OK clicked!”, Toast.LENGTH_SHORT).show(); ​​
​​​​​​​​​​​​​​}
​​​​​​​​​​​​}) ​​​​​​​​​​​​.setNegativeButton(“Cancel”, new ​​​​​​​​​​​​​​​​DialogInterface.OnClickListener()
{
​​​​​​​​​​​​​​​​public void onClick(DialogInterface dialog, ​​​​​​​​​​​​​​​​​​​​int whichButton) ​​​​
​​​​​​​​​​​​{ ​
​​​​​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​​​​​​​​​“Cancel clicked!”, Toast.LENGTH_SHORT).show(); ​
​​​​​​​​​​​​​​​}
​​​​​​​​​​​​})
​.setMultiChoiceItems(items, itemsChecked, new ​​​​​​​​​​​​​​​​DialogInterface.OnMultiChoiceClickListener()
{
​​​​​​​​​​​​​​​​​​​​@Override ​
​​​​​​​​​​​​​​​​​​​public void onClick(DialogInterface dialog, int which, ​​​​​​​​​​​​​​​​​​​​boolean isChecked)
{ ​
​​​​​​​​​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​​​​​​​​​items[which] + (isChecked ? “ checked!”: ​​​​​​​​​​​​​​​​​​​​​​​​​​​​“ unchecked!”), ​​​​​​​​​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_SHORT).show(); ​​​​​​​​​​​​​​​​​​​​
} ​​​​​​​​​​​​​​​​
} ​​​​​​​​​​​​)
​​​​​​​​​​​​.create();
​​​​​​​​}
​​​​​​​​return null; ​

4 . Click the button to display the dialog. Checking the various checkboxes will cause the Toast class to display the text of the item checked/unchecked. To dismiss the dialog, click the OK or Cancel button.

How It Works 

To display a dialog, you first override the onCreateDialog() method in the Activity class:

@Override
protected ​Dialog​ onCreateDialog(int​ id)
​{ ​​​​
//...
}
​​​}
}

This method is called when you call the showDialog() method: ​

​​​​​​​Button ​btn​=​(Button)​findViewById(R.id.btn_dialog); ​​
​​​​​​btn.setOnClickListener(new​View.OnClickListener()​
{ ​​
​​​​​​​​​​public ​void​ onClick(View​ v)​
{ ​
​​​​​​​​​​​​​​​showDialog(0);
​​​​​​​​​​​​} ​
​​​​​​​});

The onCreateDialog() method is a callback for creating dialogs that are managed by the activity. When you call the showDialog() method, this callback will be invoked. The showDialog() method accepts an integer argument identifying a particular dialog to display. To create a dialog, you use the AlertDialog class’s Builder constructor. You set the various properties, such as icon, title, and buttons, as well as checkboxes: ​​​

​@Override
​​​​protected ​Dialog​ onCreateDialog(int ​id)​
{
​​​​​​​​switch​(id)
​{ ​​
​​​​​​case​0: ​​
​​​​​​​​​​return​ new​ AlertDialog.Builder(this) ​​​​​​​​​​​​.setIcon(R.drawable.icon) ​​​​​​​​​​​​.setTitle(“This​ is​ a ​dialog​ with​ some​simple​ text...”) ​​​​​​​​​​​​.setPositiveButton(“OK”,​new ​​​​​​​​​​​​​​​​DialogInterface.OnClickListener()​
{
​​​​​​​​​​​​​​​​public​ void​ onClick(DialogInterface ​dialog,​ ​​​​​​​​​​​​​​​​int​ whichButton) ​​
​​​​​​​​​​​​​​{ ​
​​​​​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​​​​​​“OK​clicked!”,​Toast.LENGTH_SHORT).show(); ​​​​​
​​​​​​​​​​​} ​
​​​​​​​​​​​}) ​​​​​​​​​​​​.setNegativeButton(“Cancel”,​new ​​​​​​​​​​​​​​​​DialogInterface.OnClickListener()​
{
​​​​​​​​​​​​​​​​public​ void ​onClick(DialogInterface​ dialog, ​​​​​​​​​​​​​​​​​​​​int​ whichButton) ​​
​​​​​​​​​​​​​​{
​​​​​​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​​​​​​​​​“Cancel​ clicked!”,​Toast.LENGTH_SHORT).show();
​​​​​​​​​​​​​​​​}
​​​​​​​​​​​​})
​​​​​​​​​​​​.setMultiChoiceItems(items,​itemsChecked,​new ​​​​​​​​​​​​​​​​DialogInterface.OnMultiChoiceClickListener()​
{
​​​​​​​​
​​​​​​​​​​​​@Override ​​
​​​​​​​​​​​​​​​​​​public ​void​ onClick(DialogInterface​ dialog,​int ​which, ​​​​​​​​​​​​​​​​​​​​boolean ​isChecked)​
{
​​​​​​​​​​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​​​​​​​​​items[which]​+​(isChecked​?​“​checked!”: ​​​​​​​​​​​​​​​​​​​​​​​​​​​​“​unchecked!”), ​​​​​​​​​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_SHORT).show(); ​​​​​​​​​​​​​​​​​​​​
}
​​​​​​​​​​​​​​​​} ​​​​​​​​​​​​)
​​​​​​​​​​​​.create(); ​​​​​
​​​}
​​​​​​​​return ​null; ​​​​
}

The preceding code sets two buttons:
OK and Cancel, using the setPositiveButton() and setNegativeButton() methods, respectively. You also set a list of checkboxes for users to choose via the setMultiChoiceItems() method. For the setMultiChoiceItems() method, you passed in two arrays: one for the list of items to display and another to contain the value of each item to indicate if they are checked. When each item is checked, you use the Toast class to display a message .

Wednesday 4 March 2015

Android Date Picker dialog

Displaying the DatePicker View in a Dialog Window 


Like the TimePicker, you can also display the DatePicker in a dialog window.

Using a Dialog to Display the DatePicker View


1 . Add the following statements in bold to the MainActivity.java file:

package ​com.emergingandroidtech.DatePicker;
import​ android.app.Activity;
import​ android.os.Bundle;
import​ android.view.View;
import​android.widget.Button;
import​ android.widget.Toast;
import​ android.app.Dialog;
import​ android.app.TimePickerDialog;
import​ android.widget.TimePicker;
import ​android.widget.DatePicker;
import android.app.DatePickerDialog;
import java.util.Calendar;

public ​class ​MainActivity​ extends ​Activity​{
​​​​TimePicker​ timePicker;
​​​​DatePicker ​datePicker;
​​​​int ​hour,​minute; ​
​​​int yr, month, day;
​​​​static​ final ​int ​TIME_DIALOG_ID​=​0; ​
​​​static final int DATE_DIALOG_ID = 1;
​​​​
/**​Called ​when ​the ​activity ​is ​first ​created.​*/
​@Override
​​​​public ​void ​onCreate(Bundle​savedInstanceState)​{
​​​​​​​​super.onCreate(savedInstanceState);
​​​​​​​​setContentView(R.layout.main);
​​​​​​​​
//showDialog(TIME_DIALOG_ID);
​​​​​​​​
//---get the current date---
​​​​​​​​Calendar today = Calendar.getInstance();
​​​​​​​​yr = today.get(Calendar.YEAR); ​
​​​​​​​month = today.get(Calendar.MONTH); ​​​​
​​​​day = today.get(Calendar.DAY_OF_MONTH); ​
​​​​​​​showDialog(DATE_DIALOG_ID);
​​​​​​​​timePicker​=​(TimePicker)​findViewById(R.id.timePicker); ​
​​​​​​​timePicker.setIs24HourView(true);
​​​​​​​​datePicker​=​(DatePicker)​findViewById(R.id.datePicker);
​​​​​​​​
//---Button​view---
​​​​​​​​Button​ btnOpen​=​(Button)​findViewById(R.id.btnSet);
​​​​​​​​btnOpen.setOnClickListener(new​View.OnClickListener()​
{
​​​​​​​​​​​​public ​void ​onClick(View​ v)​{
​​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​​​​​“Date​selected:”​+​datePicker.getMonth()​+ ​​​​​​​​​​​​​​​​​​​​​​​​“/”​+​datePicker.getDayOfMonth()​+ ​​​​​​​​​​​​​​​​​​​​​​​​“/”​+​datePicker.getYear()​+​“\n”​+ ​​​​​​​​​​​​​​​​​​​​​​​​“Time​selected:”​+​timePicker.getCurrentHour()​+ ​​​​​​​​​​​​​​​​​​​​​​​​“:”​+​timePicker.getCurrentMinute(), ​​​​​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_SHORT).show(); ​​​​​​​​​​​​​​​​} ​​​​​​​​
});
​​​​}
​​​​
@Override
​​​​protected​ Dialog ​onCreateDialog(int ​id)
​​​​{
​​​​​​​​switch​(id)
​{ ​
​​​​​​​​​​​case ​TIME_DIALOG_ID: ​​​
​​​​​​​​​​​​​return ​new​TimePickerDialog( ​​​​​​​​​​​​​​​​​​​​this,​mTimeSetListener,​hour,​minute,​false);
​​​​​​​​​​​​case DATE_DIALOG_ID: ​​
​​​​​​​​​​​​​​return new DatePickerDialog( ​​​​​​​​​​​​​​​​​​​​this, mDateSetListener, yr, month, day); ​​
​​​​​​}
​​​​​​​​return ​null;
​​​​}

​​​​private DatePickerDialog.OnDateSetListener mDateSetListener = ​​​​​​​​new DatePickerDialog.OnDateSetListener() ​​
​​​​​​{
​​​​​​​​​​​​public void onDateSet( ​​​​​​​​​​​​DatePicker view, int year, int monthOfYear, int dayOfMonth) ​​​​​​​​​​​​{
​​yr = year;
​​​​​​​​​​​​​​​​month = monthOfYear;
​​​​​​​​​​​​​​​​day = dayOfMonth;
​​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​​​​​“You have selected : “ + (month + 1) + ​​​​​​​​​​​​​​​​​​​​​​​​“/” + day + “/” + year, ​​​​​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_SHORT).show();
​​​​​​​​​​​​}
​​​​​​​​};
​​​​
private ​TimePickerDialog.OnTimeSetListener ​mTimeSetListener​= ​​​​​​​​new​TimePickerDialog.OnTimeSetListener() ​​​​​​​​
{
​​​​​​​​​​​​public ​void ​onTimeSet( ​​​​​​​​​​​​TimePicker​ view,​int ​hourOfDay,​int​ minuteOfHour) ​
​​​​​​​​​​​{
​​​​​​​​​​​​​​​​hour​=​hourOfDay;
​​​​​​​​​​​​​​​​minute​=​minuteOfHour;
​​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​​​​​“You​have​selected​:​“​+​hour​+​“:”​+​minute, ​​​​​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_SHORT).show();
​​​​​​​​​​​​}
​​​​​​​​};
}

How It Works 

The DatePicker works exactly like the TimePicker. When a date is set, it fires the onDateSet() method, where you can obtain the date set by the user:
​​​​​​​​​​​​
public ​void ​onDateSet( ​​​​​​​​​​​​DatePicker​ view,​int ​year,​int ​monthOfYear,​int ​dayOfMonth)
​​​​​​​​​​​​{
​​​​​​​​​​​​​​​​yr​=​year;
​​​​​​​​​​​​​​​​month​=​monthOfYear; ​​​
​​​​​​​​​​​​​day​=​dayOfMonth; ​
​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​​​​​“You​have​selected​:​“​+​(month​+​1)​+ ​​​​​​​​​​​​​​​​​​​​​​​​“/”​+​day​+​“/”​+​year, ​​​​​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_SHORT).show();
​​​​​​​​​​​​}

* Note that you have to initialize the three variables — yr, month, and day — before showing the dialog:
​​​​​​​​
//---get​the​current​date---
​​​​​​​​Calendar​ today​=​Calendar.getInstance();
​​​​​​​​yr​=​today.get(Calendar.YEAR); ​​
​​​​​​month​=​today.get(Calendar.MONTH); ​
​​​​​​​day​=​today.get(Calendar.DAY_OF_MONTH); ​​​
​​​​​showDialog(DATE_DIALOG_ID);

If you don’t, you will get an illegal argument exception error during run time  (“current should be >= start and <= end”) when you create an instance of the DatePickerDialog class.

Tuesday 3 March 2015

Date Picker in Android

DatePicker View

Another view that is similar to the TimePicker is the DatePicker. Using the DatePicker, you can enable users to select a particular date on the activity.

 1 .   main.xml file as shown here: 


<?xml​ version=”1.0”​encoding=”utf-8”?>

<LinearLayout
​xmlns:android=”http://schemas.android.com/apk/res/android” ​
​​​android:orientation=”vertical”
​​​​android:layout_width=”fill_parent”
​​​​android:layout_height=”fill_parent”​>

<DatePicker
android:id=”@+id/datePicker”
​​​​android:layout_width=”wrap_content”
​​​​android:layout_height=”wrap_content” />

<TimePicker
​android:id=”@+id/timePicker” ​​
​​android:layout_width=”wrap_content”
​​​​android:layout_height=”wrap_content”​/>

<Button​
android:id=”@+id/btnSet”
​​​​android:layout_width=”wrap_content” ​​
​​android:layout_height=”wrap_content”
​​​​android:text=”I​am​all​set!”​/>

</LinearLayout>

2 .  Add in the following statements in bold to the MainActivity.java file: 


package ​com.emergingandroidtech.DatePicker;
import​ android.app.Activity;
import​ android.os.Bundle;
import ​android.view.View;
import​ android.widget.Button;
import​ android.widget.Toast;
import​ android.app.Dialog;
import​ android.app.TimePickerDialog;
import​ android.widget.TimePicker;
import android.widget.DatePicker;

public ​class ​MainActivity​ extends ​Activity​
{ ​
​​​TimePicker ​timePicker;
​​​​DatePicker datePicker;
​​​​int ​hour,​minute;
​​​​static​ final ​int​ TIME_DIALOG_ID​=​0;
​​​​
/**​Called ​when​ the ​activity ​is ​first ​created.​*/
​​​​@Override
​​​​public ​void ​onCreate(Bundle​savedInstanceState)
​{ ​
​​​​​​​super.onCreate(savedInstanceState);
​​​​​​​​setContentView(R.layout.main);
​​​​​​​​
//showDialog(TIME_DIALOG_ID);
​​​​​​​​timePicker​=​(TimePicker)​findViewById(R.id.timePicker); ​​
​​​​​​timePicker.setIs24HourView(true); ​​​​​​​​
​​​​​​​​datePicker = (DatePicker) findViewById(R.id.datePicker);
​​​​​​​​
//---Button​view---
​​​​​​​​Button​ btnOpen​=​(Button)​findViewById(R.id.btnSet); ​
​​​​​​​btnOpen.setOnClickListener(new​View.OnClickListener()​{
​​​​​​​​​​​​public ​void ​onClick(View​ v)​
{ ​
​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​​​​​“Date selected:” + datePicker.getMonth() + 1 + ​​​​​​​​​​​​​​​​​​​​​​​​“/” + datePicker.getDayOfMonth() + ​​​​​​​​​​​​​​​​​​​​​​​​“/” + datePicker.getYear() + “\n” + ​​​​​​​​​​​​​​​​​​​​​​​​“Time​selected:”​+​timePicker.getCurrentHour()​+ ​​​​​​​​​​​​​​​​​​​​​​​​“:”​+​timePicker.getCurrentMinute(), ​​​​​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_SHORT).show(); ​​​​​​​​​​​​​​​​} ​​​​​​​
​});
​​​​}
​​​​@Override
​protected​ Dialog​ onCreateDialog(int​ id)
​​​​{
​​​​​​​​switch​(id)​
{ ​
​​​​​​​​​​​case ​TIME_DIALOG_ID:​ ​​​​​​​​​​​​​​​​
return ​new​TimePickerDialog( ​​​​​​​​​​​​​​​​​​​​this,​mTimeSetListener,​hour,​minute,​false); ​
​​​​​​​}
​​​​​​​​return ​null;
​​​​}
​​​​
private ​TimePickerDialog.OnTimeSetListener ​mTimeSetListener​= ​​​​​​​​new​TimePickerDialog.OnTimeSetListener()
​​​​​​​​{ ​
​​​​​​​​​​​public ​void ​onTimeSet( ​​​​​​​​​​​​TimePicker ​view,​int​ hourOfDay,​int​ minuteOfHour) ​​
​​​​​​​​​​{ ​
​​​​​​​​​​​​​​​hour​=​hourOfDay; ​​​​​​​​​​​​​​​​minute​=​minuteOfHour; ​​​​
​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​“You​have​selected​:​“​+​hour​+​“:”​+​minute, ​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_SHORT).show(); ​​
​​​​​​​​​​}
​​​​​​​​};
}

How It Works 

Like the TimePicker, you call the getMonth(), getDayOfMonth(), and getYear() methods to get the month, day, and year, respectively:

​​​​​​​​​​​​​​​​​“Date​selected:”​+​datePicker.getMonth()​+​1​+ ​​​​​​​​​​​​​​​​​“/”​+​datePicker.getDayOfMonth()​+ ​​​​​​​​​​​​​​​​​“/”​+​datePicker.getYear()​+​“\n”​+

* Note that the getMonth() method returns 0 for January, 1 for February, and so on. Hence, you need to add a one to the result of this method to get the month number.

Monday 2 March 2015

Android TimePicker Dialog

Displaying the TimePicker in a Dialog Window 


While you can display the TimePicker in an activity, a better way is to display it in a dialog window, so that once the time is set, it disappears and doesn’t take up any space in an activity.

Using a Dialog to Display the TimePicker View 


1 .

import​ android.app.Activity;
import ​android.os.Bundle;
import​ android.view.View;
import ​android.widget.Button;
import ​android.widget.TimePicker;
import​ android.widget.Toast;
import android.app.Dialog;
import android.app.TimePickerDialog;

public​ class ​MainActivity ​extends​ Activity
​{
​​​​TimePicker​timePicker;
​​​​int hour, minute;
​​​​static final int TIME_DIALOG_ID = 0;
​​​​
/**​Called​ when​ the ​activity ​is ​first ​created.​*/

​​​​@Override
​​​​public ​void​ onCreate(Bundle​savedInstanceState)​
{
​​​​​​​​super.onCreate(savedInstanceState);
​​​​​​​​setContentView(R.layout.main);
​​​​​​​​showDialog(TIME_DIALOG_ID);
​​​​​​​​timePicker​=​(TimePicker)​findViewById(R.id.timePicker);
​​​​​​​​timePicker.setIs24HourView(true);
​​​​​​​​//---Button​view--- ​​​​​​​​
Button​ btnOpen​ =​ (Button)​ findViewById(R.id.btnSet);
​​​​​​​​btnOpen.setOnClickListener(new​View.OnClickListener()​
{
​​​​​​​​​​​​public ​void ​onClick(View​ v)
​{ ​
​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​​​​​“Time​selected:”​+ ​​​​​​​​​​​​​​​​​​​​​​​​​​​timePicker.getCurrentHour().toString()​+​“:”​+​timePicker.getCurrentMinute().toString(), ​​​​​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_SHORT).show(); ​​​​​​​​​​​​​​​​
}
​​​​​​​​});
​​​​}
​​​​
@Override ​
​​​protected Dialog onCreateDialog(int id)
​​​​{
​​​​​​​​switch (id)
{
​​​​​​​​​​​​case TIME_DIALOG_ID: ​​​​​​​​​​​​​​​​return new TimePickerDialog( ​​​​​​​​​​​​​​​​​​​​this, mTimeSetListener, hour, minute, false); ​​​​​​​​} ​​​​​​​​
return null;
​​​​}
​​​​
private TimePickerDialog.OnTimeSetListener mTimeSetListener = ​​​​​​​​new TimePickerDialog.OnTimeSetListener() ​​​​​​​​{
​​​​​​​​​​​public void onTimeSet( ​​​​​​​​​​​​TimePicker view, int hourOfDay, int minuteOfHour) ​​​​
​​​​​​​​{
​​​​​​​​​​​​​​​​hour = hourOfDay; ​​​​
​​​​​​​​​​​​minute = minuteOfHour;
​​​​​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​“You have selected : “ + hour + “:” + minute, ​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_SHORT).show(); ​​​​​​​​​​​​
}
​​​​​​​​};
}
2 . When the activity is loaded, you can see the TimePicker displayed in a dialog window. Set a time and then click the Set button. You will see the Toast window displaying the time that you just set.

How It Works 

To display a dialog window, you use the showDialog() method, passing it an ID to identify the source of the dialog:
​​​​​​​​showDialog(TIME_DIALOG_ID);

When the showDialog() method is called, the onCreateDialog() method will be called:
​​​
​@Override
​​​​protected ​Dialog​ onCreateDialog(int ​id) ​​​
​{
​​​​​​​​switch​(id)
​{ ​
​​​​​​​​​​​case​TIME_DIALOG_ID: ​​​​​​​​​​​​​​​​return ​new​ TimePickerDialog( ​​​​​​​​​​​​​​​​​​​​this,​mTimeSetListener,​hour,​minute,​false);
​​​​​​​​}
​​​​​​​​return ​null;
​​​​}
Here, you create a new instance of the TimePickerDialog class, passing it the current context, the callback, the initial hour and minute, as well as whether the TimePicker should be displayed in 24-hour format. When the user clicks the Set button in the TimePicker dialog window, the onTimeSet() method will be called:

​​​​private​ TimePickerDialog.OnTimeSetListener ​mTimeSetListener​= ​​​​​​​​new​TimePickerDialog.OnTimeSetListener() ​​​​​​​​
{
​​​​​​​​​​​​public​ void​ onTimeSet( ​​​​​​​​​​​​TimePicker​ view,​int​ hourOfDay,​int ​minuteOfHour) ​​​
​​​​​​​​​{
​​​​​​​​​​​​​​​​hour​=​hourOfDay; ​
​​​​​​​​​​​​​​​minute​=​minuteOfHour; ​​​
​​​​​​​​​​​​​Toast.makeText(getBaseContext(), ​​​​​​​​​​​​​​​​​​​​“You​have​selected​:​“​+​hour​+​“:”​+​minute, ​​​​​​​​​​​​​​​​​​​​Toast.LENGTH_SHORT).show();
​​​​​​​​​​​​} ​
​​​​​​​};

Here, the onTimeSet() method will contain the hour and minute set by the user via the hourOfDay and minuteOfHour arguments, respectively.