Search This Blog

Saturday, 29 October 2011

Gyroscope Based SmartPhone KeyLogging attack



iPhone typing


Two researchers from the University of California Davis, Hao Chen and Lian Cai, have successfully divined the keystrokes on an Android on-screen keyboard by measuring the wiggles, jiggles, and vibrations picked up by the device’s accelerometer. This is significant because the data from accelerometers is not thought of as a potential attack vector, and is thus freely available to any application on any smartphone or tablet.
Logging the keystrokes on a Windows or Mac desktop or laptop is incredibly easy: just install a piece of software (or get infected by a Trojan), configure where it should save or send the stolen keystrokes to, and that’s it. When it comes to smartphones, however, complex permission systems make this approach all but impossible — unless you use what’s known as a “side channel.” Strictly speaking, a side channel is an insecure source of information that helps a cracker break a cryptographic system. Broadly speaking, a side channel could be a blinking light on a router that mimics the binary data passing through it or the clackity-clack sounds of a physical keyboard. In other words, side channels are the characteristics of a system that have had their potential risks overlooked.
In this case, the two researchers use the Android’s orientation data a set of three angles that give the phone’s orientation in XYZ space — to work out where a user was pushing on the screen. Basically, every key has a unique pitch, roll and yaw fingerprint that can be identified (see below). The accuracy varies from phone to phone — the HTC Evo 4G updates its orientation data every 30ms as opposed to 110ms for the Motorola Droid — but overall, the researchers managed to reach 71.5% accuracy for a 10-button keyboard (number pad). The missing 28.5% is made up of keys that are close together; the software (called TouchLogger, incidentally) can generally derive the right column or row for every key, but sometimes it just doesn’t have enough data to resolve the exact key.
TouchLogger roll/pitch analysis of numbers
A full QWERTY keyboard is obviously a lot harder to infer keystrokes from than a 10-button number pad, of course — but this is just an early proof of concept, and accuracy of 70% is more than enough to destroy the confidentiality of any data that you might type into your phone, anyway. Furthermore, the research paper goes on to note that larger devices, such as tablets, should be easier to keylog — and that both gyroscopes and cameras could be used to increase the resolution and accuracy of TouchLogger.
Finally, it’s important to note that this side channel isn’t just a security hole in Android: accelerometer and gyroscope data is available through the DeviceOrientation API, which is implemented by all modern desktop (and laptop) browsers, and Android 3.0 and iOS 4.2. In other words, this current exploit would require you to install TouchLogger on your Android phone — but in theory, someone could take the work of Chen and Cai, implement it in JavaScript, and then use it to steal your login details and credit card info when you surf the web.

This is quite interesting post seemed to me so I dont think so you have to worry about this hack as its not so accurate but you have to be aware of that thing  :)  Readers if you like this post do comment !!!!!!!

Thursday, 27 October 2011

Quick Review About Latest Android 4.0 Ice Cream Sandwitch !!!!


ics-lg
While hardware junkies like myself may have spent the past few weeks drooling over the Galaxy Nexus, the onstage demo of Android 4.0 Ice Cream Sandwich proves that the software powering the device is just as impressive (if not a little moreso).
Our hands-on with the Galaxy Nexus and Ice Cream Sandwich will be coming shortly, but here’s a quick rundown of what Android 4.0 will be bringing to the table come November.
UPDATE: Our in-depth hands-on is live! Hit the link to see Ice Cream Sandwich’s features in action.
  • Roboto: Goodbye Droid Sans, a new typeface called Roboto is here to rule the roost.
  • Landscape Controls: We knew that the Galaxy Nexus opted to move the classic Android buttons onto the screen, but they smartly disappear when viewing video or in widescreen mode.
  • Flexible Widgets: Ice Cream Sandwich’s stock widgets are resizable and more robust than previous versions. They also now occupy their own separate space in the app drawer.
  • Folders: Dragging apps and contacts on top of each other create re-arrangeable folders a la iOS.
  • Favorites Tray: Users can stow their favorite apps, links, and folders into a new Favorites tray for quick and easy access.
  • Taking Screenshots: This one has been a long time coming. Hold down the power button and the volume down button to snap a screenshot.
  • Notifications: Hefty revamp here, as the contents are much more customizable. Music controls have been integrated, and notifications are also easily dismissed with a quick swipe left or right.
  • Improved Copy & Paste: Copying and pasting content is made much easier, as you can now move around entire blocks of text. Very useful.
  • Face Unlock: One of the most ambitious is Ice Cream Sandwich’s new Face Unlock feature, which allows users to unlock their handsets just by looking into the front-facing camera.
  • Enhanced Talk-to-Text: Voice input seems much smarter this time around, as it’s more accurate, requires less time, and even accounts for pauses.
  • Browser: The stock browser now sports tabs, and it maxes out at 16. Web pages can now also be saved offline for later perusal, and users can directly request the desktop version of a site.
  • Gmail: Gmail now supports two-line previews, and sports a new context-sensitive action bar at the bottom of the screen. Gesture support allows you to swipe left and right between emails.
  • People App: A new spin on the contact list. The phone’s owner has their own profile, and people’s contact details are sourced from Google+, Facebook, Twitter, etc. Users can define favorite contacts, and individual people can be placed on the homescreen or in folders for quick access.
  • Calendar: Features a redesigned UI and includes pinch-to-zoom to vary the level of detail on a calendar page.
  • Data Usage: Users can now drill down into their data usage over a certain period of time, including the ability to see which apps are the biggest data hogs and the ability to limit data usage to a certain threshold.
  • Camera: There’s a lot to love here. It features image stabilization, improved autofocus, and integration with other apps for sending photos or instant upload to Google+. Oh, and who could forget built-in face detection, panorama and time lapse modes, and on-the-fly photo retouching and enhancements.
  • Android Beam: An secure NFC-powered sharing platform that lets users share nearly any kind of content, save for applications (in that case, a link to the Market is sent instead)
Hey Readers If you wanna owe a phone in android 4.0 Samsung Galaxy Nexus is the Best Later On I will post about this android Phone also !!!!!!!!

How to deploy Javascript In android applications

Android provides a very capable UI component called WebView that can be used to display HTML content. The WebView class is standard on Android and does not require anything special to use. The entry point in the 06_HtmlOnAndroid project is the class HtmlOnAndroid and shows how little code is required to get this type of application set up. Listing 6–1 shows the onCreate method of HtmlOnAndroid.
Listing 6–1. HtmlOnAndroid.onCreate()
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
webView = new WebView(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/index.html");
webView.addJavascriptInterface(new JavaScriptInterface(), "android");
webView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
setContentView(webView);
}
In Listing 6–1 we see that a new WebView is created and set as the contentView. This makes the WebView the only component visible in the application, allowing us to have a full screen JavaScript/HTML application. After the WebView is created, a number ofmethods are called on the WebView. These methods enable functionality that is required
by our application.
The call to webView.getSettings().setJavaScriptEnabled(true) is critical for our application because it allows the JavaScript to run, which defines the actual game. By default, JavaScript is disabled on new WebViews, perhaps for performance or security reasons.
In order to set the web page displayed by the WebView a call to loadUrl is made. As can be seen in Listing 6–1 we are setting the starting URL to file:///android_asset/index.html. The index.html file is located in the assets directory of the project. By default, any files stored in the assets directory are available
on the device at the path file:///android_asset/. Without modification, an application with a single WebView has a lot of extra stuff on the screen. We want to get rid of as much of this clutter as possible to make room for the application and to make it look more native. See Figure 6–2, which shows the application before and after our cosmetic changes are made.
Figure 6–

Fig:-6.2
You can see on the left that there is a header to the WebView and scroll bars on the right. The method call setScrollBarStyle is used to remove the default scroll bars of the WebView. Since this is a simple, full-screen application, we can remove the scroll bars to increase the viewing area and prevent some user confusion. To further increase the amount of screen area in the AndroidManifest.xml file, we set the theme of the
application to @android:style/Theme.NoTitleBar as can be seen in Listing 6–2.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.ljordan.anrdoid.chapter06"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".HtmlOnAndroid"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</manifest>
Listing 6–2 shows the AndroidManifest.xml file for this project. Besides setting our theme for the application, we also define the permissions required by this application. It is important to note that the permissions of an application apply to an application that lives in a WebView as well. For example, if your application wants to make a call to an external server through JavaScript, you must include the INTERNET permission. This is
also true for the HTML5 location API, you must set the ACCESS_GPS and probably the ACCESS_FINE_LOCATION for this feature to work in your web view the way you want.

Tuesday, 25 October 2011

How to deal With Android Database

hey friends many of you have problem in working with the database in android application development, as many applications need this. So I have posted some database tutorial which will help you further to deal with the android database. Actually android have the database named SQLite database. So how to deal with that the post follows:-

assume that we have one database PERSONALDB, and have one table BIODATA. The structure of BIODATA is:

_id integer
code string
name string
gender string

_id is for key increment,
code, name, and gender is for description of person.

When program called in the first time, we have to make sure that the database and table opened if it is exist. if not, than we have to create the database and tabel. As an example from Android notepad sample, here the class PersonDbHelper for manipulating table Biodata.

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class PersonDbHelper {
    class Row extends Object {
        public long _Id;
        public String code;
        public String name;
        public String gender;
    }

    private static final String DATABASE_CREATE =
        "create table BIODATA(_id integer primary key autoincrement, "
            + "code text not null,"
            + "name text not null"
            +");";

    private static final String DATABASE_NAME = "PERSONALDB";

    private static final String DATABASE_TABLE = "BIODATA";

    private static final int DATABASE_VERSION = 1;

    private SQLiteDatabase db;

    public PersonDbHelper(Context ctx) {
        try {
            db = ctx.openDatabase(DATABASE_NAME, null);
        } catch (FileNotFoundException e) {
            try {
                db =
                    ctx.createDatabase(DATABASE_NAME, DATABASE_VERSION, 0,
                        null);
                db.execSQL(DATABASE_CREATE);
            } catch (FileNotFoundException e1) {
                db = null;
            }
        }
    }

    public void close() {
        db.close();
    }

    public void createRow(String code, String name) {
        ContentValues initialValues = new ContentValues();
        initialValues.put("code", code);
        initialValues.put("name", name);
        db.insert(DATABASE_TABLE, null, initialValues);
    }

    public void deleteRow(long rowId) {
        db.delete(DATABASE_TABLE, "_id=" + rowId, null);
    }

    public List<Row> fetchAllRows() {
        ArrayList<Row> ret = new ArrayList<Row>();
        try {
            Cursor c =
                db.query(DATABASE_TABLE, new String[] {
                    "_id", "code", "name"}, null, null, null, null, null);
            int numRows = c.count();
            c.first();
            for (int i = 0; i < numRows; ++i) {
                Row row = new Row();
                row._Id = c.getLong(0);
                row.code = c.getString(1);
                row.name = c.getString(2);
                ret.add(row);
                c.next();
            }
        } catch (SQLException e) {
            Log.e("Exception on query", e.toString());
        }
        return ret;
    }

    public Row fetchRow(long rowId) {
        Row row = new Row();
        Cursor c =
            db.query(true, DATABASE_TABLE, new String[] {
                "_id", "code", "name"}, "_id=" + rowId, null, null,
                null, null);
        if (c.count() > 0) {
            c.first();
            row._Id = c.getLong(0);
            row.code = c.getString(1);
            row.name = c.getString(2);
            return row;
        } else {
            row.rowId = -1;
            row.code = row.name= null;
        }
        return row;
    }

    public void updateRow(long rowId, String code, String name) {
        ContentValues args = new ContentValues();
        args.put("code", code);
        args.put("name", name);
        db.update(DATABASE_TABLE, args, "_id=" + rowId, null);
    }
    public Cursor GetAllRows() {
        try {
            return db.query(DATABASE_TABLE, new String[] {
                    "_id", "code", "name"}, null, null, null, null, null);
        } catch (SQLException e) {
            Log.e("Exception on query", e.toString());
            return null;
        }
    }
}

in Method onCreate Activity you just put single command below to initialize the database :
...
Db = new PersonDbHelper(this);
...

it will try opening PersonalDB first, if it is not exist, than it will create the database. in this PersonDbHelper class, you have method for inserting, deleting, updating, querying table.

Ok, have a nice try

Readers are fully invited to alert me about any mistake in the above code hope the above code helps you to understand the concepts of database !!!!!!!!!!

AND WISH YOU A VERY HAPPY DIWALI

Saturday, 22 October 2011

How To Root Samsung Galaxy S2!!!!


Warning: Perform at your own risk, rooting could possibly brick your device and void your warranty.
EDIT: Scroll to the bottom for initial instructions, make sure you have the correct kernels/firmwares to begin rooting!
What you need:
  • A Samsung Galaxy S2
  • A Windows PC
  • A USB DATACABLE
  • Odin Downloader (Download Here)
  • Download the attached XWKDD, but do NOT extract the .tar file (Download Here)
  • Download and extract SuperOneClick (Download Here)
  • Put device in USB debugging mode: Settings -> Applications -> Development -> USB debugging
Step One
Reboot your device into download mode Turn the device off, then power it on again by pressing and holding VolumeDown + Home + Power simultaneously.
Step Two
Start ODIN Downloader
samsung-galaxy-s2-rooted-odin
Step Three
Connect the device to your computer using USB.
Wait a few seconds, the ODIN screen should show you that a device is now connected.
tick the checkboxes next to “Auto reboot” and “F. Reset Time” and leave everything else as is.
Press the “PDA” button, and select the “XWKDD_insecure.tar” file.
Press “Start”. ODIN you should now be flashing the kernel, and the device should reboot.
DO Not Remove the cable and Wait until the device is rebooted.
samsung-galaxy-s2-rooted-odin2
Step Four
Once the device is rooted and while still connected via USB
Start SuperOneClick, and press ROOT
Reboot the device
That’s all folks! You should have successfully rooted your Samsung Galaxy S2.

Working with broadcast recievers

Many android learners have the problem in working with the android broadcast recievers so here is the full fledged application of the android using broadcast recivers as follows:-

To get started, first launch Eclipse and create a new Android project. Name the project as shown in Figure 1.


Figure 1 Creating a new Android project using Eclipse
Android uses a permission-based policy where all the permissions needed by an application need to be specified in the AndroidManifest.xml file. By doing so, when the application is installed it will be clear to the user what specific access permissions are required by the application. For example, as sending SMS messages will potentially incur additional cost on the user's end, indicating the SMS permissions in the AndroidManifest.xml file will let the user decide whether to allow the application to install or not.
In the AndroidManifest.xml file, add the two permissions - SEND_SMS and RECEIVE_SMS:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="net.learn2develop.SMSMessaging"
      android:versionCode="1"
      android:versionName="1.0.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SMS"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>
</manifest>
In the main.xml file located in the res/layout folder, add the following code so that the user can enter a phone number as well as a message to send:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="Enter the phone number of recipient"
        />     
    <EditText 
        android:id="@+id/txtPhoneNo"  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"        
        />
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"         
        android:text="Message"
        />     
    <EditText 
        android:id="@+id/txtMessage"  
        android:layout_width="fill_parent" 
        android:layout_height="150px"
        android:gravity="top"         
        />          
    <Button 
        android:id="@+id/btnSendSMS"  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:text="Send SMS"
        />    
</LinearLayout>
The above code creates the UI shown in Figure 2.

Figure 2 Creating the UI for sending SMS messages
Next, in the SMS activity, we wire up the Button view so that when the user clicks on it, we will check to see that the phone number of the recipient and the message is entered before we send the message using the sendSMS() function, which we will define shortly:
package net.learn2develop.SMSMessaging;
 
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
public class SMS extends Activity 
{
    Button btnSendSMS;
    EditText txtPhoneNo;
    EditText txtMessage;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
 
        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
        txtMessage = (EditText) findViewById(R.id.txtMessage);
 
        btnSendSMS.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {                
                String phoneNo = txtPhoneNo.getText().toString();
                String message = txtMessage.getText().toString();                 
                if (phoneNo.length()>0 && message.length()>0)                
                    sendSMS(phoneNo, message);                
                else
                    Toast.makeText(getBaseContext(), 
                        "Please enter both phone number and message.", 
                        Toast.LENGTH_SHORT).show();
            }
        });        
    }    
}
The sendSMS() function is defined as follows:
public class SMS extends Activity 
{
    //...
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        //...
    }
 
    //---sends an SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {        
        PendingIntent pi = PendingIntent.getActivity(this, 0,
            new Intent(this, SMS.class), 0);                
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, pi, null);        
    }    
}
To send an SMS message, you use the SmsManager class. Unlike other classes, you do not directly instantiate this class; instead you will call the getDefault() static method to obtain an SmsManager object. The sendTextMessage() method sends the SMS message with a PendingIntent. The PendingIntent object is used to identify a target to invoke at a later time. For example, after sending the message, you can use a PendingIntent object to display another activity. In this case, the PendingIntent object (pi) is simply pointing to the same activity (SMS.java), so when the SMS is sent, nothing will happen.
If you need to monitor the status of the SMS message sending process, you can actually use two PendingIntent objects together with two BroadcastReceiver objects, like this:
//---sends an SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {        
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";
 
        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);
 
        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);
 
        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off", 
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));
 
        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;                        
                }
            }
        }, new IntentFilter(DELIVERED));        
 
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);        
    }
The above code uses a PendingIntent object (sentPI) to monitor the sending process. When an SMS message is sent, the first BroadcastReceiver's onReceive event will fire. This is where you check the status of the sending process. The second PendingIntent object (deliveredPI) monitors the delivery process. The second BroadcastReceiver's onReceive event will fire when an SMS is successfully delivered.
You can now test the application by pressing F11 in Eclipse. To send an SMS message from one emulator instance to another, simply launch another instance of the Android emulator by going to the Tools folder of the SDK and running Emulator.exe.

Figure 3 Sending an SMS message
Figure 3 shows how you can send an SMS message from one emulator to another; simply use the target emulator's port number (shown in the top left corner of the window) as its phone number. When an SMS is sent successfully, it will display a "SMS sent" message. When it is successfully delivered, it will display a "SMS delivered" message. Note that for testing using the emulator, when an SMS is successfully delivered, the "SMS delivered" message does not appear; this only works for real devices.
Figure 4 shows the SMS message received on the recipient emulator. The message first appeared in the notification bar (top of the screen). Dragging down the notification bar reveals the message received. To view the entire message, click on the message.

Figure 4 The SMS message received by the Android emulator
If you do not want to go through all the trouble of sending the SMS message yourself, you can use an Intent object to help you send an SMS message. The following code shows how you can invoke the built-in SMS application to help you send an SMS message:
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
        sendIntent.putExtra("sms_body", "Content of the SMS goes here..."); 
        sendIntent.setType("vnd.android-dir/mms-sms");
        startActivity(sendIntent);
Figure 5 shows the built-in SMS application invoked to send the SMS message.

Figure 5 Invoking the built-in SMS application

Receiving SMS Messages

Besides programmatically sending SMS messages, you can also intercept incoming SMS messages using a BroadcastReceiver object.
To see how to receive SMS messages from within your Android application, in the AndroidManifest.xml file add the <receiver> element so that incoming SMS messages can be intercepted by the SmsReceiver class:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="net.learn2develop.SMSMessaging"
      android:versionCode="1"
      android:versionName="1.0.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SMS"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>        
 
        <receiver android:name=".SmsReceiver"> 
            <intent-filter> 
                <action android:name=
                    "android.provider.Telephony.SMS_RECEIVED" /> 
            </intent-filter> 
        </receiver>
 
    </application>
    <uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>
</manifest>
Add a new class file to your project and name it as SmsReceiver.java (see Figure 6).

Figure 6Adding the SmsReceiver.java file to the project
In the SmsReceiver class, extend the BroadcastReceiver class and override the onReceive() method:
package net.learn2develop.SMSMessaging;
 
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
 
public class SmsReceiver extends BroadcastReceiver
{
 @Override
 public void onReceive(Context context, Intent intent) 
       { 
 }
}
When SMS messages are received, the onCreate() method will be invoked. The SMS message is contained and attached to the Intent object (intent - the second parameter in the onReceive() method) via a Bundle object. The messages are stored in an Object array in the PDU format. To extract each message, you use the static createFromPdu() method from the SmsMessage class. The SMS message is then displayed using the Toast class:
package net.learn2develop.SMSMessaging;
 
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;
 
public class SmsReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        String str = "";            
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];            
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
                str += "SMS from " + msgs[i].getOriginatingAddress();                     
                str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "\n";        
            }
            //---display the new SMS message---
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        }                         
    }
}
 IF You want the whole source code you can download it from the given link Source Code
Guys Plz give the feedback if you found any of the mistake in the above blog....
 

Friday, 21 October 2011

Android Gallery Control

In Android the Gallery control is a selection control that displays items in a horizontal gallery. the items in the gallery appear beside each other. they can appear separated by a pre-defined space.

remember that there is a sample demo application for the gallery to download at the end of the post

we can use the gallery to display String items using a simple ArrayAdapter.
so let's see how to create a gallery that displays the word "Hello" in several languages:

the layout:
01<?xml version="1.0" encoding="utf-8"?>
02<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03    android:orientation="vertical"
04    android:layout_width="fill_parent"
05    android:layout_height="fill_parent"
06    >
07<TextView 
08    android:layout_width="fill_parent"
09    android:layout_height="wrap_content"
10    android:text="Gallery Demo"
11    />
12    <Gallery
13    android:id="@+id/gallery"
14    android:layout_width="fill_parent"
15    android:layout_height="wrap_content"
16    android:gravity="center_horizontal"
17    android:spacing="100px"
18     
19    />
20</LinearLayout>

and in the OnCreate method
01@Override
02    public void onCreate(Bundle savedInstanceState) {
03        super.onCreate(savedInstanceState);
04        setContentView(R.layout.main);
05        gallery=(Gallery)findViewById(R.id.gallery);
06        //String array holding the values
07        String [] text=new String[]{"Hello","Hi","Alloha","Bonjour","Hallo","¡Hola"};
08        //Array adapter to display our values in the gallery control
09        ArrayAdapter<string> arr=new ArrayAdapter<string>(this, android.R.layout.simple_gallery_item, text);
10gallery.setAdapter(arr);
11}
12</string></string>

the gallery will be like this

we can increse the spacing between the items by increasing the value of android:spacing property.

we can display a scroll bar to indicate the position of the current selected item in the gallery like this:
01<Gallery
02    android:id="@+id/gallery"
03    android:layout_width="fill_parent"
04    android:layout_height="wrap_content"
05    android:gravity="center_horizontal"
06    android:spacing="100px"
07    android:scrollbars="horizontal"
08    android:scrollbarFadeDuration="0"
09    android:scrollX="100px"
10    />



setting the android:scrollbarFadeDuration="0" makes the scroll bar always visible.

The android:scrollX property defines the initial scroll offset of the scroll bar which is the initial distance that the gallery is scrolled for.

Handling Gallery Events
since the gallery is a selction Control (a adapter view) so it can register a OnItemSelectedListener to handle the selection of items within the gallery.

01final String [] text=new String[]{"Hello","Hi","Alloha","Bonjour","Hallo","¡Hola"};
02gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
03 
04   @Override
05   public void onItemSelected(AdapterView parent, View view,
06     int position, long id) {
07    // TODO Auto-generated method stub
08    TextView txt=(TextView)findViewById(R.id.txt);
09    txt.setText(text[position].toString());
10   }
11 
12   @Override
13   public void onNothingSelected(AdapterView parent) {
14    // TODO Auto-generated method stub
15     
16   }
17  });


now the final step is to add two navigation buttons: Next and Previous to navigate throught the items in the gallery.
the layout is gonna be like this:
01<?xml version="1.0" encoding="utf-8"?>
02<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03    android:orientation="vertical"
04    android:layout_width="fill_parent"
05    android:layout_height="fill_parent"
06    >
07<TextView 
08    android:layout_width="fill_parent"
09    android:layout_height="wrap_content"
10    android:text="Gallery Demo"
11    android:id="@+id/txt"
12    />
13    <Gallery
14    android:id="@+id/gallery"
15    android:layout_width="fill_parent"
16    android:layout_height="wrap_content"
17    android:gravity="center_horizontal"
18    android:spacing="100px"
19    android:scrollbars="horizontal"
20    android:scrollbarFadeDuration="0"
21    android:scrollX="100px"
22    />
23    <LinearLayout
24     android:layout_width="fill_parent"
25     android:layout_height="wrap_content"
26     android:orientation="horizontal"
27     android:layout_marginTop="5px"
28     >   
29     <Button
30     android:text="Previous"
31     android:layout_width="wrap_content"
32     android:layout_height="wrap_content"
33     android:id="@+id/btnPrev"
34     android:onClick="onClick"
35      />
36      <Button
37     android:text="Next"
38     android:layout_width="wrap_content"
39     android:layout_height="wrap_content"
40     android:id="@+id/btnNext"
41     android:onClick="onClick"
42      />
43 
44    </LinearLayout>
45     
46</LinearLayout>

now in order to keep track of the index of the currently selected item we need to define two variables
1//Variable to store the number of items in the gallery
2 int ItemsInGallery=0;
3 int CurrentIndex=0;

and the navigation buttons click handlers:
01@Override
02 public void onClick(View v) {
03  // TODO Auto-generated method stub
04  switch(v.getId())
05  {
06  case R.id.btnNext:
07   //Increase the index
08   CurrentIndex++;
09   //if reached the end of the gallery, then start from the first item
10   if(CurrentIndex>ItemsInGallery-1)
11    CurrentIndex=0;
12   gallery.setSelection(CurrentIndex,true);
13   txt.setText(String.valueOf(CurrentIndex));
14   break;
15  case R.id.btnPrev:
16   //Decrease the index
17   CurrentIndex=CurrentIndex-1;
18   //If reached the first item, then return to the last item in the gallery
19   if(CurrentIndex<0)
20    CurrentIndex=ItemsInGallery-1;
21   gallery.setSelection(CurrentIndex,true);
22   txt.setText(String.valueOf(CurrentIndex));
23   break;
24  }
25 }
you can download a sample program from here