Wednesday, 25 January 2012

Access webservice from Android device


I have seen many request on forum about web-service and android.Thought of sharing this sample tutorial with you about how to use web-services in android.Following this tutorial you can get an actual understanding about how to share data between mobile device and web-services.

Lets us take an example of login screen. Suppose user is sending request of login from mobile device to the server.Server will verify the request and will return response to the mobile device.Server can send response in either XML or through soap object.
This tutorial  will also explain about request – response model using xml.

Diagram:

Step 1. Create layout for login screen:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical"
  android:background="@drawable/background"> 
  <RelativeLayout
  android:layout_width="fill_parent"
  android:layout_height="wrap_content" 
  android:gravity="left"
  android:layout_marginTop="10dip">
  <TextView
      android:text="@string/LoginHeading"
      android:id="@+id/HeadingTextView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"     
      android:textColor="@android:color/white"
      android:textStyle="bold"
      android:layout_marginLeft="13dip">
</TextView>
  </RelativeLayout>  
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="10dip"
  android:layout_marginTop="10dip"
  android:background="@android:color/white"/>
<LinearLayout
  android:layout_width="fill_parent"
  android:layout_height="wrap_content" 
  android:orientation="horizontal"
  android:gravity="center"
  android:background="@android:color/white">
<TextView
      android:text="User ID "
      android:id="@+id/uNameTextView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:gravity="center_vertical"
      android:textColor="#000000">
</TextView>
<EditText
      android:id="@+id/userIDEditText"
      android:layout_height="wrap_content"
      android:layout_width="220dip"
      android:inputType="text"
      android:hint="USERID"
      android:layout_marginLeft="20dip">
</EditText>
</LinearLayout>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="5dip" 
  android:background="@android:color/white"/>
<LinearLayout
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  android:gravity="center"
  android:background="@android:color/white">
<TextView
      android:text="@string/uPass"
      android:id="@+id/uNPassTextView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:gravity="center_vertical"
      android:textColor="#000000">
</TextView>
<EditText
      android:id="@+id/passEditText"
      android:layout_height="wrap_content"
      android:layout_width="220dip"
      android:inputType="textPassword"
      android:hint="PASSWORD"
      android:layout_marginLeft="15dip">
</EditText>
</LinearLayout>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="5dip"
  android:background="@android:color/white"/>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  android:layout_marginTop="25dip"
  android:gravity="center">
   <Button
   android:layout_width="150dip"
   android:layout_height="wrap_content"
   android:text="Login"
   android:id="@+id/loginButton">
   </Button>
   <Button
   android:layout_width="150dip"
   android:layout_height="wrap_content"
   android:text="Cancel"
   android:id="@+id/cancelButton"
   ></Button>
  </LinearLayout>
</LinearLayout>



Step 2. Create login Activity:-
Send login request to the server using login activity. Java code for activity likes,


public class LoginActivity extends Activity{
      /*
       * Global variables
       */
      Button btnLogin =null;
      Button btnCancel =null;
      EditText uNameEditext =null;
      EditText passEditext =null;
      String iemiNumber = null;
      Thread connectionThread = null;
      LoginData loginData =null;
      private Handler loginHandler = null;
      private ProgressDialog progressDialog = null;
      private AlertDialog alert = null;
      ArrayList<ResponseData> responseData = null;
      //public SharedPreferences timeStamp = null; 
      @Override
      protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.loginscreen);
            uNameEditext =(EditText)findViewById(R.id.userIDEditText);
            passEditext =(EditText)findViewById(R.id.passEditText);
            //Handler for progress dialog
            loginHandler = new Handler() {
                  @Override
                  public void handleMessage(Message msg) {
                        // TODO Auto-generated method stub
                        super.handleMessage(msg);
                        if(progressDialog.isShowing()){
                              progressDialog.dismiss();
                        }
                        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(LoginActivity.this);
                        alertDialogBuilder.setTitle("Login");
                        alertDialogBuilder.setMessage("The username or password you entered is incorrect");
                        alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                              public void onClick(DialogInterface dialog, int which) {
                                    // TODO Auto-generated method stub
                                    //after testing
                                    passEditext.setText("");
                              }
                        });
                        alert = alertDialogBuilder.create();
                        alert.setCancelable(false);
                        alert.show();
                  }
            };
            btnLogin=(Button)findViewById(R.id.loginButton);
            btnLogin.setOnClickListener(new OnClickListener() {
                  public void onClick(View v) {                       
                        doLogin();
                  }
            });   
            btnCancel =(Button)findViewById(R.id.cancelButton);
            btnCancel.setOnClickListener(new OnClickListener() {             
                  public void onClick(View v) {
                        // TODO Auto-generated method stub
                        finish();
                  }
            });
      }
      private void doLogin(){
         mUserName = userNameEditText.getText().toString();
         mUserPswd = userPswdEditText.getText().toString();     
         if(mUserName.length() < 10){            
             Toast.makeText(LoginActivity.this, "Please check Mobile Number you have entered", Toast.LENGTH_SHORT).show();
             return;
         }
         if(mUserPswd.length() < 1){            
             Toast.makeText(LoginActivity.this, "Password field can't be left blank!", Toast.LENGTH_SHORT).show();
             return;
         }
        try{           
            progressDialog = ProgressDialog.show(this, "Connecting!", "Please wait . . .", true, true);
        }catch (Exception e) {
                       // TODO: handle exception
        }       
        if(mUserName.length() >= 10 && mUserPswd.length() > 0){        
                connectcionThread = new Thread(){                   
                    public void run(){                       
                        URL url;                       
                        try {
                            //User name and password is added to the URL
URL(loginUrl+"?name="+mUserName+"&password="+mUserPswd+"&deviceId="+mDeviceId.trim());                           
                            //Trying to connect with the server.
                            loginURLConnection = url.openConnection();
                           //Connection will be timed out in 5 seconds.
                            loginURLConnection.setConnectTimeout(9000);
                            //Getting XML data as input stream from server.
                           inputStream = loginURLConnection.getInputStream();
                            parseLoginResponseXML (new InputStreamReader(inputStream));                           
                            if(isSuccess){                               
                                progressDialog.dismiss();
                                openCategoryList();
                           }else{
                     progressDialog.dismiss();
                                myHandler.sendEmptyMessage(1);
                            }
                           inputStream.close();
                            loginURLConnection = null;
                        } catch (Exception e) {
                            loginResponseMessage = "Huh! Network Error, Can't connect to server, Please try again!";
                            myHandler.sendEmptyMessage(1);
                        }
                    }
                };
                connectcionThread.start();
            //}
        }
    }
      void parseLoginResponseXML(InputStreamReader inputStreamReader) {
            // TODO Auto-generated method stub
            if(inputStreamReader !=null){
                  //Implement parser logic here
            }
      }
}

In login activity ,I am adding entered username and password to the base login url.I have use URLConnection class to send request to server.We will get response in form of InputStream object.The response can be simple xml file.We can parse response xml file.If response is true then allow user to login into application.

Step 3.create manifest file:-
As we are using internet ,we need to mention internet permission in manifest file like,

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.webservice"
      android:versionCode="2"
      android:versionName="2.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".LoginActivity"
                  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-sdk android:minSdkVersion="3" />
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

Here I have tried to explain how to consume webservice in android.Hope it is helpful.
Happy androing!!!!!


Sunday, 22 January 2012

splash screen in android

Splash Screen :This is very important screen in mobile application development.Many client demands for splash screen in their application.This is first screen of the application from application flow start.So I have decided to write about splash screen. Following exercise explain about development of splash screen in android.

Steps 1.Create splash Activity :
public class SplashScreen extends Activity {
        long spalshTime =3000;
boolean isPaused =false;
boolean isSplashActive =true;

/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Draw the splash screen
        setContentView(R.layout.splash);
        //very simple timer thread
        Thread splashTimer = new Thread(){
        public void run(){
        try{
        //wait loop
        long ms=0;
        while ( isSplashActive  && ms <spalshTime) {
sleep(100);
//increase the timer if only we r running
if (!isPaused) {
ms +=100;
}
}
        //Advance to the next screen
        startActivity(new Intent("com.mainScreen"));
       
        }catch(Exception e){
       
        }finally{
        finish();                
       
        }
        }
       
        };
        splashTimer.start();
    }
    @Override
    protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    isPaused=true;
    }
    @Override
    protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    isPaused=false;
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
    // TODO Auto-generated method stub    
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
    isSplashActive =false;
        }    
    return true;
    }
}

Steps 2.Create Manifest file like,
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.SplashScreen"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SplashScreen"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
<activity android:name="MainScreen">
            <intent-filter>
                <action android:name="com.mainScreen" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="3" />
</manifest>

That's it.Enjoy androing...!!!




Wednesday, 18 January 2012

Broadcast Receiver-launch application on reboot of Device

In Previous post I have listed some broadcast action.In this post I will use one of broadcast action.
Sometimes we require to launch application whenever user restart device.We can achieve this using broadcast receiver.Through following application I have expalin how to launch application on device reboot.

Auto Start Application :

Required Steps :
1.Create SampleActivity which will be launcher activity of application.:


package com.androindu;
import android.app.Activity;
import android.os.Bundle;

public class SampleActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}


2.Create Broadcast Receiver.which will receive  reboot action of device:
   I have override onReceive() method, where I have started launcher activity of application.

package com.androindu;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class LaunchAppBroadcast extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent intent2 = new Intent(context, SampleActivity.class);
intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent2);

}

}



3.Edit Manifest file and register Broadcast receiver for "android.intent.action.BOOT_COMPLETED" action.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androindu"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".SampleActivity"
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="LaunchAppBroadcast"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>

</application>

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



Layout file main.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Launch on reboot of device"
/>
</LinearLayout>


Thus
     
Summary :
With this post we can get idea about  how to use Broadcast receiver.



Monday, 16 January 2012

Android Broadcast List

Broadcast receiver is very import component of Android.Here are some important Broadcast  action in android.

android.bluetooth.devicepicker.action.LAUNCH
android.intent.action.ACTION_POWER_CONNECTED
android.intent.action.AIRPLANE_MODE
android.intent.action.BATTERY_CHANGED
android.intent.action.BATTERY_LOW
android.intent.action.BATTERY_OKAY
android.intent.action.BOOT_COMPLETED
android.intent.action.CONFIGURATION_CHANGED
android.intent.action.DATA_SMS_RECEIVED
android.intent.action.DATE_CHANGED
android.intent.action.DEVICE_STORAGE_LOW
android.intent.action.DEVICE_STORAGE_OK
android.intent.action.PACKAGE_RESTARTED
android.intent.action.PHONE_STATE
android.intent.action.PROVIDER_CHANGED
android.intent.action.PROXY_CHANGE
android.intent.action.REBOOT
android.intent.action.SCREEN_OFF
android.intent.action.SCREEN_ON
android.intent.action.TIMEZONE_CHANGED
android.intent.action.TIME_SET
android.intent.action.TIME_TICK

We can get all the Broadcast action from platform folder of android SDK.