Archive

Archive for the ‘Android API’ Category

JSON Parsing in android

October 29th, 2009

Let’s look at how to parse JSON objects in android

1> First we’ll need an example :

Lets look at a standard example from the json site http://json.org/example.html

     {"menu": {
				  "id": "file",
				  "value": "File",
				  "popup": {
				    "menuitem": [
				      {"value": "New", "onclick": "CreateNewDoc()"},
				      {"value": "Open", "onclick": "OpenDoc()"},
				      {"value": "Close", "onclick": "CloseDoc()"}
				    ]
				  }
				}}

you could either save this in a file or save it in a string…..like I’ve done

2> Android already contains the required JSON libraries

Lets create a JSON Object;

private JSONObject jObject;

and lets our example be a String ,

private String jString = "{\"menu\":	{\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": 	[ {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"}, 	{\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, 	 	{\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";

now we have to convert jString to the jObject ,

jObject = new JSONObject(jString); 

Now we have to start extracting the content from jObject ,

Lets extract the menu object by creating a new menu object,

JSONObject menuObject = jObject.getJSONObject("menu");

Now lets extract its atrtibutes ,

String attributeId = menuObject.getString("id");
String attributeValue = menuObject.getString("value");
JSONObject popupObject = menuObject.getJSONObject("popup");

since “popup” is not plainly a String lets extract it to an object ,

3> Now popup contains an array of “menuitem”

So, we’ll have to extract it to a JSONArray,

 JSONArray menuitemArray = popupObject.getJSONArray("menuitem"); 

Since it contains 3 items lets put it in a for loop.

for (int i = 0; i < 3; i++) {
			System.out.println(menuitemArray.getJSONObject(i)
					.getString("value").toString());
			System.out.println(menuitemArray.getJSONObject(i).getString(
					"onclick").toString());
		}

Basically thats it , u should see the output in the DDMS

4> The full code is as below,

import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;

public class JsonParser extends Activity {
	private JSONObject jObject;
	private String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\",   \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		try {
			parse();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void parse() throws Exception {
		jObject = new JSONObject(jString);

		JSONObject menuObject = jObject.getJSONObject("menu");
		String attributeId = menuObject.getString("id");
		System.out.println(attributeId);

		String attributeValue = menuObject.getString("value");
		System.out.println(attributeValue);

		JSONObject popupObject = menuObject.getJSONObject("popup");
		JSONArray menuitemArray = popupObject.getJSONArray("menuitem");

		for (int i = 0; i < 3; i++) {
			System.out.println(menuitemArray.getJSONObject(i)
					.getString("value").toString());
			System.out.println(menuitemArray.getJSONObject(i).getString(
					"onclick").toString());
		}
	}
}

Android, Android API, Mobile Market , , , , , , ,

Android Audio Support

February 13th, 2009

Android support Media API as optional APIs. The media APIs provide functionality of playing and recording audio files and video files. In today’s post we will see how to play and record audio files.

Playing Audio File:
Android has defined a MediaPlayer class for playing media file. This class can be used to play the audio files. The class provides static methods to create the instance of the media player. Here is how the MediaPlayer object can be obtained using create methods

MediaPlayer.create(context, Uri.parse("file:///sdcard/audio_file.mp3");

and

MediaPlayer.create(context, R.raw.song_file);

The first create methods gets the Uri for the audio file and can be used to play files present on the phone sdcard. The second create method use the application resource file song_file.mp3. The song_file.mp3 file is added as a raw resource under res/raw directory.
Note that if the MediaPlayer object does not get created successfully, the create methods will return null so it will be better to check for the return object for null value to avoid NullPointer exception.

The MediaPlayer object can also be obtained by instantiating using MediaPlayer constructor. The object created like this has to be initialized with the file that needs to be played. setDataSource() method can be used to initialize the object with the audio file.

MediaPlayer mediaPlayer = new MediaPlayer();

try {
mediaPlayer.setDataSource("/sdcard/audio_file.mp3"); // provide path to the file.
} catch (IllegalArgumentException e) {
// handle exception
} catch (IllegalStateException e) {
// handle exception
} catch (IOException e) {
// handle exception
}

If you want to send the media player object with one of the files from application raw resources or from application assets files you can do that as follows:

try {
AssetFileDescriptor fd = getResources().openRawResouceFd(R.raw.song_file);
mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
fd.close();
} catch (IllegalArgumentException e) {
// handle exception
} catch (IllegalStateException e) {
// handle exception
} catch (IOException e) {
// handle exception
}

The MediaPlayer object has to be prepared before the player can start playing the song. The prepare() method is the blocking method and blocks until the media player is ready to play the song. One non blocking method prepareAsync() is also provided. The non blocking prepare method should be used in case media player is used to play a song from a stream and need to buffer data before song can be played. The create methods that we saw earlier call the prepare() method and application must not call it again. To start file playback use start() method. This is how you play a file:

MediaPlayer mediaPlayer = new MediaPlayer();

try {
mediaPlayer.setDataSource("/sdcard/audio_file.mp3"); // provide path to the file.
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// handle exception
} catch (IllegalStateException e) {
// handle exception
} catch (IOException e) {
// handle exception
}

mediaPlayer.start();

The file playback can be pause with pause() method, and can be resumes with start method. The file playback can be stopped with stop() method. The media player object has to reset before it can be setup for some other song file. The media player object has to be released after its use.

Android Media API defines some listeners like OnCompletionListener, OnPrepareListener, OnErrorListener, OnBufferingUpdateListener
OnCompletionListener event gets fired when media player complete the playing of the current audio file. You can use this listener event for playing next song from the list or releasing the media player object.

OnPrepareListener is needed when prepareAsync method is used. Since the prepareAsync method does not block for the call duration, the application can not start playing the song. The onPrepared() event function will be called once the media player is ready. You can start playing the song in the onPrepared() method.

OnErrorListener is also used in case of asynchronous operations. If any error occurs in asynchronous operation, onError() method of this listener will be called.

Recording Audio Files:

The Media API also provides functionality to record audio files. The MediaRecorder class can be used for media recording. The MediaRecorder has to be initialized with the Audio Encoder, output format (codec to be used for recorded file), Audio Source (like Microphone) and output file path where the recorded file will be stored. Here is how recording can be done:

MediaRecorder recorder = new MediaRecorder();

recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

recorder.setOutputFile(filePath); // complete file path

recorder.prepare(); recorder.start();

This will start the recording the recording can be stored with stop() method. The MediaRecorder object also needs to be release after its use.
That all for today’s post. We will see Media APIs Video support in some other post.

Android, Android API , , , , ,

Android Basics – Alarm Service

February 3rd, 2009

Today we will see Alarm Service provided by Android. Android provide AlarmManager class. The class provides access to the android Alarm Service. AlarmManager provide the methods to set the alarms. Alarm can be one time or repeating. When the alarms goes off (alarm time occurs) a pending intent will be broadcasted that can invoke a BroadCastReceiver (intent receiver) or Service or Activity.

Let’s see how to set alarms. The Alarm Manger instance for the Alarm service can be obtained as follows:

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

There are 4 types of alarms the AlarmManager has defined constants for each type as RTC, RTC_WAKEUP, ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP.

While setting an alarm, a pending intent has to be defined. The pending intent is called when alarm goes off.
One time alarms:
One time alarm can be set using AlarmManager set() method. Here is how it can be done:

Intent intent = new Intent(this, OnetimeAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), sender);
Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();

The pending intent is created for a Broadcast Receiver, the receiver is just notifying the user using Toast. The alarm is set to 10 secs from current time. Here is the code for the intent receiver:

public class OnetimeAlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
}
}

Repeating alarm:
Setting a repeating alarm is similar to setting one time alarm. The repeating alarm can be set using setRepeating() method of AlarmManager. Here is the code:

Intent intent = new Intent(this, RepeatingAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), 10 * 1000, pendingIntent);
Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();

There is only one parameter extra in case of repeating alarm. The repeating alarm takes interval after which the alarm should be repeated. In this case the alarm is repeating itself after 10 secs.

The code of the RepeatingAlarmReceiver is:

public class RepeatingAlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Repeating Alarm worked.", Toast.LENGTH_LONG).show();
}
}

The repeating alarms have to be cancelled to stop them. AlarmManager provide a cancel() method that requires the same intent class with which the intent is created. This is how you can cancel the alarm.

alarmManager.cancel(pendingIntent);

Note the pendingIntent object does not need to be same object. The intent fields like action, class, category etc should be same while creating the alarm. The intent is used to identify the alarm to cancel it.

E.g. Alarm Clock:
You can create a wake up alarm with the help of android Alarm service and notification service. The ring tone and the vibration pattern can be put in the intent of extras that can be retrieved by the Broadcast receiver. The code will be as follows:

Intent intent = new Intent(this, RepeatingAlarmReceiver.class);

intent.putExtra("Ringtone", Uri.parse("file:///sdcard/audiofile.mp3"));
intent.putExtra("vibrationPatern", new long[] { 200, 300 });
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), (24 * 60 * 60 * 1000), pendingIntent);

The alarm is set as daily (will repeat after 24 hours). The broadcast receiver can show a notification with the help of the notification service.

NotificationManager manger = (NotificationManager)     context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, "Wake up alarm", System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
notification.setLatestEventInfo(context, "Context Title", "Context text", contentIntent);
notification.flags = Notification.FLAG_INSISTENT;

notification.sound = (Uri) intent.getParcelableExtra("Ringtone");
notification.vibrate = (long[]) intent.getExtras().get("vibrationPatern");

// The PendingIntent to launch our activity if the user selects this notification
manger.notify(NOTIFICATION_ID, notification);

You can set appropriate values for contentIntent as your need. You can also pass an array of boolean for each day like Sunday, Monday etc. The intent receiver will match the current day with the alarm days and show the alarm notification accordingly.

Android API , , , ,

Android Location API

January 16th, 2009

Android support Location based service APIs. Location service allows to find out the device current location. The application can ask for periodic update of the device location. The application can also register a intent receiver for proximity alerts like when the device is entering and existing from an area of given longitude, latitude and radius.

Let’s check the important classes present in the android.location package.

Android Location API:

Following are the some important classes present under the android location package.

LocationManager: The class provides access to the location service. It also provides facility to get the best Location Provider as per the criteria. Proximity alerts can be set (as said above) with help of this class.

LocationProvider: It’s an abstract superclass for location providers. A location provider provides periodic reports on the geographical location of the device.

LocationListener: Provides callback methods which are called when location gets changed. The listener object has to be registered with the location manager.

Criteria: The class provides the application to choose suitable Location Provider by providing access to set of required properties of the LocationProvider.

Android also provide an API to access the Google MAPs. So with the help of the Google MAPs and the location APIs the application can show required places to the user on the MAP. Let’s see Android support for the Google APIs.

Google Map API

Android defines a package called com.google.android.maps. The package contains classes related to rendering, controlling and overlaying information on the Google maps on the android devices. Let’s see the most important classes defined in the package:

MapActivity: It is the spacing activity defined to show the Google MAPs. The MapActivity takes care of the low-level networking.

MapView: MapView is the view that supports and displays the map. This must be contained by a MapActivity.

MapController : MapController is the object used to move the map around the screen.

Overlay: It’s a drawable object that can be shown on top of the map.

GeoPoint: It’s a position in latitude-longitude.

Now we have some basic knowledge of the Location and Map APIs, so let’s create some application and see them in action.

Application:

Let’s develop an application that shown the Google MAP on the screen and shows the user’s current position on the MAP. We will use Google MAP APIs to show map on the device and then use location APIs to get the device current location to show it on the MAP. The user location will gets updated if the user moved from the current location.

Application Activity:

To use map in an activity that activity has to be extended by the MapActivity as shown..

class MyGPSActivity extends MapActivity {
...
}

To use the Google MAP APIs, application AndroidManifest.xml file must define following XML element, as a child of the application element:

<uses-library android:name=”com.google.android.maps” />

Using the MapView:

To display Map we need to add MapView to the application. Add following in the activity’s layout file (main.xml).

<com.google.android.maps.MapView
android:id="@+id/myGMap"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="API_Key_String"
/>

To use the Google Map service an API key is needed. The API key can obtained as follows:

1) Get debug.keystore file. You will get this under USER_HOME\Local Settings\Application Data\Android directory.

2) Use keytool tool to generate Certificate fingerprint (MD5). Use following command on command prompt

keytool -list -alias androiddebugkey -keystore <path_to_debug_keystore>.keystore -storepass android -keypass android

3) Go to ‘Sign Up for the Android Maps API‘ page.  Put your Certificate fingerprint (MD5) And get your API key for android GMap application.

4) Replace “API_Key_String” with your API key.

Update the MyGPSActivity class to use the MapView

class MyGPSActivity extends MapActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
// Creating and initializing Map
gMapView = (MapView) findViewById(R.id.myGMap);
GeoPoint p = new GeoPoint((int) (lat * 1000000), (int) (long * 1000000));
gMapView.setSatellite(true);
//get MapController that helps to set/get location, zoom etc.
mc = gMapView.getController();
mc.setCenter(p);
mc.setZoom(14);
}
...
}

Certain permission has to be set in the AndroidManifest.xml file to use location information.

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>

Using Location Manager:

The location manage object can be obtained with Context.getSystemService method with Context.LOCATION_SERVICE parameter.

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

Update the GPSActivity to implement the LocationListener interface so that the activity can listener to the location changes.

class MyGPSActivity extends MapActivity implements LocationListener {
...
/* This method is called when use position will get changed */
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
protected boolean isRouteDisplayed() {
return false;
}

}

Lets add code to initialize the LocationManager and register the Location Listener with the location manager in the onCreate() method

@Override

public void onCreate(Bundle savedInstanceState) {
...
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, this);

}

Now the onLocationChanged method of the GPSActivity method will be called if the user changes its position by 500m. A “gps” (GSP_PROVIDER) provider is used here but you can obtain a provider object as per your needs with the getBestProvider method of the LocationManger and the Criteria object.

Here is the implementation of the onLocationChanged method

public void onLocationChanged(Location location) {
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
p = new GeoPoint((int) lat * 1000000, (int) lng * 1000000);
mc.animateTo(p);
}

}

The code changes the map location to the new updated location.

We can add extra things in our application like Zoom controls, Marker and Text to show current location etc.

Adding Zoom control:

The MAP api provides facility to add zoom control to the map display. Following code add zoom control to your application:

// Adding zoom controls to Map

ZoomControls zoomControls = (ZoomControls) gMapView.getZoomControls();

zoomControls.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,

LayoutParams.WRAP_CONTENT));

gMapView.addView(zoomControls);

gMapView.displayZoomControls(true);

Adding Map Overlay:

A map overlay can be added showing the user’s current location. To add an overlay, define a class that will extend Overlay class.

class MyLocationOverlay extends com.google.android.maps.Overlay {
@Override

public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {

super.draw(canvas, mapView, shadow);
Paint paint = new Paint();
// Converts lat/lng-Point to OUR coordinates on the screen.
Point myScreenCoords = new Point();
mapView.getProjection().toPixels(p, myScreenCoords);
paint.setStrokeWidth(1);
paint.setARGB(255, 255, 255, 255);
paint.setStyle(Paint.Style.STROKE);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.marker);
canvas.drawBitmap(bmp, myScreenCoords.x, myScreenCoords.y, paint);
canvas.drawText("Here I am...", myScreenCoords.x, myScreenCoords.y, paint);
return true;

} }

The overlay display a text “Here I am..” on the map at user location.

Let’s add this overlay to our map view

// Add a location mark

MyLocationOverlay myLocationOverlay = new MyLocationOverlay();

List<Overlay> list = gMapView.getOverlays();

list.add(myLocationOverlay);

Running application on Emulator:

Run the emulator instance. The latitude and longitude values can be supplied to the emulator with the help of ‘Emulator Control’ window present in the DDMS eclipse perspective. According to latitude and longitude application will display location of user.

gpsapp

Download the sample code here

Android API , , ,

Android API – SMS handling

December 29th, 2008

Many new application will use SMS as data delivery platform. Reality shows, on-demand movies etc request users to send predefined formatted SMS. Similarly some applications are coming up which sends data to user using SMS. Let’s see how such an application can be built using Android platform.

Android API support developing applications that can send and receive SMS messages. The android emulator does not support sending of the SMS currently. But the emulator can receive SMS. Lets explore the android SMS support and develop a small program that listens to the SMSes received on the device (on emulator) and will show that message as notification.

The event handling on Android is done with the help of intents and intent receivers. The intents  announce (or broadcast) the event and intent receivers respond to the event. Intent receivers act as the event handlers.

Let’s define an intent receiver that can handle the SMS received event:

package com.wissen.sms.receiver;
/**
* The class is called when SMS is received.
*/
public class SMSReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
// TODO
}
}

We need to configure this intent receiver to receive SMS receive event. For SMS receive event android has defined an intent as ‘ android.provider.Telephony.SMS_RECEIVED ‘. The receiver can be configured in AndroidManifest.xml as follows:

<receiver android:name=".receiver.SMSReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>

To receive SMS, application also needs to specify permission for receiving SMS. The permission can be set in AndroidManifest.xml as follows:

<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>

Now our intent receiver is all set to be called when the android device will receive SMS. Now we only need to retrieve the received SMS and show the SMS text in a notification.

Here is the code of intent receiver that will read the SMS from intent received and show the first message (pdu).

public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();

		Object messages[] = (Object[]) bundle.get("pdus");
		SmsMessage smsMessage[] = new SmsMessage[messages.length];
		for (int n = 0; n &lt; messages.length; n++) {
		smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
		}

		// show first message
		Toast toast = Toast.makeText(context,
		"Received SMS: " + smsMessage[0].getMessageBody(), Toast.LENGTH_LONG);
		toast.show();
		}

The SMS received by the Android device is in the form of pdus (protocol description unit). Class SmsMessage, defined in android.telephony.gsm package, can store information about the SMS. The class can also be used to create SmsMessage object from received pdus. Toast widget is used to show the SMS body as an notification.

Running the Program:
Only remaining thing now is running the application and sending the SMS message to the emulator. An SMS message can be sent to the emulator in the DDMS eclipse perspective (Dalvik Debug Monitor Service). ‘Emulator Control’ window can be used to send SMS message (an incoming number has to be provided which can be anything).

Here is the application screen shot in action,

Android SMS receiver application

Android SMS receiver application

Download the sample code here

Join the forum discussion on this post - (1) Posts

Android API , ,