JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Location tracker in Android using GPS positioning and SQLite

July 31, 2011 by Krishna Srinivasan Leave a Comment

Introduction

Android is an Open source software stack which has gained market in leaps and bounce. This includes operating system, middleware and key applications. The advantage android brings along with it is the ease of application development. Android application can be developed at a brisk rate with lesser learning curve using the tools and API provided by Android SDK. The tools and key applications have made the life of developers very easy.

Android basically has Linux as the core operating system with a Java interface. Android applications are run on Dalvik Virtual Machines. Each android application will run on different instances of DVM. Dalvik has the capabilities to run different VM’s efficiently. SQLite is Android specific database available by default in Android phones. SQLite is a lightweight and powerful database engine, and can be used in any type of application development.

also read:

  • How to set up android development environment?
  • How to write AndroidManifest.xml?
  • How to create a new activity in Android?
  • Android Books

SQLite Database in Android

Every mobile application might be handling data which have to be permanently stored and retrieved at a later instance of time. In android, SQLite is a lightweight database which is embedded into the platform by default. Most of the common database operations can be done using methods available in SQLite. The syntax is very similar to SQL syntax.

SQLite is a lightweight database which does not require any configuration. As the memory space required is minimal, it is suitable for mobile applications.

Android SDK provides two classes, which can be used by developers in order to use SQLite.

  • SQLiteOpenHelper- This class helps in creating the database and controlling version changes
  • SQLiteDatabase- This class helps in performing basic database operations

GPS in Android

Nowadays we are seeing many application related to location provider or location finder. The technique explained in this document may be used in developing several applications like Find a friend, get the updates about the location when you enter near the proximity of a given location etc.

To build a location based application classes are available in the android library, like Location Provider , Location Manager , Location etc . To find the location of the particular device Location Listener interface should be implemented by the class.

Introduction to the application

The document explains SQLite and Location Provider through an application which gets the GPS location and saves the location details in the database.

Step 1:

Create a simple android project. The project will have the below folder structure.

Step 2:

Create a class named as ‘GPSLocation’ in com.demo package. The class should extend ‘Activity’ class.

[java]public class GPSLocation extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}[/java]

Step 3:

Create an inner class named as ”MylocListener’. This class implements ‘LocationListerner’ interface.It is used for receiving notification from the LocationManager class when the location changes. LocationManager class is an inbuilt class in Android which allows applications to obtain latitude and longitude co-ordinates of the mobile device.

LocationListener interface has four unimplemented methods which have to be implemented in MylocListener class.

  • onLocationChanged()- Whenever location has been changed for a device the LocationManager class will implicitly call this method passing the new location has a parameter in the form of location object.
  • onProviderDisabled
  • onStatusChanged
  • onProviderEnabled

The other three methods can be left blank as those are not required in this application.

[java]public class MylocListener implements LocationListener {
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
String text = " My location is Latitude ="+loc.getLatitude() + " Longitude =" + loc.getLongitude();
lat=loc.getLatitude() + "";
log=loc.getLongitude()+"";
updateDatabase();
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled (String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}[/java]

The onLocationChanged methods has Location object as a parameter. The latitude and longitude of the location can be obtained from this object by using getLatitude() and getLognitude() methods.

Step 4:

Inside the onCreate() method create an instance of LocationManager class. getSystemService is an inbuilt method available for getting the handler on a particular service by passing appropriate service name. Here the service name is ‘LOCATION_SERVICE’.
Create a reference of LocationListener and initialize with the inner class created in Step 3. The inner class implements LocationListner interface. From ‘mylocman’ object call the method named as requestLocationUpdates(). This methods accepts four parameters, namely:

  • The default GPS provider available in the mobile device
  • Minimum time internal between successive notification
  • Minimum distance internal between successive notification in meters
  • The LocationListener object, whose onLocationChanged() method will be called for each location update

[java]LocationManager mylocman = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener myloclist = new MylocListener();
mylocman.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,myloclist);[/java]

Step 5:

The GPS location will be available in the location object. Now the location details have to be stored in the database. Create a database utility class named as ‘GPSDatabase’.

Create an inner classs named DBhelper which extends SQLiteOpenHelper class. SQLiteOpenHelper is a helper class to manage database creation activities. This takes care of opening the database if it exits else creates a new one.

The SQLiteOpenHelper has two unimplemented methods which should be implemented:

  • OnCreate()
  • onUpgrade()

onCreate() method is called when the database is created for the first time. The creation of tables and population of data happens in this method. onUpgrade method is called whenever to drop, add or alter the tables.

In the code given below execSQL() method is called to create a table. The method takes a query in the form of string as a parameter.

Open method and close method are used to open and close the connection with database. There are two user defined methods:

  • insertRow()
  • getAllRows()

[java]public class GPSDatabase {
private Context context;
private DbHelper dbHelper;
public final String DBNAME="gps1";
public final int DBVERSION=3;
public SQLiteDatabase db;
public final String COLUMN2="latitude";
public final String COLUMN3="longitude";
public final String COLUMN1="locationId";
public final String TABLENAME="location";
public final String CREATERDB="create table location(locationId integer primary key autoincrement,
latitude text not null, longitude text not null);";
//const
public GPSDatabase(Context context){
this.context=context;
dbHelper=new DbHelper(context);
}
public class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context){
super(context,DBNAME,null,DBVERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATERDB);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
public long insertRows(String column2, String column3){
ContentValues value=new ContentValues();
value.put(COLUMN2, column2);
value.put(COLUMN3, column3);
return db.insert(TABLENAME,null,value);
}
public Cursor getAllRows(){
Cursor cursor=db.query(TABLENAME, new String[]{COLUMN1,COLUMN2,COLUMN3}, null,null, null, null, null);
return cursor;
}
public void open() throws SQLException{
db= dbHelper.getWritableDatabase();
//return true;
}
public void close(){
dbHelper.close();
//return true;
}
}[/java]

In insertRows() create an object of ContentValues which can hold all the values to be inserted into the database. This can be achieved by calling insert()method of SQLilteDatabase class. The ContentValues object along with the table name should be passed as a parameter for the insert() method.

The method named getAllRows() queries all the rows from the corresponding table. The query() method of SQLilteDatabase class is used for retrieving data from the database. This method has eight parameters. The table to be queried is passed as the first parameter. The second parameter indicates the list of columns to be retrieved from the table. The other parameters are the different constraints that can be applied while querying the table(like groupby, orderBy having etc).These parameters can be set to null, if constraints are not required. The method returns a cursor containing the specified columns.

Step 6:

Whenever the device gets a new position from the GPS satellite, onlocationChange() method inside MylocListener class will be called. Since the position needs to be stored in database, the updateDatabase() method should be called.

In this method create an instance of GPSDaatbase class, which the database utility class. Open the database connection by calling the open() method. In order to insert the data call insetRow() method passing the values to be inserted as a parameter. In this case , the latitude and longitude coordinates will be passed as a parameter. After the successful insertion close the database by calling the close() method.

[java]public void updateDatabase(){
GPSDatabase myDatabase=new GPSDatabase(context);
myDatabase.open();
myDatabase.insertRow(lat.substring(0,4),log.substring(0,4));
myDatabase.close();
}[/java]

Step 7:

In order to track all locations traversed by a particular device, the co-ordinate positions should be displayed. To achieve this, place a button on the activity and on the click of the button the detailed report is displayed. Since the list should be displayed on the click of the button, Activity class should implement OnClickListener interface. onClick() method is an unimplemented method of this interface, which should be implemented.

Inside the onClick() method create a instance of GPSDatabase class and call the open method. In order to display the detailed report call getAllRows() method which returns a cursor containing all the values from the database . The values are added to an ArrayList object from the cursor. This ArrayList object is bound to List item component in Activity through a ListAdapter.

[java]public void onClick(View v) {
Context context = getApplicationContext();
GPSDatabase myDatabase=new GPSDatabase(this);
myDatabase.open();
Cursor cursor=myDatabase.getAllRows();
cursor.moveToFirst();
listContents= new ArrayList();
for (int i = 0; i < cursor.getCount(); i++) {
listContents.add("Lat=" +cursor.getString(1) +" "+"Log "+ cursor.getString(2));
cursor.moveToNext();
}
myDatabase.close();
ListAdapter adapter=new ArrayAdapter(this,android.R.layout.simple_dropdown_item_1line, listContents);
list=(ListView)findViewById(R.id.ListView01);
list.setAdapter(adapter);
}[/java]

Conclusion

The document explains how to track the location of the device and insert the values into SQLite database. The detailed steps used in order to achieve this requirement are briefed. This knowledge can be enhanced to develop any android apps related to database or location.

also read:

  • How to set up android development environment?
  • How to write AndroidManifest.xml?
  • How to create a new activity in Android?
  • Android Books

Filed Under: Google Android Tagged With: Google Android

Android’s JSON parser

May 8, 2011 by Krishna Srinivasan Leave a Comment

This article is based on Android in Practice, to be published on Summer 2011. It is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) ebooks and pbooks. MEAPs are sold exclusively through Manning.com. All print book purchases include an ebook free of charge. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information.

Technique: Parsing JSON

Introduction

The AJAX(Asynchronous JavaScript and XML) craze that accompanied the rise of the Web 2.0 was a key element to giving modern websites a desktop application like user experience. Interestingly, just like the XMLHttpRequest object, AJAXmade another thing popular, one which had been around for years, but the full potential of which had never really been recognized: JSON, the JavaScript Object Notation. (Never before has the invention, or better, the discovery of a single class made so much difference!).

also read:

  • How to set up android development environment?
  • How to write AndroidManifest.xml?
  • How to create a new activity in Android?

The AJAX(Asynchronous JavaScript and XML) craze that accompanied the rise of the Web 2.0 was a key element to giving modern websites a desktop application like user experience. Interestingly, just like the XMLHttpRequest object, AJAXmade another thing popular, one which had been around for years, but the full potential of which had never really been recognized: JSON, the JavaScript Object Notation. (Never before has the invention, or better, the discovery of a single class made so much difference!)

Problem

You want to integrate with a Web service that either only supports JSON or you specifically want to take advantage of JSON‘s benefits such as being able to efficiently create and manage textual representations of data structures in memory.

Solution

Before looking at the JSON API bundled with Android, let’s have a closer look at how JSON represents objects. If you’re already familiar with JavaScript, then this will, well, look familiar to you. If not, then JSON can still be quickly explained.

Basically, you can think of JSON objects as maps or object hashes. Starting with a single root element, other elements (the values) are mapped to identifiers (the keys). Here’s how this book could be modeled in JSON:

[java]{
"title": "Android in Practice",
"price": 49.99,
"authors": [
{ "name": "C. Collins" },
{ "name": "M. Galpin" },
{ "name": "M. Kaeppler }
]
}[/java]

This simple data structure already combines all kinds of syntax elements JSON knows. Finally something that’s dead simple and tremendously useful at the same time, something you seldom find anymore in computers these days!

Curly braces in JSON demarcate objects. An object is a map: it maps keys (the quotes are mandatory) to values. A value can again be an object, a string (any value put in double quotes becomes a string), or a number (with or without decimal point). Moreover, a value can also be an array of any of these. Arrays are demarcated using square brackets.

Even though it’s simple enough, you don’t have to parse JSON documents yourself, of course. Android comes with the JSON implementation from JSON.org (the reference implementation), so you can use that straight away. Before showing you how to use it to parse JSON data, let’s suppose we get our data from the TMDb Web service, which incidentally also supports JSON. Let’s have a look at what the response to Movie.imdbLookup method looks like when requested as JSON (listing 1).

Listing 1 JSON response format of TMDb’s Movie.imdbLookup method

[java][
{
"popularity":3,
"translated":true,
"adult":false,
"language":"en",
"original_name":"Inception",
"name":"Inception",
"alternative_name":"Eredet",
"movie_type":"movie",
"id":27205,
"imdb_id":"tt1375666",
"url":"http://www.themoviedb.org/movie/27205",
"votes":52,
"rating":9.0,
"certification":"PG-13",
"overview":"Dom Cobb (Leonardo DiCaprio) is a skilled thief, the best in the dangerous art of extraction: stealing valuable secrets from deep within the subconscious during the dream state when the mind is at its most vulnerable. …",
"released":"2010-07-16",
"runtime":148,
"version":226,
"last_modified_at":"2010-08-19 16:04:03",
…
}
][/java]

As we can see, the result is an array with a single element (since we’ve only requested a single movie), which represents the movie. Now we need to turn this into a Movie object, so we finally need to get hold of Android’s JSON parser. Listing 2 shows how that could look like.

Listing 2 JsonMovieParser.java parses a TMDb movie document using JSON

[java]public class JsonMovieParser {
public static Movie parseMovie(InputStream json) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(json));
StringBuilder sb = new StringBuilder(); #1
String line = reader.readLine();
while (line != null) {
sb.append(line);
line = reader.readLine();
}
reader.close();
JSONArray jsonReply = new JSONArray(sb.toString()); #2
Movie movie = new Movie();
JSONObject jsonMovie = jsonReply.getJSONObject(0); #3
movie.setTitle(jsonMovie.getString("name"));
movie.setRating(jsonMovie.getString("rating"));
return movie;
}
}

#1 Holds the server response as a string
#2 Turns the response string into a JSONObject
#3 Gets the movie JSONObject[/java]

The JSON parser relies on the data being in memory entirely, so we have to read the response string into a buffer first (#1). We can then use this string to instantiate a JSON object (a JSONArray in this case, since the root element is an array), which effectively parses the JSON string into an internal key-value map (#2). We’re interested in the first and only element of the array, so we get the JSONObject at position 0, which is the movie we’re after (#3). Any such JSONObject has accessor methods to read its values like strings, numbers, and other JSON objects or arrays.

Discussion

JSON is the most straightforward and simple way to parse a Web service response. It’s also efficient and lightweight: it’s basically nothing more than a Java HashMap mapping strings to other objects. If you can use the Java Map interface, then you can use Android’s JSON classes.

Of course an implication of this is that the json.org parser may not be the optimal choice if you need to consume really large documents, especially if you only want to access a tiny fraction of the information they contain. You probably don’t want to parse several megabytes of text into a JSON object, since it will be in memory all at once. In that case, XmlPull is probably your best bet. For anything else, the stock parser is a very good choice.

NOTE

If your documents are large, but you absolutely must rely on JSON for some reason (e.g. because the data you want to access is only available in JSON), you may want to look for a stream-based JSON parser like Jackson instead. This of course means adding another dependency to your project, so choose wisely.

There’s one subtlety you should be aware of when using Android’s JSON parser: You should always know upfront which values will be part of the response when you parse it. That’s because a JSONObject’s get*() methods will throw an exception if you try to access a field that is not there. For the elements that can exist in some responses but not in others (for optional elements), you should use the opt*() methods instead, which simply return null if the field you’re trying to access does not exist (in other words, use optString() instead of getString() for accessing an optional string field).

also read:

  • How to set up android development environment?
  • How to write AndroidManifest.xml?
  • How to create a new activity in Android?
  • Android Books

Summary

JavaScript is a very good choice for serializing data from a Web server to a JavaScript host environment such as a Web browser since a JSON server response can be executed by the client using JavaScript’s eval() function. JSON is the most straightforward and simple way to parse a Web service response. It’s also efficient and lightweight. If you can use the Java Map interface, then you can use Android’s JSON classes.

Filed Under: Google Android Tagged With: Google Android, JSON

Creating Services in Android

February 25, 2011 by Krishna Srinivasan Leave a Comment

Introduction

Services in Android are components which run in the background. They do not have any user interface. One application can start a service and the service can run in the background even if this application is switched with a new application by the user. There are two types of services namely Unbound Service and Bound Service Unbound Service is a kind of service which runs in the background indefinitely, even if the activity which started this service ends. Bound Service is a kind of service which runs till the lifespan of the activity which started this service. In this article we are going to see step by step procedure to how to create an unbound service.

also read:

  • How to set up android development environment?
  • How to write AndroidManifest.xml?
  • How to create a new activity in Android?

Android Development Tools

The software tools required for this example are as below:

  • 1. Java Development kit (JDK 5 or higher)
  • 2. Android Software Developer’s Kit(SDK)
  • 3. Eclipse IDE Eclipse version 3.4 or higher preferably galileo
  • 4. Android Developer Tool (ADT)

How to create a Android service class?

Step 1:

Create an Android Application in Eclipse as below:
Go to File->New-> Other->Android->Android Project
Provide a Project Name, Select a build target. Provide Application name, package name, Activity name, min sdk version and click finish.

Step 2:

Create a folder named raw inside the res folder of your Android Application. Copy a mp3 file to this folder and rename it without any extension with all the letters in lowercase. Check whether a resource id is generated for the same in R.java file in your Android application.

Step 3:

Right click on the Android Project created->New->Class
Provide a Class Name. Click on Browse button near the superclass option, type Service in the search box. Select the Service class from the package android.app and click finish.
Now a class which extends from the Service class will be generated in your Android application.

Step 4:

Edit the class and modify the code similar to the one below

[java]import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private static final String TAG = "MyService";
MediaPlayer player;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.sound_file_1);
player.setLooping(false); // Set looping
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}

}[/java]

}

In the above code, onCreate method is overridden to initialize the Mediaplayer with the file you have pasted in the raw folder.onDestroy method is overridden to stop the player.onStart method is overridden to start the player.

Creating Layout

Step 1:

Go to res folder of your project->layout. Here you can see an xml file, edit the file. Otherwise right click on the folder and create a new layout file(Go to New->other->Android XML File->select Layout and give a name)

Step 2:

In the Layout file add two buttons, name it as start and stop and set a background image for the screen

The Layout code is as below:

[java]
<?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" android:background="@drawable/newyear1">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Services Demo"
/>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/buttonStart" android:text="Start"></Button>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Stop" android:id="@+id/buttonStop"></Button>
</LinearLayout>

[/java]

Updating the Activity Class

Step 1 :

Update the Activity class as below:

[java]import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ServicesDemo extends Activity implements OnClickListener {
private static final String TAG = "ServicesDemo";
Button buttonStart, buttonStop;
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this); }
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart: Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MyService.class));
break;
case R.id.buttonStop: Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
break;
}
}
}[/java]

In the activity class above the onCreate method is overriden in which, the layout you have created is set as the main screen and the event listener for the button is set and the onClick method is defined to start the service and stop the service based on the input event.

startService method is used to start the service in unbound mode, i.e; the service will continuously run without regard for the activity which initiated it.

  • Android Books

stopService method is used to stop the service from the current activity, even if the current activity is restarted.

Output of the Application

Given below is the output for the service application in the emulator:

This output shows that your mediaplayer started in the background and it starts playing. You can move to other activities, still you can hear the music is keep on playing in the background.

To stop the servie either navigate back to your service activity and click the stop button. You will get the output as below. Your service will be stopped. Another way is leave the service as such till the time the song ends, your service will use stopSelf method to stop itself after the timeout period

Conclusion

Service is a basic building block of Android. Services can be bound or unbound based on the coding methodology followed. The unbound service can be used to have a separate process which should be executed apart from the activity.

also read:

  • How to set up android development environment?
  • How to write AndroidManifest.xml?
  • How to create a new activity in Android?

Filed Under: Google Android Tagged With: Google Android

New Features in Google Android 2.3

February 5, 2011 by Krishna Srinivasan Leave a Comment

Android is the first open source software stack for mobile/handheld devices. Android predominantly provides support for building rich & flexible mobile apps. Android platform includes a compatible Linux kernel based OS, rich UI, applications, support libraries, application frameworks, support for multimedia, and more. The underlying OS components are written in C/C++ and user applications are built for Android in Java.

The Android 2.3 platform which is popularly known as Gingerbread introduces many new and electrifying features for users and game & application developers. Along with Rich user interface experience, Android adds new features for developing the mobile applications also. In this article, we will understand the Android developer features in detail.

  • Android Books
  • Android Articles

What is Gingerbread?

To build the mobile applications easily and more dexterous, Google Android 2.3 platform comprises awesome improvements for users and developers.

New user features includes on-screen keyboard for faster input and more perceptive typing, rationalized user interface with various color schemes and lots of user interface changes for consistent and simpler usage, managing application and power to ensure background processes, memory usage and CPU time utilization along with killing the mischievous applications by using task killer, SIP Internet calling for integrating VOIP into Android platform and efficient download manager.

The following are some of the new features for developers:

  • The new video driver package: For leveraging faster3D graphics, Android works with OpenGL ES with improved performance.
  • Synchronized garbage collector: Android’s Virtual machine Dalvik launches its new concomitant garbage collector to reduce application suspensions and ensure smoother animation with augmented receptiveness in applications. The new JIT optimizations enable Dalvik code execute faster.
  • Efficient event handling: The Android platform performs well in efficiently utilizing the CPU during event handling like touch and key board events. This is very much useful in improving the responsiveness for all applications including CPU-intensive operations.
  • Native development: The Android gives the ability to make applications work with Native Development Kit to intercept inputs and sensor events for producing sound, animations, manipulating 3D graphics, access assets and storage using native code.
  • Enhanced Multimedia: Audio effects like deep boost, headphone virtualization and reverb and equalization are enhanced with local/global accessible tracks. The platform provides built-in support for video transmission and encoding. Also, it has integral support for front and rear cameras.
  • NFC support (Near Field Communications): Using NFC mechanism, applications can connect and respond to stockers, smart posters and other enabled devices.

Understanding the features of Android

1. Using video player in Android

Step 1: Creating VideoActivity to make the UI for Video View

[java]public class VideoActivity extends Activity {
// launching method
@Override
public void onCreate(Bundle state) {
super.onCreate(state);
//UI layout definied to load the VideoView control
setContentView(R.layout.main);
//getting the videoview control
VideoView videoView = (VideoView) findViewById(R.id.VideoView);
//defining the Media controller to control the multi media
MediaController mc = new MediaController(this);
//setting the videoView as anchor to mediacontroller
mc.setAnchorView(videoView);
//loading the the mp4 file from the Android memory
videoView.setVideoPath("/data/h.mp4");
videoView.setMediaController(mc);
videoView.requestFocus();
//starting the play
videoView.start();
}
}[/java]

Step 2: Define the VideoView in main.xml layout

[java]&lt;VideoView android:layout_height="fill_parent" android:
layout_width="fill_parent" android:id="@+id/VideoView"/&gt;[/java]

Step 3: Pushing the video file to Android memory card from command execution adb push h.mp4 /data/h.mp4

The output of video view is as :

2. Retrieving the contacts stored in the device using Android API

Step 1: Creating ContactsView activity class to make the UI

[java]// ContactsView is the user defined activity class
public class ContactsView extends Activity {
/** activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// tracing the text view
TextView cView = (TextView) findViewById(R.id.contactview);
// creating the cursor for the contacts
Cursor mycursor = managedQuery(ContactsContract.Contacts.CONTENT_URI, // URI
new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME },// selection of
// contacts
ContactsContract.Contacts.IN_VISIBLE_GROUP + " = ‘" + ("1") + "’", null, ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC");// projection of contacts
// displaying the contact names
while (mycursor.moveToNext()) {
String name = mycursor.getString(mycursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
cView.append("Contact Name: ");
cView.append(name);
cView.append("\n\n");
}
}
}[/java]

Step 2: Define the Layout in main.xml

[java]&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent"&gt;
&lt;TextView android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="@+id/contactview" /&gt;[/java]

The output is shown in the emulator screen.

3. Using Alarm service in Android platform

Step 1: Creating the SetAlarm Activity to display the interface

[java]public class SetAlarm extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void run(View view) {
EditText eText = (EditText) findViewById(R.id.seconds);
int n = Integer.parseInt(eText.getText().toString());
Intent intent = new Intent(this, Receiver.class);
PendingIntent pIntent = PendingIntent.getBroadcast(
getApplicationContext(), 111, intent, 0);
AlarmManager a = (AlarmManager) getSystemService(ALARM_SERVICE);
a.set(AlarmManager.RTC, System.currentTimeMillis() + (n * 1000),pIntent);
Toast.makeText(this, "Setting alarm in " + n + " seconds!", Toast.LENGTH_SHORT).show();
}
}[/java]

Step 2: Creating a receiver when alarm bells:

[java]public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Vibrate the mobile phone
Vibrator vib = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(3000);
Toast.makeText(context, "Oops! Time is up!!", Toast.LENGTH_SHORT).show();
}
}[/java]

Step 3: Creating the layout xml as below:

[java]&lt;EditText android:layout_width="wrap_content"
android:inputType="numberDecimal" android:layout_height="wrap_content"
android:id="@+id/seconds" android:hint="Enter no of seconds"/&gt;
&lt;Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/yes"
android:onClick="run" android:text="Start Alarm"/&gt;[/java]

Step 4: Manifest xml file can be updated as below:

[java]&lt;application android:icon="@drawable/icon" android:label="@string/app_name" &gt;
&lt;activity android:name=".SetAlarm" android:label="@string/app_name" &gt;
&lt;intent-filter &gt;
&lt;action android:name="android.intent.action.MAIN" / &gt;
&lt;category android:name="android.intent.category.LAUNCHER" / &gt;
&lt;/intent-filter &gt;
&lt;/activity &gt;
&lt;receiver android:name=".Receiver" android:enabled="true" &gt;
&lt;/receiver &gt;
&lt;/application &gt;
&lt;uses-sdk android:minSdkVersion="9" / &gt;[/java]

[java]
&lt;uses-permission android:name="android.permission.VIBRATE"&gt;&lt;/uses-permission&gt;[/java]

The output is shown in the emulator screen.

After clicking the start counter, the Toast class displays the text as below:

Once the alarm bells, the following screen will be updated (with vibration on device) as below:

Conclusion

Android runs with a Linux kernel for its platform. Java programming can be used to write Android applications, those programs can run within Dalvik VM. Every Android application runs within a Dalvik VM that is residing within Linux-kernel optimized process. The basic building blocks of Android applications are activities, intents, services, and content providers. Android provides a sophisticated web browser that is based on the WebKit open source project.

  • Android Books
  • Android Articles

Talkzilla is the coolest smartphone app for making low cost calls,Reliable, easy to use and fun : Android & iOS low cost calling app.

Filed Under: Google Android Tagged With: Google Android

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved