Checking GPS is enabled or not in Android

by Krishnaraj Varma on July 25, 2010

in Android

Download CheckGPS (17)

While searching for how to programmatically find whether GPS is enabled or not in device, I found this excellent answer and created a sample application based on it. I think it is better to share it here.

{ 0 comments }

Using Text to Speech in Android

by Krishnaraj Varma on July 25, 2010

in Android

Download TTS Engine Sample (8)

Android supports TextToSpeech (TTS) from version 1.6 onwards. The Android TextToSpeech can speak different languages such as English, German, French, etc…, but we have to download the language resource files first before using it. We can install the language files by launching Intent with action set to TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA. The following code launches the installation of language data:

Intent intent = new Intent();
intent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(intent);

The class android.speech.tts.TextToSpeech is used for TTS in Android. The constructor has two parameters, Context and TextToSpeech.OnInitListener. The TextToSpeech.OnInitListener’s onInit method will be called when the TTS engine is initialized. The status is passed to the onInit(int status) method. The value TextToSpeech.SUCCESS indicates success and TextToSpeech.ERROR indicates error.

Once it is successfully initialized we can use the speak method to start speaking. The syntax of speak method is:

public int speak(String text, int queueMode, HashMap params)

The first parameter is the text to speak, second is parameter is the queuing mode. This parameter can be either TextToSpeech.QUEUE_ADD or TextToSpeech.QUEUE_FLUSH. The value TextToSpeech.QUEUE_FLUSH tells the system to drop all entries in the queue and start with the new text. TextToSpeech.QUEUE_ADD tells the system to append the new text the queue. The third parameter is a HashMap The key can have values TextToSpeech.Engine.KEY_PARAM_STREAM or TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID. If the key is TextToSpeech.Engine.KEY_PARAM_STREAM, then the value is one of the AudioManger’s stream types. When you specify one of these values, the TextToSpeech engine will use the settings of that particular stream to speak the text. Some of the possible values are:

String.valueOf(AudioManager.STREAM_ALARM)
String.valueOf(AudioManager.STREAM_MUSIC)
String.valueOf(AudioManager.STREAM_RING)

If the key is TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, then the value is a user defined string id. This can be used to check whether the TTS engine finished speaking the text or not. When the TTS engine finished speaking the text, the TextToSpeech.OnUtteranceCompletedListener’s onUtteranceCompleted method will be called. This technique is used in the sample application. For more information refer to the source code of the sample.

We can change the TTS engine’s language by using the method setLocale(Locale loc). The parameter loc specifies the Locale corresponds to desired language.

The speech rate can be set by using the method setSpeechRate(float speechRate). The parameter speechRate specifies the rate of the speech. 1 is normal rate. Lower values slow the speech rate and higher values increases the rate.

To change the pitch we use setPitch(float pitch). The parameter pitch specifies the pitch to use. 1 means normal, less than 1 lowers the tone and greater that 1 increases the tone.

I hope this gives you an introduction to the TTS in Android, for more detailed information refer to this excellent article.

Happy TTS coding!

{ 0 comments }

Getting IP address of the device in Android

by Krishnaraj Varma on July 25, 2010

in Android

Download IP Address Sample (13)

For one of my project I need to get the IP address of the device, I searched a lot and found this link.

The method is to enumerate all network interfaces and find the IP address if it is not loop-back adapter. This will give the IP address if you are connected to a network (WiFi or Cellular).

You can also use the WifiManger to get he IP address if you are connected to WiFi network. The following code retrieves the WiFi IP address:

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();

Note that the getIpAddress returns an integer value. To convert to readable format we can use the following code:

String.format("%d.%d.%d.%d",
(ipAddress & 0xff),
(ipAddress >> 8 & 0xff),
(ipAddress >> 16 & 0xff),
(ipAddress >> 24 & 0xff))

Note: To use the first method you need the android.permission.INTERNET permission, otherwise it will throw unknown error. For the second method you need android.permission.ACCESS_WIFI_STATE.

{ 0 comments }

Sending and Receiving SMS in Android

by Krishnaraj Varma on July 18, 2010

in Android

Download SMS Demo (36)

Sending SMS messages

The class SmsManager is used to send SMS messages in Android. Prior to API Level 4 android.telephony.gsm.SmsManager is used and in API level 4 onwards android.telephony.SmsManager is used. This class can send text, binary and multi-part messages.

Sending text messages

To send a text message, we use the method sendTextMessage. The syntax of the method is:

public void sendTextMessage (String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent)

The destinationAddress is the destination phone number, scAddress is the address of the service center (normally we pass null), the sentIntent is a broadcast which will be send when the SMS message is successfully sent from the device. The last parameter deliveryIntent is also a broadcast sent when the SMS message is delivered to the destination address.

Sending multi-part messages

SMS messages can have maximum of 160 characters in length. If you want to send a message longer than 160 characters, you have to split the message and sent one by one. The SmsManager has a convenient method sendMultipartTextMessage which can be used to send messages longer that 160 characters. The syntax is:

public void sendMultipartTextMessage (String destinationAddress, String scAddress, ArrayList parts, ArrayList sentIntents, ArrayList deliveryIntents)

The first and second parameters are same as previous. The third is an ArrayList of strings in the order of original message. When the destination device receives a multi-part message, it combines the message and display to the user. The forth one is an ArrayList of PendingIntent which will broadcast for each string part is send from the device. the fifth one is also an ArrayList of PendingIntent which will broadcast after the string part is delivered to the destination device.

To split the message in to different parts the SmsManager class has a method divideMessage. This function divides the entire message into several parts. Each part contains the maximum SMS message size.

Sending binary SMS message

To send a binary message, we use the method sendDataMessage. The syntax is:

public void sendDataMessage (String destinationAddress, String scAddress, short destinationPort, byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent)

The first and second parameters are same as previous methods, the third one is the destination port. The message will be sent to this port instead of the default one. The forth parameter is an array of byte which the message data to send. The fifth and sixth are pending intents to broadcast when the message is send and delivered respectively.

The system will not process the binary message to a specific port. You need an application that will receive the message to the specified port. Please refer to the sample application which receives both binary and text messages.

Please note that there is no method to send multi-part binary messages.

Receiving SMS message

To receive SMS message we create a broadcast receiver and register. The system will broadcast when a message is received. To receive text message we create broadcast receiver with action android.provider.Telephony.SMS_RECEIVED

To receive a binary message we create broadcast receiver with android.intent.action.DATA_SMS_RECEIVED. We also need to specify additional parameters, the receiving data port and the scheme.

The sample application for this article sends both binary and text messages. The application also has two broadcast receivers for both types.

{ 0 comments }

Getting battery information in Android

by Krishnaraj Varma on July 11, 2010

in Android

Download Battery Info Sample (25)

To get the battery information in Android we register a broadcast receiver with intent filter Intent.ACTION_BATTERY_CHANGED. In onReceive method, the intent received will have battery information. The intent contains many useful information about the battery, some of the bundle keys are :

    present
    technology
    plugged
    scale
    health
    voltage
    level
    temperature
    status

In API versions higher than 5, the BatteryManager has the constants for these keys. In lesser versions we have to hard-code these keys (I used Bundle.toString() method to get all the keys).

The battery level information is calculated by using the formula (level * 100) / scale.

{ 0 comments }

Getting speed of the device using GPS in Android

by Krishnaraj Varma on July 11, 2010

in Android

Download Speed Demo (23)

Most of the GPS receivers are capable of calculating speed of the device. All most all the GPS enabled phones expose the speed and other information through APIs. In Android we can specify whether we need the speed information while searching for best GPS provider.

The Criteria class provides a method setSpeedRequired to specify whether the provider should provide speed information. Passing true specify the speed information is required and false specify this information is not required. Please note that all GPS providers do not support this feature.

The getSpeed method of the Location class is used to get the speed information. The hasSpeed method returns true is speed information is available otherwise false. The speed reported in meters/second.

The accuracy of GPS speed information depends on many factors. To get more about the accuracy and how the receivers is calculating the speed follow this link.

Happy GPS coding!

{ 0 comments }

Geocoding and Reverse Geocoding in Android

by Krishnaraj Varma on July 4, 2010

in Android

Download Geocoder Sample (63)

Geocoding is the process of finding geographic location from location name, zip codes, etc… Reverse Geocoding is the process of finding location name and other information from geographic location. In Android there is a class Geocoder which handles Geocoding and Reverse Geocoding. This class has three methods: getFromLocation, getFromLocationName and a variant of getFromLocationName.

The method getFromLocation is used to reverse geocode and the method getFromLocationName is used to geocode. The getFromLocation method accepts 3 parameters: latitude, longitude and maximum number of results to return.

There are 2 variants of the method getFromLocationName. Both accept location name and maximum number of results to return. The first variant accepts additional four parameters. These are the longitude and latitude of the bounding rectangle for the search results. If you specify these parameters, the Geocoder will only search within the bounding rectangle, i.e. the results outside the bounding rectangle will not be included in the results.

These functions return a list of Address class which represents the result of the query.

The sample provided is a simple one to demonstrate the use of this class, hope this will help you to start geocoding.

{ 0 comments }

Vibrating the phone in Android

by Krishnaraj Varma on June 27, 2010

in Android

To vibrate the phone we use Vibrator class. This is a system service so we don’t instantiate but use getSystemService to get the instance of the class. The following code snippet vibrates the phone for a period of time.

Vibrator vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
long[] pattern = {0,1000,2000,3000};

vibrator.vibrate(pattern, -1);

The vibrate method accepts the pattern to vibrate and an index of the pattern to start repeating. If we don’t want to repeat pass -1. If we just want to vibrate for a period of time with default pattern then we can use the following variant of the vibrate method which vibrate for 1 second.

vibrator.vibrate(1000);

{ 0 comments }

Using Status Bar Notification in Android

by Krishnaraj Varma on June 27, 2010

in Android

Download Notification Sample (65)

This is an example of using Status Bar Notification in Android. Notifications are using in Android to notify the user of events. The classes Notification and NotificationManager is used create notification. NotificationManager is a system service. We get the instance using getSystemService. The following code snippet creates a default notification:

NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

int icon = R.drawable.icon;
CharSequence text = "Notification Text";
CharSequence contentTitle = "Notification Title";
CharSequence contentText = "Sample notification text.";
long when = System.currentTimeMillis();

Intent intent = new Intent(this, NotificationViewer.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);

Notification notification = new Notification(icon,text,when);

notification.setLatestEventInfo(this, contentTitle, contentText, contentIntent);

notificationManager.notify(Constants.NOTIFICATION_ID, notification);

For creating a status bar notification, we create an instance of Notification class and uses notify method of NotificationManager to add the trigger the notification. Here the Notification class is created with three parameters, icon to display, notification text to ticker and the time at which the notification is displayed. Then we set the notification title, notification text and the Pending Intent to launch when the user clicks on the notification.

The notify method of the NotificationManager is used to trigger the notification. This will add the notification to the status bar area. When the use pulls down the status bar the notification title, text and icon will be shown.

Vibrating the phone

If we want to vibrate the phone when the notification is displayed, then we can set the vibration pattern or use the flag to use the default vibration. Following code snippet sets the default vibration.

notification.defaults |= Notification.DEFAULT_VIBRATE;

To vibrate we set the vibrate member of the notification class. This is an array of long values; first element is the millisecond to wait before start, second is the length of the first vibration, third is the next millisecond to stay off and forth is the next millisecond to stay on and so on. The pattern can be as long as we like. Following code snippet sets the vibration:

long[] vibrate = {0,100,200,300};
notification.vibrate = vibrate;

Flashing the LED

If we want to flash the LED then we can use the defaults flag to DEFAULT_LIGHTS. Following code snippets adds the default LED flash.

notification.defaults |= Notification.DEFAULT_LIGHTS;

To use our own color pattern, set the ledARGB, ledOffMS, and ledOnMS and add the FLAG_SHOW_LIGHTS to the flag field. Following code snippets add a custom color pattern.

notification.ledARGB = Color.RED;
notification.ledOffMS = 300;
notification.ledOnMS = 300;

Using a custom view to display notification.

In the above example the notification is displayed in a default view. If we want to use our own custom view to display notification, then we can define the custom layout using the RemoteView. For this we create an instance of RemoteView and set the contentView field of the Notification class.

Note: If we are setting the contentView then we should set the contentIntent field also, otherwise an exception will occur.

The RemoteView provides helper methods to set the values of the layout items like setTextViewText, setProgressBar, setImageViewResource, etc…

The example provided here is a simple one to display default and custom view notifications. The custom view defines an image view, text view and a progress bar. Once the custom notification is triggered, the application creates a thread to start the progress bar update. This is a simple method display the progress indicator. Real world scenarios require more complicated method.

{ 0 comments }

Download Phone State Sample (137)

My previous article explains how to use the TelephonyManager. One of the important functionality of TelephonyManager is listening to different phone state events. The method listen(PhoneStateListener listener, int events) is used to add a phone state listener. The first parameter is the PhoneStateListener class and the second parameter is the int value contains various phone state to listen. We can listen for following events:

    PhoneStateListener.LISTEN_SIGNAL_STRENGTH
    PhoneStateListener.LISTEN_DATA_ACTIVITY
    PhoneStateListener.LISTEN_CELL_LOCATION
    PhoneStateListener.LISTEN_CALL_STATE
    PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR
    PhoneStateListener.LISTEN_DATA_CONNECTION_STATE
    PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR
    PhoneStateListener.LISTEN_SERVICE_STATE

The PhoneStateListener has following methods:

    void onCallForwardingIndicatorChanged(boolean cfi)
    void onCallStateChanged(int state, String incomingNumber)
    void onCellLocationChanged(CellLocation location)
    void onDataActivity(int direction)
    void onDataConnectionStateChanged(int state)
    void onDataConnectionStateChanged(int state, int networkType)
    void onMessageWaitingIndicatorChanged(boolean mwi)
    void onServiceStateChanged(ServiceState serviceState)
    void onSignalStrengthChanged(int asu)
    void onSignalStrengthsChanged(SignalStrength signalStrength)

The PhoneStateListener.LISTEN_SIGNAL_STRENGTH events invoke the onSignalStrengthChanged(int asu) method. This method requires the permission READ_PHONE_STATE. The method has one integer parameter which is the signal strength value. This value can be in the range 0-31. This function is deprecated in Android Version 2.0 and above. Above 2.0 we should use the onSignalStrengthsChanged(SignalStrength signalStrength) method. Only one parameter is there and it SignalStrenth class. The SignalStrength class has different following methods:

    int describeContents()
    boolean equals(Object o)
    int getCdmaDbm()
    int getCdmaEcio()
    int getEvdoDbm()
    int getEvdoEcio()
    int getEvdoSnr()
    int getGsmBitErrorRate()
    int getGsmSignalStrength()

The function names describes its purpose.

The PhoneStateListener.LISTEN_DATA_CONNECTION_STATE event invokes the methods onDataConnectionStateChanged(int state) and onDataConnectionStateChanged(int state, int networkType). Both these are invoked. The first parameter is the connection state and can be one of the following values:

    TelephonyManager.DATA_DISCONNECTED
    TelephonyManager.DATA_CONNECTING
    TelephonyManager.DATA_CONNECTED
    TelephonyManager.DATA_SUSPENDED

The PhoneStateListener.LISTEN_DATA_ACTIVITY event invokes the method onDataActivity(int direction). This method requires the permission READ_PHONE_STATE. The direction parameter can be one of the following values:

    TelephonyManager.DATA_ACTIVITY_IN
    TelephonyManager.DATA_ACTIVITY_OUT
    TelephonyManager.DATA_ACTIVITY_INOUT
    TelephonyManager.DATA_ACTIVITY_NONE

The PhoneStateListener.LISTEN_CALL_STATE event invokes the method onCallStateChanged(int state, String incomingNumber). This method requires the permission READ_PHONE_STATE. The state parameter can be one of the following values:

    TelephonyManager.CALL_STATE_IDLE
    TelephonyManager.CALL_STATE_RINGING
    TelephonyManager.CALL_STATE_OFFHOOK

The incomingNumber parameter contains the incoming number if the state is TelephonyManager.CALL_STATE_RINGING.

The PhoneStateListener.LISTEN_CELL_LOCATION event invokes the method onCellLocationChanged(CellLocation location) method. This method requires the permission ACCESS_COARSE_LOCATION. This will be an instance of GsmCellLocation class. GsmCellLocation class is explained in my previous article.

The PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR event invokes the method onCallForwardingIndicatorChanged(boolean cfi) method. This method requires the permission READ_PHONE_STATE. The boolean parameter cgi indicates whether the current call is forwarding or not.

The PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR event invokes the method onMessageWaitingIndicatorChanged(boolean mwi). This method requires the permission READ_PHONE_STATE. The boolean parameter mwi indicates whether an incoming message is waiting for user attention or not.

The PhoneStateListener.LISTEN_SERVICE_STATE event invokes the method onServiceStateChanged(ServiceState serviceState). The parameter is an instance of ServiceState class. The ServiceState class has methods to retrieve operator name in short alphanumeric format, operator name in short long format, operator id, etc…

To un-register a listener we use the method listen with event parameter set to LISTEN_NONE.

The sample provided is same for this and the previous article. Hope this article helps to to get started with PhoneStateListener.

{ 0 comments }