Monday 27 August 2012

Android Splash Screen Example

Android Splash Screen Example
Hello Friends,

Have you searching for Splash screen demo example in android ??
Today , I am sharing the full running code of splash screen in android.

1. SplashScreen.java

package com.mukesh.tutorials.splash;

import com.pxr.tutorials.splash.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;

public class SplashScreen extends Activity {
        
        protected int _splashTime = 5000; 
        
        private Thread splashTread;
        
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.splash);
            
            
            final SplashScreen sPlashScreen = this; 
            
            // thread for displaying the SplashScreen
            splashTread = new Thread() {
                @Override
                public void run() {
                    try {                       
                        synchronized(this){
                                wait(_splashTime);
                        }
                        
                    } catch(InterruptedException e) {} 
                    finally {
                        finish();
                        
                        Intent i = new Intent();
                        i.setClass(sPlashScreen, Main.class);
                                startActivity(i);
                        
                        //stop();
                    }
                }
            };
            
            splashTread.start();
        }
        //for fading effect
        /*@Override
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                synchronized(splashTread){
                        splashTread.notifyAll();
                }
            }
            return true;
        }*/
        
}


2.AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

      package="com.pxr.tutorials.splash"

      android:versionCode="1"

      android:versionName="1.0">

    <uses-sdk android:minSdkVersion="4" />



    <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="com.mukesh.tutorials.splash.Main" />

    </application>

</manifest>


3.Main.Java


package com.mukesh.tutorials.splash;

import com.pxr.tutorials.splash.R;

import android.app.Activity;
import android.os.Bundle;

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




Download Source Code: 
SplashDemo


Hope this will helps anyone....
Enjoy :)

Friday 3 August 2012

Show Custom Alert Box| Dialogue Box in Phone Gap Application

Phonegap alert box

Hello Friends,


Here , I am sharing my code in which we show custom alert box in
Phone Gap Application ,Same as Android and Iphone.

In My Html code i am calling logout() method on button(Logout) click Which show
A confirmation alert box.


The Java Script code which i am using is:

<script type="text/javascript">
function  logout() {
    showConfirm();
}

function showConfirm() {
    navigator.notification.confirm(
        'Are you sure?',  // message
        onConfirm,        // callback to invoke with index of button pressed
        'Logout',         // title
        'Ok,Cancel'       // buttonLabels
    );
}

//process the confirmation dialog result
function onConfirm(button) {
    if(button==1){
        //your code
    }else {
      //your code
    }
}
</script>

Hope , this will Helps any one.

Network reachability code in Phone gap-Android

Phone Gap network check


Hello Friends,

Have you searching for how to check network connection in your
Phone Gap  Application ?

Here , I am sharing my network reachability code in phone gap
application.

Note:
        In some of the devices if you are trying to connect your app using GPRS.
In this case the connection type will be  'Unknown connection' so in my code i am
only checking following condition to show confirm dialogue.


if(networkStatusType == 'undefined' || networkStatusType == 'No network    
                     connection'){
         showConfirm();
}




Code:
Index.html

  <!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, height=device-height" />
  <title>Login Form</title>
  <link rel="stylesheet" href="css/style.css">
  

<link rel="stylesheet" href="css/jquery.mobile-1.0b3.min.css" />


<script type="text/javascript" src="js/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.0b3.min.js"></script>

<script type="text/javascript" src="js/phonegap-1.0.0.js"></script>
<script type="text/javascript" src="js/SQLStore.js"></script>
<script type="text/javascript" src="js/NWReachability.js"></script>
<script type="text/javascript">
var DEBUG_ANDROID_THEME=true;
$(document).ready(function() {
//initDB();
});

</script
</head>

<body>
<div data-dom-cache="true" data-role="page" id="page">
 <div data-role="header" data-position="inline" data-theme="b">
<h1>LOGIN</h1>
         </div>

  <div class="container">
    <section class="login">
      <!--  <h1>Login to VEO App</h1>  -->
      <form>
        <p>
          <input type="text" name="txtName" id="loginName" value="" placeholder="Username">        
        </p>
        <p>
          <input type="password" name="txtPassword" id="password" value="" 
          placeholder="Password" > 
        </p>
        <p class="submit" style="width: 100px;">
           <input type="button" name="commit" value="Login" onclick="loginvalidation();">
        </p>
      </form>
    </section>    
  </div>
</div>
  
</body>
</html>



In my NetworkReachability.js


/*function for login validation */


function loginvalidation() {
        var msg="";
        //msg="Wrong Input";
        var ck_name = /^[A-Za-z0-9_.]{3,20}$/;
        var name_int = /[0-9]/;
        var ck_password = /^[A-Za-z0-9!@#$%^&*()_]{5,20}$/;
        var userName =$("#loginName").val();
        var password =$("#password").val();
        if(userName == "" || password == ""){
        msg="Please fill User Name and Password ";
            showErrorToast(msg);
        $("#loginName").focus();
        }
        else {
        var pos=userName.search(name_int);
        if(pos==0){
        msg="Invalid User Name "
        showErrorToast(msg);
        $("#loginName").focus();
                $("#loginName").val("");
        }
        else if(!ck_name.test(userName)){
        msg="Invalid User Name "
                $("#loginName").focus();
                $("#loginName").val("");
                showErrorToast(msg);
                }
        else if(!ck_password.test(password))
        {
        msg="Invalid Password "
                $("#password").focus();
                $("#password").val("");
                showErrorToast(msg);
               
        }
        else {
        var networkStatusType = checkConnection();
        alert(networkStatusType);
       
        if(networkStatusType == 'undefined' || networkStatusType == 'No network    
                     connection'){
        showConfirm();
        }
        else{
        //Your own call
        }
        
        
        }
        
     }
  }





//check network connection 
function checkConnection() {
    var networkState = navigator.network.connection.type;

    var states = {};
    states[Connection.UNKNOWN]  = 'Unknown connection';
    states[Connection.ETHERNET] = 'Ethernet connection';
    states[Connection.WIFI]     = 'WiFi connection';
    states[Connection.CELL_2G]  = 'Cell 2G connection';
    states[Connection.CELL_3G]  = 'Cell 3G connection';
    states[Connection.CELL_4G]  = 'Cell 4G connection';
    states[Connection.NONE]     = 'No network connection';

    //alert('Connection type: ' + states[networkState]);
    var  networkStatus=states[networkState];
    return networkStatus;

}

function showConfirm() {
    navigator.notification.confirm(
        'No network connection'// message
        onConfirm,              // callback to invoke with index of button pressed
        'Please Check Network Setting.',            // title
        'Ok,Cancel'          // buttonLabels
    );
}

//process the confirmation dialog result
function onConfirm(button) {
    if(button==1){
     //your code
    }else {
       //your code
    }
}


I think this will help you... 
Enjoy Coding :)

Please Comment if you have any query.

Monday 30 July 2012

Google map example in android

Android Google map and Google api key example
Hello Friends ,Here I am sharing the full tutorial of How to implements Google map
in your android application:

Step 1: Creating Key Store 


Open the command prompt and follow the steps

C:\Mukesh\Android-Sdk\tools>keytool -genkey -v -keystore projectkey.keystore -alias aliasname -keyalg RSA -keysize 2048 -validity 15000
Enter keystore password: ------------
What is your first and last name?
[Unknown]: ------------
What is the name of your 
organizational unit?
[Unknown]: ------------
What is the name of your organization?
[Unknown]: ------------
What is the name of your City or Locality?
[Unknown]: ------------
What is the name of your State or Province?
[Unknown]: ------------
What is the two-letter country code for this unit?
[Unknown]: ------------

Is CN=mukesh, OU=zss, O=zss, L=delhi, ST=delhi, C=dl correct?

[no]: yes

Generating 2,048 bit RSA key pair and self-signed certificate 

(SHA1withRSA) with a validity of 15,000 days

        for: CN=CN, OU=OU, O=O, L=L, ST=ST, C=C

Enter key password for <aliasname>

        (RETURN if same as keystore password): ------------

Re-enter new password: ------------

[Storing projectkey.keystore]
C:\Mukesh\Android-Sdk\tools>keytool -list -alias aliasname -keystore projectkey.keystore
Enter keystore password:
aliasname, Jul 22, 2012, PrivateKeyEntry,
Certificate fingerprint (MD5):
A2:69:37:23:5B:27:68:B0:B7:5E:C1:61:08:04:F8:C0



Step 2: Obtaining Google API key for Google Map:
                                            Using Certificate fingerprint(MD5) you can get your get your google 
API Key from this link:
                         http://code.google.com/android/maps-api-signup.html 


Finally you get this:
Your key is: 
0NmasjBqpEvFTVP4IugZrbssdsIKnwPH2qSpd8g

This key is good for all apps signed with your certificate whose fingerprint is:

A2:69:37:23:5B:27:68:B0:B7:5E:C1:61:08:04:F8:C0

Here is an example xml layout to get you started on your way to mapping glory:
              <com.google.android.maps.MapView
                 android:layout_width="fill_parent"
                 android:layout_height="fill_parent"
                 android:apiKey="0NmasjBqpEvFTVP4IugZrbssdsIKnwPH2qSpd8g"
                 />


Use the above xml code and Enjoy...:)
Please Comment me or Ask if you face any problem.

Thursday 26 July 2012

Phonegap get Latitude and Longitude / PhoneGap Geolocation Sample Application

Hello Friends,

With the help Phone Gap Api, You can easily get current position using GPS .
To start playing with it, Please have a look at this simple function or Code:

// Check if geolocation is available
if(navigator.geolocation) {
    // This is the specific PhoneGap API call
    navigator.geolocation.getCurrentPosition(function(p) {
        // p is the object returned
        alert('Latitude '+p.coords.latitude);
        alert('Longitude '+p.coords.longitude);
    }, function(error){
        alert("Failed to get GPS location");
    });
} else {
    alert("Failed to get GPS working");
}


Also Please add permission in your plugin.xml file
1.<plugin name="Geolocation" value="com.phonegap.GeoBroker"/>
2. <plugin name="Notification" value="com.phonegap.Notification"/>



Enjoy Coding.... :)
Please, write questions in comments.
Don’t forget share this post....... :) 

Monday 23 July 2012

Android Send and Receive Sms


Hello Friends ,
Today ,I am sharing a sample application in which we can send and received
the sms.

1. SmsActivity.java



package com.app;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.telephony.gsm.SmsMessage;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SmsActivity 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);
        
        /*
        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);
        */
                
        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();
            }
        });        
    }
    
    //---sends a SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {      
     /*
        PendingIntent pi = PendingIntent.getActivity(this, 0,
                new Intent(this, test.class), 0);                
            SmsManager sms = SmsManager.getDefault();
            sms.sendTextMessage(phoneNumber, null, message, pi, null);        
        */
     
     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);               
    }    
}

2.SmsReceiver.Java



package com.app;



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();

        }                   

 }

}


Download The Source Code:
Sms.zip



Sunday 22 July 2012

Creating keystore and google api key for google maps-Android



Open the command prompt and follow the steps

C:\Mukesh\Android-Sdk\tools>keytool -genkey -v -keystore projectkey.keystore -alias aliasname -keyalg RSA -keysize 2048 -validity 15000
Enter keystore password: ------------
What is your first and last name?
[Unknown]: ------------
What is the name of your 
organizational unit?
[Unknown]: ------------
What is the name of your organization?
[Unknown]: ------------
What is the name of your City or Locality?
[Unknown]: ------------
What is the name of your State or Province?
[Unknown]: ------------
What is the two-letter country code for this unit?
[Unknown]: ------------

Is CN=mukesh, OU=zss, O=zss, L=delhi, ST=delhi, C=dl correct?

[no]: yes

Generating 2,048 bit RSA key pair and self-signed certificate 

(SHA1withRSA) with a validity of 15,000 days

        for: CN=CN, OU=OU, O=O, L=L, ST=ST, C=C

Enter key password for <aliasname>

        (RETURN if same as keystore password): ------------

Re-enter new password: ------------

[Storing projectkey.keystore]
C:\Mukesh\Android-Sdk\tools>keytool -list -alias aliasname -keystore projectkey.keystore
Enter keystore password:
aliasname, Jul 22, 2012, PrivateKeyEntry,
Certificate fingerprint (MD5):
A2:69:37:23:5B:27:68:B0:B7:5E:C1:61:08:04:F8:C0

Using your Certificate fingerprint (MD5) get google api key from this site

http://code.google.com/android/maps-api-signup.html

 

Copyright @ 2013 Android Developers Blog.