Senin, 07 Desember 2009

Sample Android Activity,Service ( 1 )

An activity is the equivalent of a Frame/Window in GUI toolkits. It takes up the entire drawable area of the screen. An activity is what gets bound to the AndroidManifest.xml as the main entry point into an application. For long running tasks, it’s best to use a service that talks to this activity.

Service : Activities are meant to display the UI and get input from the user. Services on the other hand keep running for the duration of the user’s ‘session’ on the device.


Activity Navigation:
This has done by the following two ways.
1. Fire and forget – create an event (Intent) and fire it
2. Async callback – create an event (Intent), fire it, and wait for it’s response in a callback method (of the calling-Activity).

Activity history stack
Please note that Android maintains a history stack of all the Activities that have been spawned in an application’s Linux process. In the sample code above, the calling-Activity simply provides the class name of the sub-Activity. When the sub-Activity finishes, it puts it’s result code and any data back on the stack and finishes itself. Since Android maintains the stack, it knows which calling Activity to pass the result back to. The calling-Activity has an onActivityResult method that handles all the callbacks from the sub-Activities. This is pretty confusing at first, since to keep it all straight we have to use CorrelationIds (more on that below).

Example : User wants to navigate Talk application to Browser Application. Using the Browser application wants to serach some photos and saved his local memory. After that he shares the photo with his friend via email application and finally he will come back to the talk application.

Firstly, as the user is talking to his friend, a specific Talk application is opened, which contains the activity manager. System Creates two processes, the main system process and Talk application process. Moreover, before going to Web Browser application, the system saves a Talk state T in order to remember that process. At this point, as a user holds a talk and opens a web browser, the system creates a new process and new web browser activity is launched in it. Again, the state of the last activity is saved.After that, the user browses the internet, finds his picture in Picasa album and saves it to particular folder. He does not close a web browser, instead he opens a folder to find saved picture. The folder activity is launched in particular process.  At this point, the user finds his saved picture in the folder and he creates a request to open an Email application. The last state F is saved. Now assume that the mobile phone is out of the memory and there is no room to create a new process for Email application. Therefore, Android looks to kill a process. It can not destroy Folder process, as it was used previously and could be reused again, so it kills Web Browser process as it is not useful anymore and locates a new Email process instead. The user opens Email application and sends a picture to his friend via email. Now he wants to go back to the Talk application and to resume a talk to his friend. Because of the previously saved states, this work is done fast and easily. In this example, Email application is popped out and the user sees a previous Folder application.Next, the user goes back to Web Browser application. Unfortunately, web browser
process was killed previously so the system has to kill another process (in our case it is Email application process, which is not used anymore) in order to locate Web Browser process and manage the stack memory. Now the user comes back to the Talk application and resumes his talk with his friend. Because of the saved states, going back procedure is fast and useful, because it remembers previous activities and its views.
This example shows, that it does not matter how many applications and processes are active or how much available memory is left, Android it manages fast and without a user interaction.

Fire and forget
For this method we just calls the child activity and flow the process. we are not getting any return value from the child activity. Here intent is just an event. It can have a target of an activity calss along with some date that's passed in via a Bundle.
refer : http://about-android.blogspot.com/2009/12/passing-data-or-parameter-to-another_02.html


1. Create a two Activity [MainActivity & ChildActivity]

Activity : 1 -  MainActivity
 public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }
}
 
 Activity : 2 - ChildActivity
 public class ChildActivity extends Activity {
     /**
      * @see android.app.Activity#onCreate(Bundle)
      */
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         // TODO Put your code here
     }
 }
 

2.  Define Your Shared collection
    Bundle bundle = new Bundle();
    bundle.putString("sample", "this is the test commands");

3. Call the child Activity from mainactivity with the bundle
    startActivity(new Intent(this, ChildActivity.class).putExtras(bundle));
 
4. Get the Value from MainActivity in ChildActivity
     this.getIntent().getExtras().getString("sample")

5. Toast the Message
    Toast.makeText(this, this.getIntent().getExtras().getString("sample"),
            Toast.LENGTH_LONG).show();



Full Source :MainActivity.java
 
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Bundle bundle = new Bundle();
        bundle.putString("sample", "this is the test commands");
        bundle.putString("sample1", "this is the test commands1");
        startActivity(new Intent(this, ChildActivity.class).putExtras(bundle));
    }
}

-------ChildActivity.java----------
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

public class ChildActivity extends Activity {
    /**
     * @see android.app.Activity#onCreate(Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(this, this.getIntent().getExtras().getString("sample"),
                Toast.LENGTH_LONG).show();
        Toast.makeText(this, this.getIntent().getExtras().getString("sample1"),
                Toast.LENGTH_LONG).show();
    }
}   
 

Async callback, and correlationId
The calling-Activity has to provide a correlationId/request code to the Intent/event, before firing/raising it. This is then used by the sub-Activity to report it’s results back to the calling-Activity when it’s ready. The calling-Activity does not stop when it spawns the sub-Activity.

Please note that this sub-Activity is not "modal", that is, the calling Activity does not block, when startSubActivity() is called. So if you’re thinking that this is like a modal dialog box, where the calling-Activity will wait for the sub-Activity to produce a result, then you have to think of it differently.


1. Create a two Activity [MainActivity & ChildActivity]

Activity : 1 -  MainActivity
 public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }
}
 
 Activity : 2 - ChildActivity
 public class ChildActivity extends Activity {
     /**
      * @see android.app.Activity#onCreate(Bundle)
      */
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         // TODO Put your code here
     }
 }
 

2. Call the child Activity from mainactivity with the bundle
    Intent i = new Intent(this, ChildActivity.class);
    startActivityForResult(i, 1);
 
4. Set the Value from ChildActivity To  MainActivity
    setResult(RESULT_OK, new Intent().putExtra("result", "value from Child Activity"));
    finish();

5. Receive the value from ChildActiivity and Print the Message in onActivityResult Method
    if (resultCode == RESULT_OK) {
        String name = data.getStringExtra("result");
        Toast.makeText(this, "You have chosen the City: " + " " + name,
                Toast.LENGTH_LONG).show();
    }

Source Code

MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Intent i = new Intent(this, ChildActivity.class);
        startActivityForResult(i, 1);
    }
   
    protected void start(Intent intent) {
        this.startActivityForResult(intent, 1);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       
               
        if (resultCode == RESULT_OK) {
            String name = data.getStringExtra("result");
            Toast.makeText(this, "You have chosen the Value: " + " " + name,
                    Toast.LENGTH_LONG).show();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

}

ChildActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class ChildActivity extends Activity {
    /**
     * @see android.app.Activity#onCreate(Bundle)
     */
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(this, "Child Activity", Toast.LENGTH_LONG).show();       
        setResult(RESULT_OK, new Intent().putExtra("result", "value from Child Activity"));
        finish();
    }
}


Kamis, 03 Desember 2009

Working with Alert / Log / Notification in Android

Here we are discussing about the some essential Source which is helps to track or use the inbuild system call.
1. Toast
    Toast notification are holdes alert message to the user. It does not accept the interaction events. It automatically fades in and out.

System Toast Notification
Activity : 1 -  MainActivity
 public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }
}
 

2.  Define Toast Object and Message
    // One-line Toast Notification Implementation
    Toast.makeText(this, "Demo Toast", Toast.LENGTH_LONG).show();

    // Change the Notification Position
    Toast myToast = Toast.makeText(this, "Demo Toast", Toast.LENGTH_LONG);
    myToast.setGravity(Gravity.TOP, 100, 100);
    myToast.show();

3. Save and run the Project.

Custom Toast Notification
Activity : 1 -  MainActivity
 public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }
}


2. Layout : Create a custom Layout with some icon and text message

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout android:id="@+id/AbsoluteLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
    <ImageView android:id="@+id/ImageView01" android:layout_height="wrap_content"
    android:layout_width="wrap_content" android:layout_y="161dip" android:layout_x="45dip"
    android:background="@drawable/icon"></ImageView>
    <TextView android:layout_width="wrap_content" android:layout_x="131dip"
    android:layout_height="wrap_content" android:layout_y="163dip" android:id="@+id/TextView01"
    android:text="Custom Message"></TextView>
</AbsoluteLayout>

3. Get the Layout View using the LayoutInflator in Activity Class
    LayoutInflater inflater = getLayoutInflater();
    View layout = inflater.inflate(R.layout.custommessage,
        (ViewGroup) findViewById(R.id.AbsoluteLayout01));

4. Define the Toast object with the custom message.
        Toast toast = new Toast(getApplicationContext());
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP | Gravity.LEFT, 100, 100);
        toast.setView(layout);
        toast.show();

5. Save and run the Project.

Full Source
custommessage.xml - Layout
    <?xml version="1.0" encoding="utf-8"?>
    <AbsoluteLayout android:id="@+id/AbsoluteLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
        <ImageView android:id="@+id/ImageView01" android:layout_height="wrap_content"
        android:layout_width="wrap_content" android:layout_y="161dip" android:layout_x="45dip"
        android:background="@drawable/icon"></ImageView>
        <TextView android:layout_width="wrap_content" android:layout_x="131dip"
        android:layout_height="wrap_content" android:layout_y="163dip" android:id="@+id/TextView01"
        android:text="Custom Message"></TextView>
    </AbsoluteLayout>
    
    
    
MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // One-line Toast Notification Implementation
        Toast.makeText(this, "Demo Toast", Toast.LENGTH_LONG).show();

        // Change the Notification Position
        Toast myToast = Toast.makeText(this, "Demo Toast", Toast.LENGTH_LONG);
        myToast.setGravity(Gravity.TOP, 100, 100);
        myToast.show();

        // Custom Notification
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.custommessage,
                (ViewGroup) findViewById(R.id.AbsoluteLayout01));
        Toast toast = new Toast(getApplicationContext());
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP | Gravity.LEFT, 100, 100);
        toast.setView(layout);
        toast.show();

    }
}


Log -
Log Class provides to create a log statement with Key Value Pair.
You can create Log statement using the following steps.
1. Create a Project -> Activity
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
    }
}
2. Call the d() with Key value pair. ->
    Log.d("@G MYLOG","Sample Log Message");
    Key -> @G MYLOG
    Value->Sample Log Message
    
3. Run and Check the Log.
    Go to Window->Show View -> Android -> Log Cat


    

Source :
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.d("@G MYLOG","Sample Log Message");
    }
}


Rabu, 02 Desember 2009

Database Programming in android

Android provides four ways to achieve the persistence.
Preferences - Basically used for storing user preferences for a single application or across applications for a mobile. This is typically name-value pairs accessible to the context.
Databases - Android supports creating of databases based on SQLite db. Each database is private to the applications that creates it
Files - Files can be directly stored on the mobile or on to an extended storage medium. By default other applications cannot access it.
Network - Data can be stored and retrieved from the network too depending on the availability.    

Preference :
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). First we need to put our value in to the context. And the context object lets you retrieve SharedPreferences through the method Context.getSharedPreferences().

1. Make a Shared Preference Collection
2. Retrieve Shared Preference Collection

Make a Shared Preference Collection
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
    SharedPreferences.Editor prefsEditor = myPrefs.edit();
    prefsEditor.putString("sample", "this is test commands");
    prefsEditor.commit();


Retrieve Shared Preference Collection
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
    prefsEditor.getString("sample", "DEFAULT VALUE")
;


Creating and Using Databases in Android
Every application uses data, and Android applications are no exception. Android uses the open-source, stand-alone SQL database, SQLite. Learn how to create and manipulate a SQLite database for your Android app.

Android uses the SQLite database system, which is an open-source, stand-alone SQL database, widely used by many popular applications.

In Android, the database that you create for an application is only accessible to itself; other applications will not be able to access it. Once created, the SQLite database is stored in the /data/data//databases folder of an Android device. In this article, you will learn how to create and use a SQLite database in Android.

Here we are going to introduce two new class for database programming.
Class 1. Create a SQLiteFactoryManager which is provide the database.
Class 2. Create a DAOHelper which provides CRUD Operation.


Create a SQLiteFactoryManager which is provide the database.
SQLiteFactoryManager is used to create a database and tables
Step 1: Create a SQLConnectionFactory class which extends the SQLiteOpenHelper
        public class SQLConnectionFactory extends SQLiteOpenHelper {

Step 2: Create a database using the SQLiteOpenHelper constructor
        public SQLConnectionFactory(Context context) {
            super(context, DATABASENAME, null, 1);   
        }


Step 3: Create Tables
    db.execSQL(CREATE_USERTABLE);
   

SAMPLE SOURCE   

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

public class SQLConnectionFactory extends SQLiteOpenHelper {

    private static final String DATABASENAME = "BIRTHDAY";
    private static final String CREATE_USERTABLE = "CREATE TABLE BIRTHDAY(ID INTEGER NOT NULL CONSTRAINT USER_PK PRIMARY KEY AUTOINCREMENT,NAME TEXT,CATEGORY TEXT,DOB DATE,AGE INTEGER)";
   
    public SQLConnectionFactory(Context context) {
        super(context, DATABASENAME, null, 1);   
    }
   
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_USERTABLE);
        Log.d("@G SQLConnectionFactory", " CREATE_USERTABLE Table ");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}


Create a DAOHelper which provides CRUD Operation.
Step1: Get the Factory Object from SQLConnectionFactory.
        factoryObj = new SQLConnectionFactory(c);

Step2: Get the readable/writeable database object using the Factory Object.
        public static SQLiteDatabase getReadableDataBase(Context c) {
            return factoryObj.getReadableDatabase();
        }

        public static SQLiteDatabase getWriteableDataBase(Context c) {
            return factoryObj.getReadableDatabase();
        }


Step 3: Perform the CRUD operation using SQLite query. insertData,removeData,getData.

Sample Code

import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import android.widget.ArrayAdapter;

public class DAOHelper {

    static SQLConnectionFactory factoryObj;
    static SQLiteDatabase database;

    public DAOHelper(Context c) {
        factoryObj = new SQLConnectionFactory(c);
    }

    public static SQLiteDatabase getReadableDataBase(Context c) {
        return factoryObj.getReadableDatabase();
    }

    public static SQLiteDatabase getWriteableDataBase(Context c) {
        return factoryObj.getWriteableDatabase();
    }

    public void insertData(Context c, Object bindValue[]) {
        database = getWriteableDataBase(c);
        SQLiteStatement statement = database
                .compileStatement("SELECT MAX(ID) + 1 FROM BIRTHDAY");
        long taskId = statement.simpleQueryForLong();
        if (taskId <= 0) {
            taskId = 1;
        }
        database.execSQL(
                "INSERT INTO BIRTHDAY(NAME,CATEGORY,DOB) VALUES(?,?,?)",
                bindValue);
    }

    public ArrayList getData(Context c, Object bindValue[]) {
        ArrayList taskNameList = new ArrayList();
        try {
            database = database = getReadableDataBase(c);
            Cursor results = database.rawQuery("SELECT * FROM BIRTHDAY", null);
            if (results.moveToFirst()) {
                for (; !results.isAfterLast(); results.moveToNext()) {
                    taskNameList.add(results.getString(1) + " - "
                            + results.getString(3));
                }
            }
        } catch (Exception e) {
            Log.e("Tasks App", "Unable to to refresh tasks.", e);
        } finally {
            return taskNameList;
        }
    }

    public boolean removeData(Context c, Object bindValue[]) {
        try {
            database = database = getReadableDataBase(c);
            database.execSQL("DELETE FROM BIRTHDAY WHERE ID in (?)", bindValue);
        } catch (Exception e) {
            Log.e("Remove Data", "Unable to to DELETE id.", e);
        } finally {
            return true;
        }
    }

}

Hope this is helpful for you



Passing data or parameter to another Activity Android - 2

Passing data or parameter to another Activity Android - using Bundle
This following step helps to share the content using bundle.
 1. Create a two Activity [MainActivity & ChildActivity]

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

 
 Activity : 2 - ChildActivity
 public class ChildActivity extends Activity {
     /**
      * @see android.app.Activity#onCreate(Bundle)
      */
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         // TODO Put your code here
     }
 }

 

2.  Define Your Shared collection
    Bundle bundle = new Bundle();
    bundle.putString("sample", "this is the test commands");
    bundle.putString("sample1", "this is the test commands1");



3. Call the child Activity from mainactivity with the bundle
    startActivity(new Intent(this, ChildActivity.class).putExtras(bundle));
 
4. Get the Value from MainActivity in ChildActivity
     this.getIntent().getExtras().getString("sample")

5. Toast the Message
    Toast.makeText(this, this.getIntent().getExtras().getString("sample"),
            Toast.LENGTH_LONG).show();
    Toast.makeText(this, this.getIntent().getExtras().getString("sample1"),
        Toast.LENGTH_LONG).show();
 

 
 Full Source :MainActivity.java
 
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Bundle bundle = new Bundle();
        bundle.putString("sample", "this is the test commands");
        bundle.putString("sample1", "this is the test commands1");
        startActivity(new Intent(this, ChildActivity.class).putExtras(bundle));
    }
}

-------ChildActivity.java----------
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

public class ChildActivity extends Activity {
    /**
     * @see android.app.Activity#onCreate(Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(this, this.getIntent().getExtras().getString("sample"),
                Toast.LENGTH_LONG).show();
        Toast.makeText(this, this.getIntent().getExtras().getString("sample1"),
                Toast.LENGTH_LONG).show();
    }
}

Passing data or parameter to another Activity Android

In this blog we have discussed shared preference and bundle collection. We can pass the value from parent activity to child activity using the bundled collection and shared preference.
1. Shared Preference
2. Bundle Collection

Shared Preference
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). First we need to put our value in to the context. And the context object lets you retrieve SharedPreferences through the method Context.getSharedPreferences().

1. Make a Shared Preference Collection
2. Retrieve Shared Preference Collection

Make a Shared Preference Collection
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
    SharedPreferences.Editor prefsEditor = myPrefs.edit();
    prefsEditor.putString("sample", "this is test commands");
    prefsEditor.commit();

Retrieve Shared Preference Collection
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
    prefsEditor.getString("sample", "DEFAULT VALUE");


 1. Create a two Activity [MainActivity & ChildActivity]
 
Activity : 1 -  MainActivity
 public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }
}

 
 Activity : 2 - ChildActivity
 
public class ChildActivity extends Activity {
     /**
      * @see android.app.Activity#onCreate(Bundle)
      */
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         // TODO Put your code here
     }
 }

 

2.  Define Your Shared collection
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
        SharedPreferences.Editor prefsEditor = myPrefs.edit();
        prefsEditor.putString("sample", "this is test commands");
        prefsEditor.commit();   
   

3. Call the child Activity from mainactivity
   
startActivity(new Intent(this,ChildActivity.class));
 
4. Get the Value from MainActivity in ChildActivity
 
    SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);

5. Toast the Message
  
  Toast.makeText(this, myPrefs.getString("sample", "DEFAULT VALUE"), Toast.LENGTH_LONG).show();   
 
 
 Full Source :MainActivity.java
 
 import android.app.Activity;
 import android.content.Intent;
 import android.content.SharedPreferences;
 import android.os.Bundle;
 
 public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
         SharedPreferences.Editor prefsEditor = myPrefs.edit();
         prefsEditor.putString("sample", "this is test commands");
         prefsEditor.commit();       
         startActivity(new Intent(this,ChildActivity.class));
     }
}

-------ChildActivity.java----------
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

public class ChildActivity extends Activity {
    /**
     * @see android.app.Activity#onCreate(Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        SharedPreferences myPrefs = this.getSharedPreferences("contact", MODE_WORLD_READABLE);
        Toast.makeText(this, myPrefs.getString("sample", "DEFAULT VALUE"), Toast.LENGTH_LONG).show();       
    }
}


Minggu, 29 November 2009

Android Hello World Activity Sample

Here we are looking how to create a sample hello android program using eclipse IDE
1.Setup your Environment
2. Create an application

1. Setup Android Environment
a. Download latest Eclipse from http://eclipse.org/
b. update android Plug-in - Refer : http://about-android.blogspot.com/2009/11/about-android-first-of-all-android_09.html


c. Install Android SDK
Install new android SDK from the android site. Refer:http://about-android.blogspot.com/2009/11/about-android-first-of-all-android_09.html


D. Configure SDK with your Eclipse
Go to Window>Preference>Select Android > Browse "SDK PATH" > Apply


E. Create a Device / Emulator
Create emulator using the AVD manager
Open AVD Manager > New > Give Name/Target > Create AVD.


Android Environment has setted. Now we can create an android Application.

2. Create a " Hello World Apps "
a. Open Eclipse > File > Android Project.


b. Check the Android Folder Structure.
Go to Window > Show View > package Explorer


AndroidManifest.xml - It contains the overall application configuration.
src - Contains the java code like activites,service,broadcast receiver , etc,.
res - Contains the application resource
          1. drawable - Icon,Image
          2. raw - Sounds
          3. menu - menu properties
          4. values - application properites like title,color value, dropdown values.
          5. layout - screen design
gen - Contains the R.java File which is used to map the resource and java src.

c. Run the application
Run > Run Android Application

 

 D. Check the Emulator


Hope this is useful for create a hello world program.

Sabtu, 21 November 2009

Application Fundamentals

Android applications are written in the Java programming language.
Android application archieve format is .apx
Each process has its own Java virtual machine (VM), so application code runs in isolation from the code of all other application
Android Application Components are Activites,Service,Broadcast receivers and Content providers

Activities
An application that has a visible UI is implemented with an activity. When a user selects an application from the home screen or application launcher, an activity is started.

Services
A service should be used for any application that needs to persist for a long time, such as a network monitor or update-checking application.

Content providers
You can think of content providers as a database server. A content provider's job is to manage access to persisted data, such as a SQLite database. If your application is very simple, you might not necessarily create a content provider. If you're building a larger application, or one that makes data available to multiple activities or applications, a content provider is the means of accessing your data.

Broadcast receivers
An Android application may be launched to process a element of data or respond to an event, such as the receipt of a text message.

AndroidManifest.xml - Configuration
An Android application, along with a file called AndroidManifest.xml, is deployed to a device.
AndroidManifest.xml contains the necessary configuration information to properly install it to the device. It includes the required class names and types of events the application is able to process, and the required permissions the application needs to run.

Project Folder Structure ;
1. src - It contain the java code
2. Resource - It contain the all resource with different floder
    drawable - Icon
    raw - Sounds
    menu - Menu
    values - Project Properties
    layout - User interface Screens
3. gen - It contains the R.java file. You could not edit R.java manually. This have been generated automatically by understanding resource files etc.
4. AndroidManifest -It contains the Project properties
5. Android lib.


The next topic discusses the "Hello Android" Program and layout.

Jumat, 20 November 2009

Architecture of Android

Architecture of Android :
1. Linux Kernal [ 2.6 Kernal - security, memory management, process management, network stack, and driver model]
2. Native Libraries [SQLite, WEBKit, OpenGL,..]
3. Runtime + Dalvik VM [.dex format, Lightweight VM, Efficient Dalvik Bytecode]
4. Application Framework [Activity Manager, Content Manager, Location Manager, ]
5. Application [ System Apps and Your Apps]


Linux Kernal
Android is based on the linux keral 2.6. From the Kernal 2.6 android using the hardward interaction layer
Android relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack, and driver model. The kernel also acts as an abstraction layer between the hardware and the rest of the software stack.

Libraries
Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework.

Android Runtime
Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language.

Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included "dx" tool.

The Dalvik VM relies on the Linux kernel for underlying functionality such as threading and low-level memory management.



Application Framework

Developers have full access to the same framework APIs used by the core applications. The application architecture is designed to simplify the reuse of components; any application can publish its capabilities and any other application may then make use of those capabilities (subject to security constraints enforced by the framework). This same mechanism allows components to be replaced by the user.

Underlying all applications is a set of services and systems, including:

* A rich and extensible set of Views that can be used to build an application, including lists, grids, text boxes, buttons, and even an embeddable web browser
* Content Providers that enable applications to access data from other applications (such as Contacts), or to share their own data
* A Resource Manager, providing access to non-code resources such as localized strings, graphics, and layout files
* A Notification Manager that enables all applications to display custom alerts in the status bar
* An Activity Manager that manages the lifecycle of applications and provides a common navigation backstack



Applications

Android will ship with a set of core applications including an email client, SMS program, calendar, maps, browser, contacts, and others. All applications are written using the Java programming language.

The next topic discusses the basic components and folder structure of android application.

Senin, 09 November 2009

About Android

First of all, Android operating system is running on the Linux kernel 2.6.27, meaning stronger security, improved stability and a range of core applications enhancements. Android provides packs SIM Application Toolkit 1.0 and features are auto-checking and repair of SD cardfile-system. Just like the iPhone OS 3.0, Android comes with the SDK that adds new APIs which help developers create better apps.

Some of the features are simply catchup of the iPhone’s, like a new virtual keyboard or improved mobile web browser. Others are designed to add more punch through flashier eye candy, like animated window transitions, smooth, accelerometer-based application rotations between portrait and landscape modes and overall polish of user interface elements.

Android Features:
* Application framework enabling reuse and replacement of components
* Dalvik virtual machine optimized for mobile devices. -
* Integrated browser based on the open source WebKit engine
* Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional)
* SQLite for structured data storage
* Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF)
* GSM Telephony (hardware dependent)
* Bluetooth, EDGE, 3G, and WiFi (hardware dependent)
* Camera, GPS, compass, and accelerometer (hardware dependent)
* Rich development environment including a device emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE
* Support Other platform. Andriod NDK for c,c++ Developer and ASM for phython developers

Reference:
http://www.dalvikvm.com/ [1]

Top 10 features you’ll love about Android 1.5
  • Smart virtual keyboard
  • Home screen customizable with widgets
  • Live Folders for quick-viewing your data
  • Video recording and sharing
  • Picasa image uploading
  • Faster, standards-compliant browser
  • Voice Search
  • Stereo Bluetooth and hands-free calls
  • Snappier overall performance
  • Nice-to-haves
What are Other Mobile OS?
  • Symbian OS from Symbian Ltd,
  •  RIM BlackBerry operating system
  • iPhone OS from Apple Inc.
  • Windows Mobile from Microsoft
  • Linux operating system Palm webOS from Palm Inc.



The second Android Developer Challenge has begun! In this contest, real-world users will help review and score applications and the overall winner will take away $250,000 (read more...)


How to Program Google Android in eclipse
You can bulid your android application using the powerful Eclipse environment. This part introduces Android application development with the Eclipse plug-in, otherwise known as Android Development Tools. This provides an introduction to Android development with a quick introduction to the platform, a tour of Android Development Tools, and includes the construction of "Hello World " example applications.

Prerequisites
This section provides to setup the right environment to develop the android application.

System Requirements
Eclipse Platform
Get the latest version of Eclipse 3.5 (Galileo) from http://www.eclipse.org/galileo/ (V3.5 was used in this tutorial).

Android Developer Tools
Get the latest version of Android SDK from http://developer.android.com/sdk/index.html (V2.0 was used in this tutorial).


Set The Android Environment

Steps to Install Eclipse and Add plugin
1. Get the Eclipse 3.5 archieve File from http://www.eclipse.org/galileo/
2. Extract the archieve File and run the Eclipse
3. Click Help->Install New software->Add
4. Type : Name :Android plug-in
5. Install the Plug-in
6. Restart the Eclipse

Steps to Install Android SDK
2 : Run the Setup. - Goto the Commant pr
3 : You can see the popup (Android SDK and AVD Manager)
4 : If you encounter the following issue follow the solution, still if you have issue post your comments
----------------
Issue :Failed to fetch URL https://dl-ssl.google.com/andr oid/repository/repository.xml

Solution :
Step 1 : Run the Tool
Step 2 : Change settings options and checked in [ misc section "force https:// ... sources to be fetched using http://..." ]
Step 3 : Restart application
Step 4 : Ensure the Option Selected.
-----------------
5. Ensure your SDK is successfully updated.
Now the android environment is ready to create your application.


Develop Android Applications With Eclipse

You can develop your first android application using the below steps.

  • Create Emulator using the android toolkit
  • Configure Android SDK with your Eclipse
  • Create a demo Application

Create Device Using The Android Toolkit
1. Go to the SDK/tools/
2. Open a SDK Tool and run android.bat File
3. You can see the Android SDK and AVD Manager and Click "New"
4. Enter Device Name & Target Version and Click Create.

Configure Android SDK with your Eclipse
1. Open Eclipse
2. Go to preference : Window -> preference -> select Android
3. Browse and select the SDK Path (You can see the SDK version)
4. Apply and Close the preference popup

Create a demo Application
1. Open Eclipse and Create a new Android Project : File ->New -> Project -> Android Project
2. Enter the following data
1. project Name : Demo
2. Select Build Target : Android 1.1
3. Application Name : Demo
4. Package Name : com.demo
5. Create Activity : Demo
6. Min SDK Version : 2
3. Finally Click Finish
4. Check you application in project explorer
5. Run the your application : Run-> Run

About SDK Tool

You can find the following tools from your android sdk location
1. emulator – the emulator executable, that runs the APK files
2. adb – android debugger bridge, which is used to communicate with instances of the emulator
3. ddms – this is the debugger for the emulator executable

emulator – run your APK files
Run this program to launch the emulator that you can run your APK files in.
When you use plugins in your IDE to launch APK files, the emulator is started and the APK files are loaded it by the IDE.
otherwise you can using the below commands to install your application.


adb – install and uninstall APK files
The adb program is used to install APK files into the emulator that’s running.
Command : adb install
For example: “adb install SomeAndroidApp.apk”

To uninstall an APK file you have use adb to remove the file from the emulator itself.
For example: "adb shell rm data/app/SomeAndroidApp.apk"

*NOTE: To install or uninstall an APK file, please make sure that the emulator is already running.


ddms – debug and monitor your Android apps, and the emulator
This is the Android SDK emulator debugger. This is what you can do with your ebugger:

1. You can use this to look at LogCat output from your Android programs (Log.i(), Log.e(), etc) calls that are made in your Android program.
2. You can set the telephony status of your emulator. You can control the network data i/o speed and latency. You can even fake an incoming phone call into the emulator. You can even create an incoming SMS message.
3. You can take screenshots of the display of the emulator at any given time.
4. You can view the contents of the emulator’s filesystem. This is useful if you want to see where files are stored (that you download in your apps for example).

Here’s more information from Google Android docs on ddms.
The Eclipse plugin gives you full access to ddms functionality inside the IDE itself.

Emulator performance
To get an idea of what CPU speed your emulator is emulating try this:
1. start a shell session (adb shell),
2. then run "cat /proc/cpuinfo" to get the BogoMIPS.








Senin, 06 Juli 2009

WallSwitch v1.5.0 Released!

I'm incredibly happy to finally announce that WallSwitch 1.5 has been published to the Android Market! It's been a significant amount of work to add some of the new features and fix the outstanding bugs. Here's what you can expect to find in the new version:




  • You can now select multiple wallpaper folders

  • New picker for auto-switch interval

  • Low Performance Mode, in case your phone is sluggish

  • Android 1.5 officially, and exclusively, supported

  • Won't auto-switch right at boot. It waits a minute so the boot can finish.



There were also a few bugs fixed in the image processing. Notably, cropping should be faster and more accurate. As always, if you find any bugs, please don't hesitate to email me.

Minggu, 03 Mei 2009

WallSwitch v1.0.4 Released!

Released tonight with a couple more bug fixes.




I'm going to start work on v1.1 soon, which will add some of my more frequently requested features.

Rabu, 29 April 2009

WallSwitch v1.0.3 Released!

Just a quick note on a release that happened a couple days ago. Some bugs were found very quickly and I had to do a quick release so it would work on more phones.




Other than that, working on a couple more features. Right now, I'm thinking checkboxes instead of a radio button for choosing the folder for your wallpapers will be the first thing I do. It seems to be the more requested feature at the moment and is a really good idea.

Minggu, 26 April 2009

WallSwitch 1.0 Released!




I'm happy to announce that WallSwitch 1.0 has been released!




WallSwitch is a program designed to randomly switch the wallpaper on your phone at a given interval. It handles all the image processing, like cropping, automatically so that you never have to manually set your wallpaper again!




It is also designed to intelligently determine if an image should be cropped or letterboxed so that you always have the optimal wallpaper size for you.




You can download it to your G1 (or any future Android devices) through the Android Marketplace. Search for 'WallSwitch'.

Sabtu, 25 April 2009

Registering for TIME_TICK After a Reboot in Android

Creating a service that will receive TIME_TICK, but also start on boot isn't immediately obvious. It took me a bit to figure out the best way to do it, so I figure it's worth sharing.




To start, you can't register your receiver to get TIME_TICK in the android manifest. The registration for TIME_TICK has to happen in code using Intent.registerReceiver. You can, however, define that your receiver has android.permission.RECEIVE_BOOT_COMPLETED and set your receiver to handle it, which will give you some control on boot. Here's the relevant portion of AndroidManifest.xml:





<application android:icon="@drawable/icon" android:label="@string/app_name"
android:enabled="true" android:debuggable="false">
<activity android:name=".AndroidMain" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="DemoService"></service>
<receiver android:name="DemoReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.TIME_TICK"></action>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>




This isn't enough, however, since your receiver can't register itself to listen to TIME_TICK. Intent.registerReceiver registers for the lifetime of the Intent it's called from. If we register it using the intent created for BOOT_COMPLETED, it's dead as soon as it exits the handler. Therefore, we need to start a background service that will keep running. This service then creates a new instance of the receiver and registers that for TIME_TICK.




DemoReceiver.java:



public class DemoReceiver extends BroadcastReceiver {
static final String LOGGING_TAG = "MyDemo";

@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().compareTo(Intent.ACTION_BOOT_COMPLETED) == 0){
Log.v(LOGGING_TAG, "DemoReceiver.onReceive(ACTION_BOOT_COMPLETED)");
context.startService(new Intent(context, DemoService.class));
}else if(intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0)
Log.v(LOGGING_TAG, "DemoReceiver.onReceive(ACTION_TIME_TICK)");
else
Log.v(LOGGING_TAG, "DemoReceiver.onReceive(" + intent.getAction() + ")");
}
}




DemoService.java:



public class DemoService extends Service {
static final String LOGGING_TAG = "MyDemo";

@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onStart(Intent intent, int startId){
super.onStart(intent, startId);
Log.v(LOGGING_TAG, "DemoService.onStart()");
}

@Override
public void onCreate(){
super.onCreate();
Log.v(LOGGING_TAG, "DemoService.onCreate()");

registerReceiver(
new DemoReceiver(),
new IntentFilter(Intent.ACTION_TIME_TICK));
}
}





If this all works correctly, we'll see log messages that look something like:




04-25 21:04:22.580: VERBOSE/MyDemo(182): DemoReceiver.onReceive(ACTION_BOOT_COMPLETED)
04-25 21:04:22.630: VERBOSE/MyDemo(182): DemoService.onCreate()
04-25 21:04:22.650: VERBOSE/MyDemo(182): DemoService.onStart()
04-25 21:05:00.140: VERBOSE/MyDemo(182): DemoReceiver.onReceive(ACTION_TIME_TICK)

Selasa, 14 April 2009

Image Processing in Android

While working on WallSwitch, I ran into a number of hairy problems with image processing. The worst, by far, was this:


04-15 02:20:34.693: ERROR/dalvikvm-heap(165): 50331648-byte external allocation too large for this process.
04-15 02:20:34.693: ERROR/(165): VM won't let us allocate 50331648 bytes
04-15 02:20:38.233: ERROR/AndroidRuntime(165): java.lang.OutOfMemoryError: bitmap size exceeds VM budget


I got it when trying to do a simple BitmapFactory.decodeFile() on a jpeg I had on the sd card. The jpeg was huge (~4MB) but that should exceed the 16MB heap I get, right? I found some decent help here and here, but nothing that really explained what was going on. I knew I was hitting the limit, but had no idea why.





Then, I remembered something a friend had told me a few years ago about how jpegs are compressed (duh) but that it had to first decompress to a bitmap before painting to your screen. It makes sense, after all. If I've got 1024x768 pixels on my monitor and I want to paint a picture over all of it, I'm going to need 768,432 bytes (depending on bit-depth).




I whipped out my calculator and had a facepalm moment. Needless to say 50,331,648 is 4096x6144 * 2, which corresponds to the size of my jpeg, when fully decompressed.




Fixing this was, happily, very easy. You just need to set inSampleSize on your BitmapFactory.Options to something useful. It'll sample the image you get back, returning something 1/2, 1/4, ... the size. The key here is to try to keep the sample size a power of two. It isn't necessary, but it makes the processing faster and it'll make sure the image you get back keeps the same proportions.





// First, get the dimensions of the image
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);

// Only scale if we need to
// (16384 buffer for img processing)
Boolean scaleByHeight = Math.abs(options.outHeight - targetHeight) >= Math.abs(options.outWidth - targetWidth);
if(options.outHeight * options.outWidth * 2 >= 16384){
// Load, scaling to smallest power of 2 that'll get it <= desired dimensions
double sampleSize = scaleByHeight
? options.outHeight / targetHeight
: options.outWidth / targetWidth;
options.inSampleSize =
(int)Math.pow(2d, Math.floor(
Math.log(sampleSize)/Math.log(2d)));
}

// Do the actual decoding
options.inJustDecodeBounds = false;
options.inTempStorage = new byte[IMG_BUFFER_LEN];
Bitmap output = BitmapFactory.decodeFile(filePath, options);


It's still a pretty slow operation to perform, but this at least makes it possible!