Download source code of this article.
Just for fun and time-pass I created a sample RSS reader application based on this article. I think it is better to share it here.
Point of Interest: Downloading XML data from Internet, XML parsing, AsyncTask.
Download source code of this article.
Just for fun and time-pass I created a sample RSS reader application based on this article. I think it is better to share it here.
Point of Interest: Downloading XML data from Internet, XML parsing, AsyncTask.
Download source code of this article.
Almost all mobile phones have a built in digital camera. Android phones are no exception. In Android device, to access the camera hardware we use Camera class along with SurfaceView.
The Camera class let you change the settings, preview and take still pictures. The SurfaceView class is used to show the preview to the user. To use the camera feature you should have the android.permission.CAMERA permission.
First we create a SurfaceView to show the live preview. The SurfaceView class holds the surface to draw. We use the interface SurfaceHolder to access the underlying surface. We implement the callback interface SurfaceHolfer.Callback and add this to the SurfaceHolder using SurfaceHolder.addCallback method. The SurfaceHolfer.Callback interface has three methods:
abstract void surfaceChanged(SurfaceHolder holder, int format, int width, int height) abstract void surfaceCreated(SurfaceHolder holder) abstract void surfaceDestroyed(SurfaceHolder holder)
The surfaceCreated method will be called after the surface is created, surfaceChanged will be after any changes have been made to the surface and surfaceDestroyed will be called after the surface is destroyed.
To find more about the SurfaceView and SurfaceHolder interface refer to the Google documentation.
Once our surface is created we open the Camera using Camera.open() method. After opening the camera, we set the live preview surface using setPreviewDisplay() method of the Camera class. We open and set the preview surface once the surfaceCreated() method is called because at this point the surface will be created and initialized properly.
Now we have to set the appropriate parameters to start the camera using the Camera.Parameters class. We can get the current camera parameter using the getParameters() method of the Camera class. We set the camera parameter once the surfaceChaneged() method is called. Once we set all the camera parameters we can start preview using Camera.startPreview() method. This will start the live preview.
The Camera class uses different callback interface to report different events to the application. The following callback interfaces are used to notify the events;
Camera.AutoFocusCallback Camera.ErrorCallback Camera.PictureCallback Camera.PreviewCallback Camera.ShutterCallback
The Camera.AutoFocusCallback interface is used to notify the completion of auto focus. Note that all devices may not have auto-focus feature. The onAutoFocus() will be called once the auto focus in finished. We use Camera.autoFocus() method to start the auto focus.
The Camera.ErrorCallback interface is used to notify when an error occurred. The onError() method will be called if an error occurred during the camera operation.
The Camera.PictureCallback interface is used to supply the image data after the picture is taken. The onPictureTaken() method will be called once the data is available. The format of the data depends on the current camera picture format which can be set using Camera.Parameters class.
The Camera.PreviewCallback interface is used to notify the supply the current preview frame. The onPreviewFrame() method will be called when the preview frame is available. Again the format of the data depends on the current camera picture format.
The Camera.ShutterCallback interface is to notify when the picture is captured from the camera. The onShutter() method will be called once the picture is taken from the camera.
To take a still picture, we use the method Camera.takePicture() The takePicture() method has three parameters. First one is a Camera.ShutterCallback interface to notify when the picture is captured from the camera. Second one is Camera.PictureCallback interface to notify when raw data is available from the camera. The third one is another Camera.PictureCallback interface when the JPEG data is available from the device.
In API version 5 or above there is another variant of takePicture() method. This method accepts 4 parameters. The first and second are same as the previous one. The third is the Camera.PictureCallback interface which is used to notify when completely scaled postview image is available. The forth one is the same as the third parameter in the first variant.
The data will be supplied to the calling application, the application can use this data for post processing or saving to a file.
In API version 8 or above, we can use the method Camera.setDisplayOrientation() method to set the orientation of the display. This is used by portrait applications to correctly display the live preview. In versions prior to 8, we can safely use the landscape mode to correctly display the preview.
The sample application displays the live preview. When the take picture button is clicked the image is saved to sdcard using time as the filename.
Happy Camera Coding
Download source code of this article.
In Android we use intent to start an activity, start a service, send broadcasts, etc. Intent is used for late runtime binding of applications. In Android intent represents the action to be performed. There are two primary information in an intent, they are action and data. Action attribute represents the action to be performed such as edit, view, dial, etc. The data attribute is the data to be operated on. Some of the common actions are ACTION_VIEW, ACTION_DIAL, ACTION_EDIT, ACTION_PICK, ACTION_SEND, ACTION_SEARCH, ACTION_CALL, etc. The following code snippets show some of the examples:
final String[] addressList = new String[] { toAddress };
final Intent email_intent = new Intent(android.content.Intent.ACTION_SEND);
email_intent.setType("message/rfc822");
email_intent.putExtra(android.content.Intent.EXTRA_EMAIL, addressList);
email_intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Sample mail");
email_intent.putExtra(android.content.Intent.EXTRA_TEXT, "Sample mail for testing purpose");
startActivity(Intent.createChooser(email_intent, "Send mail..."));
// needs permission android.permission.CALL_PHONE
Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel://123456789"));
startActivity(intent);
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH); intent.putExtra(SearchManager.QUERY, "Krishnaraj Varma"); startActivity(intent);
For a more detailed information about intent and intent action follow this link
There is another method to start an application using PackageManager class. This class has a method getLaunchIntentForPackage which will return the LAUNCHER intent of the specified package or null if not found. We can use this returned intent to start the application. The following code snippet starts the example application of this article:
PackageManager packageManager = getPackageManager();
String packageName = "com.varma.samples.applauncher";
try
{
Intent intent = packageManager.getLaunchIntentForPackage(packageName);
if(null != intent)
{
startActivity(intent);
}
}
catch (NameNotFoundException e)
{
e.printStackTrace();
}
catch (ActivityNotFoundException e)
{
e.printStackTrace();
}
To enumerate all the installed application packages, we can use getInstalledApplications method of the PackageManager class. This method returns a list of ApplicationInfo class. The ApplicationInfo class contains information regarding and application such as package name, label, icon, etc. This information comes from the AndroidManifest.xml file of the particular application.
The example application lists all the installed applications in a list view and when you click on an item, the application will be launched if a LAUNCHER intent is found.
Download source code of this article.
Recently in one of my project, time has to be displayed in different time zone. I used the class SimpleDateFormat class to convert and format the local time. This class has one convenient method setTimeZone, which converts the location time to the given time zone while formatting. The following code snippet converts the local time to another time zone:
SimpleDateFormat format = new SimpleDateFormat("EEE, MMM d, yyyy h:mm a");
format.setTimeZone(timezone);
format.format(new Date());
If you want to enumerate all the time zones, you can use the method getAvailableIDs of the TimeZone class. The method returns an array of string which contains all the timezone ids. The sample application lists all the time zones and the corresponding time.
Download source code of the article.
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.
Download source code of this article.
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, HashMapparams)
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
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!
Download source code of the article.
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.
Download source code of the article.
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.
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.
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, ArrayListparts, 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.
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.
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.
Download source code of the article.
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 :
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.
Download source code of the article.
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!
Copyright © 2012 · Genesis Framework by StudioPress · WordPress · Log in