Friday, December 18, 2009

Hello, Stack Overflow!

Over the past year, an Android presence has been growing on a relatively new technical Q&A web site called Stack Overflow. The site was designed specifically for programmers, with features like syntax highlighting, tagging, user reputation, and community editing. It's attracted a loyal software developer community, and developers continue to express great praise for this new tool. Well, the Android team has been listening...and we agree.

Today, I'm happy to announce that we're working with Stack Overflow to improve developer support, especially for developers new to Android. In essence, the Android tag on Stack Overflow will become an official Android app development Q&A medium. We encourage you to post your beginner-level technical questions there. It's also important to point out that we don't plan to change the android-developers group, so intermediate and expert users should still feel free to post there.

I think that this will be a great new resource for novice Android developers, and our team is really excited to participate in the growth of the Android developer community on Stack Overflow. I hope to see you all there!

Back and other hard keys: three stories

Android 2.0 introduces new behavior and support for handling hard keys such as BACK and MENU, including some special features to support the virtual hard keys that are appearing on recent devices such as Droid.

This article will give you three stories on these changes: from the most simple to the gory details. Pick the one you prefer.

Story 1: Making things easier for developers

If you were to survey the base applications in the Android platform, you would notice a fairly common pattern: add a little bit of magic to intercept the BACK key and do something different. To do this right, the magic needs to look something like this:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
// do something on back.
return true;
}

return super.onKeyDown(keyCode, event);
}

How to intercept the BACK key in an Activity is also one of the common questions we see developers ask, so as of 2.0 we have a new little API to make this more simple and easier to discover and get right:

@Override
public void onBackPressed() {
// do something on back.
return;
}

If this is all you care about doing, and you're not worried about supporting versions of the platform before 2.0, then you can stop here. Otherwise, read on.

Story 2: Embracing long press

One of the fairly late addition to the Android platform was the use of long press on hard keys to perform alternative actions. In 1.0 this was long press on HOME for the recent apps switcher and long press on CALL for the voice dialer. In 1.1 we introduced long press on SEARCH for voice search, and 1.5 introduced long press on MENU to force the soft keyboard to be displayed as a backwards compatibility feature for applications that were not yet IME-aware.

(As an aside: long press on MENU was only intended for backwards compatibility, and thus has some perhaps surprising behavior in how strongly the soft keyboard stays up when it is used. This is not intended to be a standard way to access the soft keyboards, and all apps written today should have a more standard and visible way to bring up the IME if they need it.)

Unfortunately the evolution of this feature resulted in a less than optimal implementation: all of the long press detection was implemented in the client-side framework's default key handling code, using timed messages. This resulted in a lot of duplication of code and some behavior problems; since the actual event dispatching code had no concept of long presses and all timing for them was done on the main thread of the application, the application could be slow enough to not update within the long press timeout.

In Android 2.0 this all changes, with a real KeyEvent API and callback functions for long presses. These greatly simplify long press handling for applications, and allow them to interact correctly with the framework. For example: you can override Activity.onKeyLongPress() to supply your own action for a long press on one of the hard keys, overriding the default action provided by the framework.

Perhaps most significant for developers is a corresponding change in the semantics of the BACK key. Previously the default key handling executed the action for this key when it was pressed, unlike the other hard keys. In 2.0 the BACK key is now execute on key up. However, for existing apps, the framework will continue to execute the action on key down for compatibility reasons. To enable the new behavior in your app you must set android:targetSdkVersion in your manifest to 5 or greater.

Here is an example of code an Activity subclass can use to implement special actions for a long press and short press of the CALL key:

@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_CALL) {
// a long press of the call key.
// do our work, returning true to consume it. by
// returning true, the framework knows an action has
// been performed on the long press, so will set the
// canceled flag for the following up event.
return true;
}
return super.onKeyLongPress(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_CALL && event.isTracking()
&& !event.isCanceled()) {
// if the call key is being released, AND we are tracking
// it from an initial key down, AND it is not canceled,
// then handle it.
return true;
}
return super.onKeyUp(keyCode, event);
}

Note that the above code assumes we are implementing different behavior for a key that is normally processed by the framework. If you want to implement long presses for another key, you will also need to override onKeyDown to have the framework track it:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_0) {
// this tells the framework to start tracking for
// a long press and eventual key up. it will only
// do so if this is the first down (not a repeat).
event.startTracking();
return true;
}
return super.onKeyDown(keyCode, event);
}

Story 3: Making a mess with virtual keys

Now we come to the story of our original motivation for all of these changes: support for virtual hard keys, as seen on the Droid and other upcoming devices. Instead of physical buttons, these devices have a touch sensor that extends outside of the visible screen, creating an area for the "hard" keys to live as touch sensitive areas. The low-level input system looks for touches on the screen in this area, and turns these into "virtual" hard key events as appropriate.

To applications these basically look like real hard keys, though the generated events will have a new FLAG_VIRTUAL_HARD_KEY bit set to identify them. Regardless of that flag, in nearly all cases an application can handle these "hard" key events in the same way it has always done for real hard keys.

However, these keys introduce some wrinkles in user interaction. Most important is that the keys exist on the same surface as the rest of the user interface, and they can be easily pressed with the same kind of touches. This can become an issue, for example, when the virtual keys are along the bottom of the screen: a common gesture is to swipe up the screen for scrolling, and it can be very easy to accidentally touch a virtual key at the bottom when doing this.

The solution for this in 2.0 is to introduce a concept of a "canceled" key event. We've already seen this in the previous story, where handling a long press would cancel the following up event. In a similar way, moving from a virtual key press on to the screen will cause the virtual key to be canceled when it goes up.

In fact the previous code already takes care of this — by checking isCanceled() on the key up, canceled virtual keys and long presses will be ignored. There are also individual flags for these two cases, but they should rarely be used by applications and always with the understanding that in the future there may be more reasons for a key event to be canceled.

For existing application, where BACK key compatibility is turned on to execute the action on down, there is still the problem of accidentally detecting a back press when intending to perform a swipe. Though there is no solution for this except to update an application to specify it targets SDK version 5 or later, fortunately the back key is generally positioned on a far side of the virtual key area, so the user is much less likely to accidentally hit it than some of the other keys.

Writing an application that works well on pre-2.0 as well as 2.0 and later versions of the platform is also fairly easy for most common cases. For example, here is code that allows you to handle the back key in an activity correctly on all versions of the platform:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
// Take care of calling this method on earlier versions of
// the platform where it doesn't exist.
onBackPressed();
}

return super.onKeyDown(keyCode, event);
}

@Override
public void onBackPressed() {
// This will be called either automatically for you on 2.0
// or later, or by the code above on earlier versions of the
// platform.
return;
}

For the hard core: correctly dispatching events

One final topic that is worth covering is how to correctly handle events in the raw dispatch functions such as onDispatchEvent() or onPreIme(). These require a little more care, since you can't rely on some of the help the framework provides when it calls the higher-level functions such as onKeyDown(). The code below shows how you can intercept the dispatching of the BACK key such that you correctly execute your action when it is release.

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getRepeatCount() == 0) {

// Tell the framework to start tracking this event.
getKeyDispatcherState().startTracking(event, this);
return true;

} else if (event.getAction() == KeyEvent.ACTION_UP) {
getKeyDispatcherState().handleUpEvent(event);
if (event.isTracking() && !event.isCanceled()) {

// DO BACK ACTION HERE
return true;

}
}
return super.dispatchKeyEvent(event);
} else {
return super.dispatchKeyEvent(event);
}
}

The call to getKeyDispatcherState() returns an object that is used to track the current key state in your window. It is generally available on the View class, and an Activity can use any of its views to retrieve the object if needed.

Thursday, December 17, 2009

New resources and sample code on developer.android.com

Hey Android developers—if you've visited the online Android SDK documentation recently, you may have noticed a few changes. That's right, there's a new Resources tab, which was designed to take some of the load off the Developer's Guide. We've moved a number of existing resources to the Resources tab, including tutorials, sample code, and FAQs. We've also formalized a few of our most popular developer blog posts into technical articles; watch for more of these to appear in the future.

In addition, we just released a new batch of sample code, available now as a ZIP file download on the samples index page. And we're working on updating the way in which we distribute official sample code; more on that some other time.

New sample screenshots

The new sample code includes:

  • Multiple Resolutions: a simple example showing how to use resource directory qualifiers to support multiple screen configurations and Android SDK versions.
  • Wiktionary and WiktionarySimple: sample applications that illustrate how to create an interactive home screen widget.
  • Contact Manager: an example on using the new ContactsContract interface to query and manipulate a user's various accounts and contact providers.
  • Bluetooth Chat: a fun little demo that allows two users to have a 1 on 1 chat over Bluetooth. It demonstrates how to discover devices, initiate a connection, and transfer data.
  • API Demos > App > Activity > QuickContactsDemo: a demo showing how to use the android.widget.QuickContactsBadge class, new in Android 2.0.
  • API Demos > App > Activity > SetWallpaper: a demo showing how to use the new android.app.WallpaperManager class to allow users to change the system wallpaper.
  • API Demos > App > Text-To-Speech: a sample using Text-To-Speech (speech synthesis) to make your application talk.
  • NotePad (now with Live Folders): this sample now includes code for creating Live Folders.

We hope these new samples can be a valuable resource for learning some of the newer features in Android 1.6 and 2.0. Let us know in the android-developers Google Group if you have any questions about these new samples or about the new Resources tab.

Thanks for tuning in, and 'til next time, happy coding!

Knowing is half the battle

As a developer, I often wonder which Android platforms my applications should support,especially as the number of Android-powered devices grows. Should my application only focus on the latest version of the platform or should it support older ones as well?

To help with this kind of decision, I am excited to announce the new
device dashboard. It provides information about deployed Android-powered devices that is helpful to developers as they build and update their apps. The dashboard provides the relative distribution of Android platform versions on devices running Android Market.


Android PlatformPercentage of Devices
1.10.3%
1.527.7%
1.654.2%
2.02.9%
2.0.114.8%

The above graph shows the relative number of Android devices that have accessed Android Market during the first 14 days of December 2009.

From a developer's perspective, there are a number of interesting points on this graph:

  • At this point, there's little incentive to make sure a new application is
    backward compatible with Android 1.0 and Android 1.1.
  • Close to 30% of the devices are running Android 1.5. To take advantage of this significant install base, you may consider support for Android 1.5.
  • Starting with Android 1.6, devices can have different screen densities & sizes. There are several devices out there that fall in this category, so make sure to adapt your application to support different screen sizes and take advantage of devices with small, low density (e.g QVGA) and normal, high density (e.g. WVGA) screens. Note that Android Market will not list your application on small screen devices unless its manifest explicitly indicates support for "small" screen sizes. Make sure you properly configure the emulator and test your application on different screen sizes before uploading to Market.
  • A new SDK for Android 2.0.1 was released two weeks ago. All Android 2.0 devices will be updated to 2.0.1 before the end of the year, so if your application uses features specific to Android 2.0, you are encouraged to update it to take advantage of the latest Android 2.0.1 API instead.

In summary, Android 1.5, 1.6, and 2.0.1 are the 3 versions of the platform that are deployed in volume. Our goal is to provide you with the tools and information to make it easy for you to target specific versions of the platform or all the versions that are deployed in volume.

We plan to update the dashboard regularly to reflect deployment of new Android platforms. We also plan to expand the dashboard to include other information like devices per screen size and so on.

Friday, December 11, 2009

Come to Our Virtual Office Hours

Starting this week, we're going to be holding regular IRC office hours for Android app developers in the #android-dev channel on irc.freenode.net. Members of the Android team will be on hand to answer your technical questions. (Note that we will not be able to provide customer support for the phones themselves.)

We've arranged our office hours to accommodate as many different schedules as possible, for folks around the world. We will initially hold two sessions each week:

  • 12/15/09 Tuesday, 9 a.m. to 10 a.m. PST
  • 12/17/09, Thursday 5 p.m. to 6 p.m. PST
  • 12/22/09, Tuesday 9 a.m. to 10 a.m. PST
  • 01/06/10 Wednesday 9 a.m. to 10 a.m. PST
  • 01/07/10 Thursday 5 p.m. to 6 p.m. PST

Check Wikipedia for a helpful list of IRC clients. Alternatively, you could use a web interface such as the one at freenode.net. We will try to answer as many as we can get through in the hour.

We hope to see you there!

Thursday, December 10, 2009

Optimize your layouts



Writing user interface layouts for Android applications is easy, but it can sometimes be difficult to optimize them. Most often, heavy modifications made to existing XML layouts, like shuffling views around or changing the type of a container, lead to inefficiencies that go unnoticed.

Starting with the SDK Tools Revision 3 you can use a tool called layoutopt to automatically detect common problems. This tool is currently only available from the command line and its use is very simple - just open a terminal and launch the layoutopt command with a list of directories or XML files to analyze:


$ layoutopt samples/
samples/compound.xml
7:23 The root-level <FrameLayout/> can be replaced with <merge/>
11:21 This LinearLayout layout or its FrameLayout parent is useless samples/simple.xml
7:7 The root-level <FrameLayout/> can be replaced with <merge/>
samples/too_deep.xml
-1:-1 This layout has too many nested layouts: 13 levels, it should have <= 10!
20:81 This LinearLayout layout or its LinearLayout parent is useless
24:79 This LinearLayout layout or its LinearLayout parent is useless
28:77 This LinearLayout layout or its LinearLayout parent is useless
32:75 This LinearLayout layout or its LinearLayout parent is useless
36:73 This LinearLayout layout or its LinearLayout parent is useless
40:71 This LinearLayout layout or its LinearLayout parent is useless
44:69 This LinearLayout layout or its LinearLayout parent is useless
48:67 This LinearLayout layout or its LinearLayout parent is useless
52:65 This LinearLayout layout or its LinearLayout parent is useless
56:63 This LinearLayout layout or its LinearLayout parent is useless
samples/too_many.xml
7:413 The root-level <FrameLayout/> can be replaced with <merge/>
-1:-1 This layout has too many views: 81 views, it should have <= 80! samples/useless.xml
7:19 The root-level <FrameLayout/> can be replaced with <merge/>
11:17 This LinearLayout layout or its FrameLayout parent is useless
For each analyzed file, the tool will indicate the line numbers of each tag that could potentially be optimized. In some cases, layoutopt will also offer a possible solution.

The current version of layoutopt contains a dozen rules used to analyze your layout files and future versions will contain more. Future plans for this tool also include the ability to create and use your own analysis rules, to automatically modify the layouts with optimized XML, and to use it from within Eclipse and/or a standalone user interface.


Windows users: to start layoutopt, open the file called layoutopt.bat in the tools directory of the SDK and on the last line, replace %jarpath% with -jar %jarpath%.

Monday, December 7, 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();
    }
}


Thursday, December 3, 2009

Android SDK Updates

Today we are releasing updates to multiple components of the Android SDK:

  • Android 2.0.1, revision 1
  • Android 1.6, revision 2
  • SDK Tools, revision 4

Android 2.0.1 is a minor update to Android 2.0. This update includes several bug fixes and behavior changes, such as application resource selection based on API level and changes to the value of some Bluetooth-related constants. For more detailed information, please see the Android 2.0.1 release notes.

To differentiate its behavior from Android 2.0, the API level of Android 2.0.1 is 6. All Android 2.0 devices will be updated to 2.0.1 before the end of the year, so developers will no longer need to support Android 2.0 at that time. Of course, developers of applications affected by the behavior changes should start compiling and testing their apps immediately.

We are also providing an update to the Android 1.6 SDK component. Revision 2 includes fixes to the compatibility mode for applications that don't support multiple screen sizes, as well as SDK fixes. Please see the Android 1.6, revision 2 release notes for the full list of changes.

Finally, we are also releasing an update to the SDK Tools, now in revision 4. This is a minor update with mostly bug fixes in the SDK Manager. A new version of the Eclipse plug-in that embeds those fixes is also available. For complete details, please see the SDK Tools, revision 4 and ADT 0.9.5 release notes.

One more thing: you can now follow us on twitter @AndroidDev.

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");
    }
}


Wednesday, December 2, 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();       
    }
}


Monday, November 30, 2009

Announcing the Winners of ADC 2

Back in May at Google I/O, we announced ADC 2 -- the second Android Developer Challenge -- to encourage the development of cool apps that delight mobile users. We received many interesting and high-quality applications -- everything from exciting arcade games to nifty productivity utilities. We also saw apps that took advantage of openness of Android to enhance system behavior at a deep level to provide users with a greater degree of customization and utility. We were particularly pleased to see submissions from many smaller and independent developers.

Over the last couple of months, tens of thousands of Android users around the world reviewed and scored these applications. There were many great apps and the scores were very close. Together with our official panel of judges, these users have spoken and selected our winners!

I am pleased to present the ADC 2 winners gallery, which includes not only the top winners overall and in each category, but also all of the applications that made it to the top 200. There are a lot of great applications in addition to the top winners.

Thanks to everyone who submitted applications or helped us judge the entrants. We encourage all developers to submit their applications to Android Market where their app can be downloaded and enjoyed by Android users around the world.

Sunday, November 29, 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.

Tuesday, November 24, 2009

ADC 2 Public Judging is now closed

Thanks to tens of thousands of Android users around the world who participated in the review of ADC 2 finalist applications, we have now collected sufficient scores to complete Round 2 of public judging.

We are reviewing the final results and will announce the top winners this coming Monday, November 30. Thanks to all who've participated in ADC 2 and good luck to all the finalists.

Saturday, November 21, 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.

Friday, November 20, 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.

Wednesday, November 11, 2009

Integrating Application with Intents

Written in collaboration with Michael Burton, Mob.ly; Ivan Mitrovic, uLocate; and Josh Garnier, OpenTable.

OpenTable, uLocate, and Mob.ly worked together to create a great user experience on Android. We saw an opportunity to enable WHERE and GoodFood users to make reservations on OpenTable easily and seamlessly. This is a situation where everyone wins — OpenTable gets more traffic, WHERE and GoodFood gain functionality to make their applications stickier, and users benefit because they can make reservations with only a few taps of a finger. We were able to achieve this deep integration between our applications by using Android's Intent mechanism. Intents are perhaps one of Android's coolest, most unique, and under-appreciated features. Here's how we exploited them to compose a new user experience from parts each of us have.

Designing

One of the first steps is to design your Intent interface, or API. The main public Intent that OpenTable exposes is the RESERVE Intent, which lets you make a reservation at a specific restaurant and optionally specify the date, time, and party size.

Hereʼs an example of how to make a reservation using the RESERVE Intent:

startActivity(new Intent("com.opentable.action.RESERVE",
Uri.parse("reserve://opentable.com/2947?partySize=3")));

Our objective was to make it simple and clear to the developer using the Intent. So how did we decide what it would look like?

First, we needed an Action. We considered using Intent.ACTION_VIEW, but decided this didn't map well to making a reservation, so we made up a new action. Following the conventions of the Android platform (roughly <package-name>.action.<action-name>), we chose "com.opentable.action.RESERVE". Actions really are just strings, so it's important to namespace them. Not all applications will need to define their own actions. In fact, common actions such as Intent.ACTION_VIEW (aka "android.intent.action.VIEW") are often a better choice if youʼre not doing something unusual.

Next we needed to determine how data would be sent in our Intent. We decided to have the data encoded in a URI, although you might choose to receive your data as a collection of items in the Intent's data Bundle. We used a scheme of "reserve:" to be consistent with our action. We then put our domain authority and the restaurant ID into the URI path since it was required, and we shunted off all of the other, optional inputs to URI query parameters.

Exposing

Once we knew what we wanted the Intent to look like, we needed to register the Intent with the system so Android would know to start up the OpenTable application. This is done by inserting an Intent filter into the appropriate Activity declaration in AndroidManifest.xml:

<activity android:name=".activity.Splash" ... >
...
<intent-filter>
<action android:name="com.opentable.action.RESERVE"/>
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="reserve" android:host="opentable.com"/>
</intent-filter>
...
</activity>

In our case, we wanted users to see a brief OpenTable splash screen as we loaded up details about their restaurant selection, so we put the Intent Filter in the splash Activity definition. We set our category to be DEFAULT. This will ensure our application is launched without asking the user what application to use, as long as no other Activities also list themselves as default for this action.

Notice that things like the URI query parameter ("partySize" in our example) are not specified by the Intent filter. This is why documentation is key when defining your Intents, which weʼll talk about a bit later.

Processing

Now the only thing left to do was write the code to handle the intent.

    protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Uri uri;
final int restaurantId;
try {
uri = getIntent().getData();
restaurantId = Integer.parseInt( uri.getPathSegments().get(0));
} catch(Exception e) {
// Restaurant ID is required
Log.e(e);
startActivity( FindTable.start(FindTablePublic.this));
finish();
return;
}
final String partySize = uri.getQueryParameter("partySize");
...
}

Although this is not quite all the code, you get the idea. The hardest part here was the error handling. OpenTable wanted to be able to gracefully handle erroneous Intents that might be sent by partner applications, so if we have any problem parsing the restaurant ID, we pass the user off to another Activity where they can find the restaurant manually. It's important to verify the input just as you would in a desktop or web application to protect against injection attacks that might harm your app or your users.

Calling and Handling Uncertainty with Grace

Actually invoking the target application from within the requester is quite straight-forward, but there are a few cases we need to handle. What if OpenTable isn't installed? What if WHERE or GoodFood doesn't know the restaurant ID?



Restaurant ID knownRestaurant ID unknown
User has OpenTableCall OpenTable IntentDon't show reserve button
User doesn't have OpenTableCall Market IntentDon't show reserve button

You'll probably wish to work with your partner to decide exactly what to do if the user doesn't have the target application installed. In this case, we decided we would take the user to Android Market to download OpenTable if s/he wished to do so.

    public void showReserveButton() {

// setup the Intent to call OpenTable
Uri reserveUri = Uri.parse(String.format( "reserve://opentable.com/%s?refId=5449",
opentableId));
Intent opentableIntent = new Intent("com.opentable.action.RESERVE", reserveUri);

// setup the Intent to deep link into Android Market
Uri marketUri = Uri.parse("market://search?q=pname:com.opentable");
Intent marketIntent = new Intent(Intent.ACTION_VIEW).setData(marketUri);

opentableButton.setVisibility(opentableId > 0 ? View.VISIBLE : View.GONE);
opentableButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
PackageManager pm = getPackageManager();
startActivity(pm.queryIntentActivities(opentableIntent, 0).size() == 0 ?
opentableIntent : marketIntent);
}
});
}

In the case where the ID for the restaurant is unavailable, whether because they don't take reservations or they aren't part of the OpenTable network, we simply hide the reserve button.



Publishing the Intent Specification

Now that all the technical work is done, how can you get other developers to use your Intent-based API besides 1:1 outreach? The answer is simple: publish documentation on your website. This makes it more likely that other applications will link to your functionality and also makes your application available to a wider community than you might otherwise reach.

If there's an application that you'd like to tap into that doesn't have any published information, try contacting the developer. It's often in their best interest to encourage third parties to use their APIs, and if they already have an API sitting around, it might be simple to get you the documentation for it.

Summary

It's really just this simple. Now when any of us is in a new city or just around the neighborhood its easy to check which place is the new hot spot and immediately grab an available table. Its great to not need to find a restaurant in one application, launch OpenTable to see if there's a table, find out there isn't, launch the first application again, and on and on. We hope you'll find this write-up useful as you develop your own public intents and that you'll consider sharing them with the greater Android community.

Monday, November 9, 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.