Monday 5 September 2011

List of installed Application

Gives the list of installed application,

        final PackageManager pm = getPackageManager();
        //gets list of installed apps.
        List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
        for (ApplicationInfo packageInfo : packages)
        {
            if( pm.getLaunchIntentForPackage(packageInfo.packageName) != null)
            {
                // Application Icon
                Drawable d = packageInfo.loadIcon(getPackageManager());                
                Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
              
                // Application name
                String data = packageInfo.loadLabel(getPackageManager()).toString();

                // uid
                int uid = packageInfo.uid;
            }
        }

Alert Dialog in Android

Code Snippet to display Alert Dialog,

           Builder dialog = new AlertDialog.Builder(this);
            dialog.setTitle("----Title---");
            dialog.setMessage("Message to be displayed");
            dialog.setPositiveButton("ok", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {

                   // Operation to be performed on clicking
                }
            });
            dialog.show();

Currently Running Process in Android

Gives list of currently running process,
  
        ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> list= am.getRunningAppProcesses();
        for(int i =0 ; i< list.size();i++)
        {
           ActivityManager.RunningAppProcessInfo runningApp = list.get(i);   
            processInfo.setProcessName(runningApp.processName);           
            int processId = runningApp.pid;
            processInfo.setProcessId(processId);
            runningPL.add(processInfo);
        }

Android Apk File


Dex File:

Java source code is converted into Java Byte Code using Java compiler, Java byte code is again converted to Dalvik byte code using dex compiler.Dex Byte code is converted in to .dex file by Dalvik virtual m/c.Here is the graphical representation of conversion,
 

APK File :

Apk file an android archive , composed of Dalvik Executable and Resource file.

Honey Comb

ActionBar :

ActionBar , is one of the coolest feature newly available in honey com ui.Allows user to customize title bar.
By ActionBar ,frequently used action made available to user without searching.

3 forms of Action Bar:
  • Tabbed Action Bar
  • List Action Bar
  • Standard Action Bar
Tabbed Action Bar:

Options appear in tab form.In below screen shot we have two tabs namely Tab1 & tab2.

     
Code snippet :

       ActionBar bar = this.getActionBar();
        bar.setTitle("Tabbed Activity");
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
      
        TabListener tabListener = new TabListener() {
          
            public void onTabUnselected(Tab tab, FragmentTransaction ft) {
                System.out.println("Tab Unselected("+tab.getText());              
            }
          
            public void onTabSelected(Tab tab, FragmentTransaction ft) {              
                System.out.println("Tab Selected"+tab.getText());
              
            }          
            public void onTabReselected(Tab tab, FragmentTransaction ft) {
                System.out.println("Tab Reselected"+tab.getText());              
            }
        };
      
        // Create tabs
      
        Tab tab1 = bar.newTab();
        tab1.setText("Tab1");
        tab1.setTabListener(tabListener);
        bar.addTab(tab1);
      
        Tab tab2 = bar.newTab();
        tab2.setText("Tab2");
        tab2.setTabListener(tabListener);
        bar.addTab(tab2);

Standard Action Bar:
Options appear in right corner as quick launch icons.In below screen shot we have two Quick launch icon.



Code Snippet :


private void createmenuActionBar()
    {
        ActionBar bar = this.getActionBar();
        bar.setTitle("menu");       
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    // action should be handled here
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        return super.onOptionsItemSelected(item);
    }

menu.xml :(res/menu/menu.xml)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:id="@+id/group1">
        <item android:id="@+id/item1" android:title="@string/menu1"
            android:icon="@drawable/creep001" android:showAsAction="ifRoom"></item>
        <item android:id="@+id/item2" android:title="@string/menu2"
            android:showAsAction="ifRoom" android:icon="@drawable/creep002"></item>
    </group>
</menu>

List Action Bar:

Options appear in list  form.In below screen shot we have two options blackberry & android



In Activity , specify form

        ActionBar bar = this.getActionBar();
        bar.setTitle("List");       
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);


menu.xml(res/menu/menu.xml)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:id="@+id/group1">
        <item android:id="@+id/item1" android:title="@string/menu1"
            android:icon="@drawable/creep001" ></item>
        <item android:id="@+id/item2" android:title="@string/menu2"
             android:icon="@drawable/creep002"></item>
    </group>
</menu>




Splash Screen

Code Snippet:

Splash Activity will be displayed for few seconds and  next Screen(MainActivity.java)  is pushed using Timer Task.

SplashActivity.java

import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class SplashActivity extends Activity {

        @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
        initTimer();
    }
    private void initTimer()
    {
        Timer t = new Timer();
        TimerTask timerTask = new TimerTask()
        {          
            @Override
            public void run()
            {
                Intent intent = new Intent(SplashActivity.this,MainScreen.class);
                startActivity(intent);
                finish();
            }
        };
        t.schedule(timerTask, 3000);
    }
MainScreen.java

import android.app.Activity;
import android.content.Intent;

public class MainScreen extends Activity {

        @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);    
    }  

User Interface:

Layout with background image (splash.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="fill_parent"
    android:layout_height="fill_parent"    
     xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/SplashScreen"
    android:background="@drawable/img">
  </RelativeLayout>

HTTP Request

Code snippet to post data to server:

The following code sends data to server using post request method.

            HttpParams httpParams = null;
            HttpClient httpclient =  null;
            HttpPost httppost = null;
            List<NameValuePair> nameValuePairs = null;

            HttpResponse response = null;

            httpParams = new BasicHttpParams();
            httpclient =  new DefaultHttpClient(httpParams);
            httppost = new HttpPost("Give Server URL");
            nameValuePairs = new ArrayList<NameValuePair>();
            // post data parameters
            nameValuePairs.add(new BasicNameValuePair("deviceId", deviceId));
            try
            {
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                response = httpclient.execute(httppost);
                int statusCode = response.getStatusLine().getStatusCode();
                Log.i("Status Code ->  ",statusCode+"");
                if(statusCode != 200)
                {
                    showDialog("Connection Error.Please Try again laterlll !!!");
                }
             } catch (Exception e)
             {
                 Log.e("Exception - Uploading data to server",e.getMessage());
             }

Getting Latitude and Longtitude in Android

Code Snippet to get latitude and longitude,

Retrieves the latitude and longitude based on current location. The corresponding class should implement LocationListener, callback notifies user in case of any change in latitude and longitude.

Code:
 private void getLatLon()
        {
            LocationManager locationManager =
                (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            Location location = locationManager
            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (location != null)
            {
                lat = location.getLatitude();
                lon = location.getLongitude();          
            }       
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100,this);
        }
        @Override
        public void onLocationChanged(Location loc)
        {
            lat = loc.getLatitude();
            lon = loc.getLongitude();  
            System.out.println("Lat and long here is"+lat +"--------->>"+lon);
        }
        @Override
        public void onProviderDisabled(String arg0) {
        }
        @Override
        public void onProviderEnabled(String arg0) {
        }
        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2)
        {
        }


Android Permission :

ACCESS_COARSE_LOCATION
ACCESS_MOCK_LOCATION
CONTROL_LOCATION_UPDATES

Passing Values from activity to another activity using Intent

Passing Values from activity to another activity using Intent: 

User Interface:

We have a login screen with UserName label(TextView) ,Password label(TextView) ,UserName (EditView),Password (EditView) to enter values and a login Button.    
          
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">
 <LinearLayout android:id="@+id/LinearLayout01"
  android:layout_height="wrap_content" android:layout_width="fill_parent">
  <TextView android:layout_width="wrap_content"
   android:layout_height="wrap_content" android:id="@+id/UserNameText"
   android:text="UserName" android:typeface="sans" android:textStyle="bold">
</TextView>

  <EditText android:layout_height="wrap_content" android:hint="User Name"
   android:layout_width="fill_parent" android:id="@+id/username"></EditText>
 </LinearLayout>
 <LinearLayout android:id="@+id/LinearLayout02"
  android:layout_height="wrap_content" android:layout_width="fill_parent">
  <TextView android:layout_width="wrap_content"
   android:layout_height="wrap_content" android:id="@+id/PasswordText"
   android:text="Password" android:textStyle="bold"></TextView>
  <EditText android:layout_height="wrap_content" android:hint="Password"
   android:singleLine="true" android:layout_width="fill_parent"
   android:id="@+id/password"></EditText>
 </LinearLayout>
 <Button android:layout_height="wrap_content" android:id="@+id/login"
  android:text="Login" android:layout_gravity="center"
  android:layout_width="100px"></Button>
</LinearLayout>

Activity:
               On Clicking on login button, displays an dialog with username

LoginActivity.java
package com.login;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends Activity {
    /** Called when the activity is first created. */
    // Retrieve username and password using id.
    EditText userName = null;
    EditText password = null;
    // Button
    Button loginButton = null;
    Context context = null;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        userName = (EditText)findViewById(R.id.username);
        password = (EditText)findViewById(R.id.password);
        loginButton = (Button)findViewById(R.id.login);
        loginButton.setOnClickListener(new Button.OnClickListener()
        {
            @Override
            public void onClick(View arg0)
            {                       
                if(password.getText()!= null && userName.getText()!= null && password.getText().length()==0 && userName.getText().length()==0)
                {
                    showDialog();       
                }
                else
                {
                    String uName = userName.getText().toString();
                    Intent intent = new Intent(LoginActivity.this,DisplayActivity.class);
                    intent.putExtra("UserName", uName);
                    startActivity(intent);
                }
            }
        });
    }
    /**
     * On clicking login button, dialog is displayed with userName
     */
    private void showDialog()
    {
        Builder alert = new AlertDialog.Builder(this);
        alert.setMessage("Enter UserName and Password");
        alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {

            }
        });
        alert.show();       

    }
}
DisplayActivity.java
package com.login;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
/**
 *
 * @author rathika.r
 *
 */
public class DisplayActivity  extends Activity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {       
        super.onCreate(savedInstanceState);
        setContentView(R.layout.data);
        TextView uName = (TextView)findViewById(R.id.TextView01);
        Bundle data = getIntent().getExtras();
        if(data != null && data.containsKey("UserName"))
        {
            uName.setText("Welcome "+data.getCharSequence("UserName")+"!!!");
        }
    }
}
Output:

Android Basics

Sample Log-in Screen:

User Interface:
                Username and password edit field with login Button.(main.xml)
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">
<LinearLayout android:id="@+id/LinearLayout01"
android:layout_height="wrap_content" android:layout_width="fill_parent">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/UserNameText"
android:text="UserName" android:typeface="sans" android:textStyle="bold"></TextView>

<EditText android:layout_height="wrap_content" android:hint="User Name"
android:layout_width="fill_parent" android:id="@+id/username"></EditText>
</LinearLayout>
<LinearLayout android:id="@+id/LinearLayout02"
android:layout_height="wrap_content" android:layout_width="fill_parent">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/PasswordText"
android:text="Password" android:textStyle="bold"></TextView>
<EditText android:layout_height="wrap_content" android:hint="Password"
android:singleLine="true" android:layout_width="fill_parent"
android:id="@+id/password"></EditText>
</LinearLayout>
<Button android:layout_height="wrap_content" android:id="@+id/login"
android:text="Login" android:layout_gravity="center"
android:layout_width="100px"></Button>
</LinearLayout>

Activity:
               On Clicking on login button , displays an dialog with username

LoginActivity.java
package com.login;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends Activity {
/** Called when the activity is first created. */
// Retrieve username and password using id.
EditText userName = null;
EditText password = null;
// Button
Button loginButton = null;
Context context = null;

@Override
public void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
userName = (EditText)findViewById(R.id.username);
password = (EditText)findViewById(R.id.password);
loginButton = (Button)findViewById(R.id.login);
loginButton.setOnClickListener(new Button.OnClickListener() 
{
@Override
public void onClick(View arg0)
{
showDialog();
}
});
}
/**
 * On clicking login button, dialog is displayed with userName
 */
private void showDialog() 
{
Builder alert = new AlertDialog.Builder(this);
alert.setMessage("Welcome "+userName.getText()+"!!!!");
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface arg0, int arg1) {


}
});
alert.show();

}
}
Output:

Access Gallery,Camera,CallLog and Contacts

Code Snippet to access gallery,

Intent intent = new Intent();
// View  the gallary
intent.setAction(Intent.ACTION_VIEW);
intent.setData(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
// Start the activity
startActivity(intent);

Code Snippet to open Camera,
  
Intent  intent = new Intent()
intent.setAction(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(intent);    

Code Snippet to access Call Log:

Intent  intent = new Intent();
intent.setAction(Intent.ACTION_CALL_BUTTON);
startActivity(intent);
 

Code Snippet to access Contacts:


Intent  intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(android.provider.Contacts.People.CONTENT_URI);
startActivity(intent);   

Android device information

Code Snippet to get device information,

         String deviceId_str,softwareVersion_str ,simSerialNo,voicemailNumer_str,
        sim_operator_Name;

        TelephonyManager telephonyManager = null;
        telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

        // device Id
        deviceId_str = telephonyManager.getDeviceId();
        // software version
        softwareVersion_str = telephonyManager.getDeviceSoftwareVersion();
        // serial number
        simSerialNo = telephonyManager.getSimSerialNumber();
        //voice mail number
        voicemailNumer_str = telephonyManager.getVoiceMailNumber();
        // sim operator name
        sim_operator_Name= telephonyManager.getSimOperatorName();

Android Permission :
android.permission.READ_PHONE_STATE, needs to be included in manifest file.