5 Best Android Music Player Apps

admin

Music has that healing element which never fails to sooth an aching person. Whatever it is, it is undeniably true that people crave for music. And so, it is not equally surprising to see business establishments catering the wants of humanity. All around the world, you can see different kinds of music players flooding in the market. Among the gadgets offering techie music to the consumers, are the powerful Android-powered devices. With the Android software living in your gadget, you can always have access to an incredible number of music apps in the market. Five of the best are listed below:

1. Double Twist Player

Double Twist is currently the best music application available in the market. With this app, you can find all kinds of music you want on your Android phone. But what's more amazing is that you can synchronize your Droid with a desktop PC via Wi-Fi connection to detect music files. If you are a MAC OS user, you can use iTunes to synchronize with your Android device. The good news is that the basic functionalities of this app are available for free

2. TuneWiki

If there's a Wiki in the Internet, there's also a Wiki in the Android market. If you own an Android, you should never let go of this must-have music player because this is the only music app with lyrics and social network for music discovery. TuneWiki allows you to see song lyrics in your device while the song is being played. Moreover, this app can translate the lyrics into 40 different languages. Pretty superior, huh? With TuneWiki, you can also find and follow users to check what they are listening. Also, this app gives you the choice to search for great songs through song maps and top charts that are updated periodically.

3. PowerAmp

If you're looking for a powerful music app, then you must not forget to include PowerAmp in your list. This music app plays a number of files in your device, including MP3, FLAC, ALAC, WAV and WMA. It also comes with a 10 band equalizer which has presets and separate treble and bass adjusters, a sleep timer for pausing in between songs, and an album art finder and tag editor. Worthy to mention is that this app also allows you to browse and play songs either from specified folders on your device or from the automatically generated Android library. Lastly, PowerAmp comes with several home screen widgets for fast music control, a Last.fm scrobbling which is built-in, and lock screen controls. Obviously, PowerAmp has lived by its name.

4. PlayerPro

PlayerPro allows you to browse your music by albums, artists, songs, genres, playlists and folders. With this music app, you can download, search and save lyrics in your Android device. The bonus part is that this player routinely downloads appropriate album art and artist photos, saving you a lot of time. This app also comes with mixable audio effects for devices powered by an Android platform. It has a 5-band graphic equalizer with a lot of presets, on top of other features such as stereo widening, bass boost, reverb and volume control.

5. WinAmp

Among the list, this app might have been the oldest but still, it's one of the best. WinAmp currently found its way from the huge desktop PCs to the modern Android devices. Aside from enabling you to play, manage, and sync music from your PC to your Android, the current WinAmp also offers a complete music management solution featuring a wireless desktop sync (take note that WinAmp 5.6 is required), an iTunes library import, and an access to thousands of Internet radio stations. Clearly, WinAmp has made its own music revolution to serve the modern genre.

If the above apps do not suit your needs, then you can always have a glimpse on other music player apps in the Android market. However, chances are you would still find yourself going back to this list. So far, these are the apps tried and tested as the best by Android users. When it comes to music apps, surely, you would be wading in the same boat.

5 Great Android Apps for Amazing Video Conferencing

admin

Video conferencing makes our lives easier. Connecting with people from school and business has also been made possible because of video conferencing. In line with this, Android also allows its devices to do just that. In no particular order, here are 5 Great Android apps for Amazing Video conferencing:

1. Qik Video Connect

The Android Qik's interface is different with that of its iOs counterpart. The Android version has four blocks on its screen each representing a certain function with its description. Its functions include Video Chat, Record and Share, Video Mail and Video Gallery. Although the Android version differs with the iOs version in its appearance, both have the same functionality.

Aside from its Video Chat function, another thing which you may find interesting is the Video mail. It's just like the Voice Mail but this time, it uses video. An advantage of the Video Mail is that the quality of the video is better than that of the live video chat since it is pre-recorded. The bad news is that you may not be able to use this service for free after June 1 since they will be charging an annual fee for this service.

With Qik, you can also upload your videos to the web and share them via email and SMS. Although Qik has good features, it may not have the best video chat experience. Right now, however, Qik is one of the best options among Video Conferencing Android apps.

2. Tango

The good thing about Tango is that it allows it users to have a cross-platform video chat. That means you can have a video chat with a friend using an iOs even if you're on Android-very cool indeed! Although Fring has this capability, Tango scores more points when it comes to video quality and ease of use. With Tango, one can also make calls over 3G and 4G networks as well.

Finding your friends using Tango is also made convenient by this app. Tango can search through your Android or iPhone Address book for friends who are on Tango and adds them into the app's contact list. Also, setup of this app is quite easy.

3. Fring

Fring is user-friendly. Its interface is neat and not cluttered. Even a first-time user wouldn't have a problem getting to know the app. Video Quality is good although not as good as FaceTime (iPhone). Its audio still has more room for improvement. The good thing, though, is that it can be downloaded from the Android website for free.

4. Knocking Live Video

Knocking Live Video lets its user share live video from his phone to another one's. This Video-sharing app used to be available only in the iPhone. Now, it's in Android-good news for Android enthusiasts! This is a cross-platform app which means that an Android user can share live videos to a family or friend who's using the iPhone. It's one of the most popular social network apps today and you can download this app for free.

5. Skype

Skype is undeniably one of the best in VoIP apps around. Unfortunately, Android Skype doesn't have video conferencing with the exception of 4G phones. A lot are hopeful though that this service would extend to non-4G phones in the near future.

Android Development

admin

Google's android technology is an interesting, thought-provoking one that has android development gaining momentum across the world. A simple search on android brings out thousands of pages all discussing the potential this new piece of technology is giving the android application developer.

There are tutorials and articles, even sample codes that all serve the purpose of empowering the android application developer and implement various features of their creative software works. On some specific websites , sample codes offered include those of real-world android platform applications, that one can make and deploy. These codes clearly show all the amazing techniques in use in the android development environment.

There are also numerous articles with loads of tips, optimization strategies and DIY / how-to pieces, that give you the knowledge-base to further understand this particular environment as an android app developer. Tutorials seek to take you through the basics of what an android app is to more advanced-level skills in application development using the technology on offer.

You could also download the android software development kit (SDK) that runs on Windows, Linux as well as Mac OS. It is pretty much easy to set up this SDK. First you need a PC with appropriate features. On Windows, you just install the SDK much the same way as you install any other software on a Windows-based system. After this, you will ready to explore what the android development kit contains. You will get to know the basics on what an android application developer needs to know, what the Android SDK offers and how to integrate whatever application you may have into the overall platform.

Another thing included in this SDK is what is known as the framework topics. These take you through all the baby steps through to internalizing what APIs you may need to advanced skills like user interface development and data manipulation on the android platform.

The android market topics aim at showing you how to not only publish your application as an android app developer, but also the steps to take to ensure you earn from your ideas.

It is important to note that like any other application development platform, android is also fast changing, with various versions out. So you need to appraise yourself on what is current and what may not necessarily work out well. At the present, an android application developer would require the all-new Android 3.2 platform.

In a nut-shell, android development is like a blank slate for an astute android application developer. You can turn nothing into something and earn from it!

Android Programming

admin

Android applications development features a software improvement kit (SDK) and supplies a variety of libraries and tools. The software improvement package offers a complete set of tools to design the consumer interface for software and likewise to develop and debug software code. Android functions improvement assists in creating new and unique applications for many who use mobiles with Android platform.

The chances are infinite with Android Utility Improvement to push up the extent of flexibility. We rent a set of sensible Android Software developer's crew who attempt to be specialised on Android and are serving our beneficial clients to construct Customized Utility on Android, worldwide. It also allows units to communicate with one another for enabling social applications. It also helps builders to combine information of the consumer like contacts, geographic location & calendar to offer user more relevant experience. This app may make it easier to finish your building project on time with out extending your budget. It additionally has the function of in-app purchase for all items.

Our Google Android app developers have developed and deployed many functions starting from personalised apps to enterprise stage Android apps. Android recreation improvement is intrinsic part of our Android internet utility improvement companies and developers have mastered the art of crafting elegant games that sparkle on you Android phone. We will develop completely different sort of sensible applications that synchronize Internet and mobile platforms. The emerging Android pill phase will further enable penetration of PCs and low cost computing units for mobile computing purposes that may otherwise require a personal computer. For example, a restaurant supervisor might very nicely take orders utilizing the android pill or the doctor at a hospital could make efficient use of EMR (Electronic Medical Information) utilizing android pill based mostly apps requiring minimal keyboard interaction.

Android is a fast emerging platform for cell growth and has a really fast rising mobile market; this raises the bar as one needs to be technically sound and imaginatively progressive to seize some of its share. Every single day we see new and fresh innovative ways on how an organization can make it big by the social media market. An enterprise can only run efficiently if it has the gasoline of the customers or purchasers, and the social media is an effective way to get that needed fuel.

After mulling over the significance of being experience we determined to specialise in Android utility growth and gratify the users fully by serving their function of custom Android application. Following is the listing of versatile classes of android purposes that we work upon. Ask about getting your development environment arrange, get assist with the first steps of Android improvement (your first User Interface, your first permission, your first file on the Android file system, your first app on the Android Market.). Be sure you examine the archives first earlier than asking new questions. This legal professional's quiz app presents random regulation a question after which collects the consumer response. Upon completion it presents the person with a summary of how they did.

If you have a cell application development concept that you simply need to convert into outstanding Mobile software, we're here to help you. Our skilled Cellular Utility Improvement Specialists will coordinate with you, perceive your requirements, contribute their ideas, give you your best suited needs and get the Cellular Software ready for you. To know more about how we develop your dream android mobile software contact us now.

Commerce Tracking with Google Analytics for Android

admin



Today we released a new version of the Google Analytics Android SDK which includes support for tracking e-commerce transactions. This post walks you through setting it up in your mobile application.

Why It’s Important

If you allow users to purchase goods in your application, you’ll want to understand how much revenue your application generates as well as which products are most popular.
With the new e-commerce tracking functionality in the Google Analytics Android SDK, this is easy.

Before You Begin

In this post, we assume you’ve already configured the Google Analytics Android SDK to work in your application. Check out our SDK docs if you haven’t already.
We also assume you have a Google Analytics tracking object instance declared in your code:
GoogleAnalyticsTracker tracker;
Then in the activity’s onCreate method, you have initialized the tracker member variable and called start:
tracker = GoogleAnalyticsTracker.getInstance();
tracker.start("UA-YOUR-ACCOUNT-HERE", 30, this);

Setting Up The Code

The best way to track a transaction is when you’ve received confirmation for a purchase. For example, if you have a callback method that is called when a purchase is confirmed, you would call the tracking code there.
public void onPurchaseConfirmed(List purchases) {
// Use Google Analytics to record the purchase information here...
}

Tracking The Transaction

The Google Analytics Android SDK provides its own Transaction object to store values Google Analytics collects. The next step is to copy the values from the list of PurchaseObjects into a Transaction object.
The SDK’s Transaction object uses the builder pattern, where the constructor takes the required arguments and the optional arguments are set using setters:
Transaction.Builder builder = new Transaction.Builder(
purchase.getOrderId(),
purchase.getTotal())
.setTotalTax(purchase.getTotalTax())
.setShippingCost(purchase.getShippingCost()
.setStoreName(purchase.getStoreName());
You then add the transaction by building it and passing it to a Google Analytics tracking Object:
tracker.addTransaction(builder.build());

Tracking Each Item

The next step is to track each item within the transaction. This is similar to tracking transactions, using the Item class provided by the Google Analytics SDK for Android. Google Analytics uses the OrderID as a common ID to associate a set of items to it’s parent transaction.
Let’s say the PurchaseObject above has a list of one or more LineItem objects. You can then iterate through each LineItem and create and add the item to the tracker.
for (ListItem listItem : purchase.getListItems()) {
Item.Builder itemBuilder = new Item.Builder(
purchase.getOrderId(),
listItem.getItemSKU(),
listItem.getPrice(),
listItem.getCount())
.setItemCategory(listItem.getItemCategory())
.setItemName(listItem.getItemName());

// Now add the item to the tracker. The order ID is the key
// Google Analytics uses to associate this item to the transaction.
tracker.addItem(itemBuilder.build());
}

Sending the Data to Google Analytics

Finally once all the transactions and items have been added to the tracker, you call:
tracker.trackTransactions();
This sends the transactions to the dispatcher, which will transmit the data to Google Analytics.

Viewing The Reports

Once data has been collected, you can then log into the Google Analytics Web Interface and go to the Conversions > Ecommerce > Product Performance report to see how much revenue each product generated.

Here we see that many people bought potions, which generated the most revenue for our application. Also, more people bought the blue sword than the red sword, which could mean we need to stock more blue items in our application. Awesome!

Learning More

You can learn more about the new e-commerce tracking feature in the Google Analytics SDK for Android developer documentation.
What’s even better is that we’ll be demoing all this new functionality this year at Google IO, in the Optimizing Android Apps With Google Analytics session.

New Tools For Managing Screen Sizes

admin

Android 3.2 includes new tools for supporting devices with a wide range of screen sizes. One important result is better support for a new size of screen; what is typically called a “7-inch” tablet. This release also offers several new APIs to simplify developers’ work in adjusting to different screen sizes.
This a long post. We start by discussing the why and how of Android “dp” arithmetic, and the finer points of the screen-size buckets. If you know all that stuff, you can skip down to “Introducing Numeric Selectors” to read about what’s new. We also provide our recommendations for how you can do layout selection in apps targeted at Android 3.2 and higher in a way that should allow you to support the maximum number of device geometries with the minimum amount of effort.
Of course, the official write-up on Supporting Multiple Screens is also required reading for people working in this space.

Understanding Screen Densities and the “dp”

Resolution is the actual number of pixels available in the display, density is how many pixels appear within a constant area of the display, and size is the amount of physical space available for displaying your interface. These are interrelated: increase the resolution and density together, and size stays about the same. This is why the 320x480 screen on a G1 and 480x800 screen on a Droid are both the same screen size: the 480x800 screen has more pixels, but it is also higher density.
To remove the size/density calculations from the picture, the Android framework works wherever possible in terms of "dp" units, which are corrected for density. In medium-density ("mdpi") screens, which correspond to the original Android phones, physical pixels are identical to dp's; the devices’ dimensions are 320x480 in either scale. A more recent phone might have physical-pixel dimensions of 480x800 but be a high-density device. The conversion factor from hdpi to mdpi in this case is 1.5, so for a developer's purposes, the device is 320x533 in dp's.

Screen-size Buckets

Android has included support for three screen-size “buckets” since 1.6, based on these “dp” units: “normal” is currently the most popular device format (originally 320x480, more recently higher-density 480x800); “small” is for smaller screens, and “large” is for “substantially larger” screens. Devices that fall in the “large” bucket include the Dell Streak and original 7” Samsung Galaxy Tab. Android 2.3 introduced a new bucket size “xlarge”, in preparation for the approximately-10” tablets (such as the Motorola Xoom) that Android 3.0 was designed to support.
The definitions are:
  • xlarge screens are at least 960dp x 720dp.
  • large screens are at least 640dp x 480dp.
  • normal screens are at least 470dp x 320dp.
  • small screens are at least 426dp x 320dp. (Android does not currently support screens smaller than this.)
Here are some more examples of how this works with real screens:
  • A QVGA screen is 320x240 ldpi. Converting to mdpi (a 4/3 scaling factor) gives us 426dp x 320dp; this matches the minimum size above for the small screen bucket.
  • The Xoom is a typical 10” tablet with a 1280x800 mdpi screen. This places it into the xlarge screen bucket.
  • The Dell Streak is a 800x480 mdpi screen. This places it into the bottom of the large size bucket.
  • A typical 7” tablet has a 1024x600 mdpi screen. This also counts as a large screen.
  • The original Samsung Galaxy Tab is an interesting case. Physically it is a 1024x600 7” screen and thus classified as “large”. However the device configures its screen as hdpi, which means after applying the appropriate ⅔ scaling factor the actual space on the screen is 682dp x 400dp. This actually moves it out of the “large” bucket and into a “normal” screen size. The Tab actually reports that it is “large”; this was a mistake in the framework’s computation of the size for that device that we made. Today no devices should ship like this.

Issues With Buckets

Based on developers’ experience so far, we’re not convinced that this limited set of screen-size buckets gives developers everything they need in adapting to the increasing variety of Android-device shapes and sizes. The primary problem is that the borders between the buckets may not always correspond to either devices available to consumers or to the particular needs of apps.
The “normal” and “xlarge” screen sizes should be fairly straightforward as a target: “normal” screens generally require single panes of information that the user moves between, while “xlarge” screens can comfortably hold multi-pane UIs (even in portrait orientation, with some tightening of the space).
The “small” screen size is really an artifact of the original Android devices having 320x480 screens. 240x320 screens have a shorter aspect ratio, and applications that don’t take this into account can break on them. These days it is good practice to test user interfaces on a small screen to ensure there are no serious problems.
The “large” screen size has been challenging for developers — you will notice that it encompases everything from the Dell Streak to the original Galaxy Tab to 7" tablets in general. Different applications may also reasonably want to take different approaches to these two devices; it is also quite reasonable to want to have different behavior for landscape vs. portrait large devices because landscape has plenty of space for a multi-pane UI, while portrait may not.

Introducing Numeric Selectors

Android 3.2 introduces a new approach to screen sizes, with the goal of making developers' lives easier. We have defined a set of numbers describing device screen sizes, which you can use to select resources or otherwise adjust your UI. We believe that using these will not only reduce developers’ workloads, but future-proof their apps significantly.
The numbers describing the screen size are all in “dp” units (remember that your layout dimensions should also be in dp units so that the system can adjust for screen density). They are:
  • width dp: the current width available for application layout in “dp” units; changes when the screen switches orientation between landscape and portrait.
  • height dp: the current height available for application layout in “dp” units; also changes when the screen switches orientation.
  • smallest width dp: the smallest width available for application layout in “dp” units; this is the smallest width dp that you will ever encounter in any rotation of the display.
Of these, smallest width dp is the most important. It replaces the old screen-size buckets with a continuous range of numbers giving the effective size. This number is based on width because that is fairly universally the driving factor in designing a layout. A UI will often scroll vertically, but have fairly hard constraints on the minimum space it needs horizontally; the available width is also the key factor in determining whether to use a phone-style one-pane layout or tablet-style multi-pane layout.
Typical numbers for screen width dp are:
  • 320: a phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
  • 480: a tweener tablet like the Streak (480x800 mdpi).
  • 600: a 7” tablet (600x1024).
  • 720: a 10” tablet (720x1280, 800x1280, etc).

Using the New Selectors

When you are designing your UI, the main thing you probably care about is where you switch between a phone-style UI and a tablet-style multi-pane UI. The exact point of this switch will depend on your particular design — maybe you need a full 720dp width for your tablet layout, maybe 600dp is enough, or 480dp, or even some other number between those. Either pick a width and design to it; or after doing your design, find the smallest width it supports.
Now you can select your layout resources for phones vs. tablets using the number you want. For example, if 600dp is the smallest width for your tablet UI, you can do this:
res/layout/main_activity.xml           # For phones
res/layout-sw600dp/main_activity.xml   # For tablets
For the rare case where you want to further customize your UI, for example for 7” vs. 10” tablets, you can define additional smallest widths:
res/layout/main_activity.xml           # For phones
res/layout-sw600dp/main_activity.xml   # For 7” tablets
res/layout-sw720dp/main_activity.xml   # For 10” tablets
Android will pick the resource that is closest to the device’s “smallest width,” without being larger; so for a hypothetical 700dp x 1200dp tablet, it would pick layout-sw600dp.
If you want to get fancier, you can make a layout that can change when the user switches orientation to the one that best fits in the current available width. This can be of particular use for 7” tablets, where a multi-pane layout is a very tight fit in portrait::
res/layout/main_activity.xml          # Single-pane
res/layout-w600dp/main_activity.xml   # Multi-pane when enough width
Or the previous three-layout example could use this to switch to the full UI whenever there is enough width:
res/layout/main_activity.xml                 # For phones
res/layout-sw600dp/main_activity.xml         # Tablets
res/layout-sw600dp-w720dp/main_activity.xml  # Large width
In the setup above, we will always use the phone layout for devices whose smallest width is less than 600dp; for devices whose smallest width is at least 600dp, we will switch between the tablet and large width layouts depending on the current available width.
You can also mix in other resource qualifiers:
res/layout/main_activity.xml                 # For phones
res/layout-sw600dp/main_activity.xml         # Tablets
res/layout-sw600dp-port/main_activity.xml    # Tablets when portrait

Selector Precedence

While it is safest to specify multiple configurations like this to avoid potential ambiguity, you can also take advantage of some subtleties of resource matching. For example, the order that resource qualifiers must be specified in the directory name (documented in Providing Resources) is also the order of their “importance.” Earlier ones are more important than later ones. You can take advantage of this to, for example, easily have a landscape orientation specialization for your default layout:
res/layout/main_activity.xml                 # For phones
res/layout-land/main_activity.xml            # For phones when landscape
res/layout-sw600dp/main_activity.xml         # Tablets
In this case when running on a tablet that is using landscape orientation, the last layout will be used because the “swNNNdp” qualifier is a better match than “port”.

Combinations and Versions

One final thing we need to address is specifying layouts that work on both Android 3.2 and up as well as previous versions of the platform.
Previous versions of the platform will ignore any resources using the new resource qualifiers. This, then, is one approach that will work:
res/layout/main_activity.xml           # For phones
res/layout-xlarge/main_activity.xml    # For pre-3.2 tablets
res/layout-sw600dp/main_activity.xml   # For 3.2 and up tablets
This does require, however, that you have two copies of your tablet layout. One way to avoid this is by defining the tablet layout once as a distinct resource, and then making new versions of the original layout resource that point to it. So the layout resources we would have are:
res/layout/main_activity.xml           # For phones
res/layout/main_activity_tablet.xml    # For tablets
To have the original layout point to the tablet version, you put <item> specifications in the appropriate values directories. That is these two files:
res/values-xlarge/layout.xml
res/values-sw600dp/layout.xml
Both would contain the following XML defining the desired resource:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="layout" name="main_activty">
@layout/main_activity_tablet
</item>
</resources>
Of course, you can always simply select the resource to use in code. That is, define two or more resources like “layout/main_activity” and “layout/main_activity_tablet,” and select the one to use in your code based on information in the Configuration object or elsewhere. For example:
public class MyActivity extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate();

Configuration config = getResources().getConfiguration();
if (config.smallestScreenWidthDp >= 600) {
setContentView(R.layout.main_activity_tablet);
} else {
setContentView(R.layout.main_activity);
}
}
}

Conclusion

We strongly recommend that developers start using the new layout selectors for apps targeted at Android release 3.2 or higher, as we will be doing for Google apps. We think they will make your layout choices easier to express and manage.
Furthermore, we can see a remarkably wide variety of Android-device form factors coming down the pipe. This is a good thing, and will expand the market for your work. These new layout selectors are specifically designed to make it straightforward for you to make your apps run well in a future hardware ecosystem which is full of variety (and surprises).

Android Developer Labs 2011

admin

We in Android Developer Relations have been cooking up a rather special set of Android Developer Labs (ADLs) for the second half of 2011, and we’re ready to start the ball rolling.
Here’s the schedule. These are one-day events, so in Seattle and New York we’re running it twice for two audiences.

  • Bangalore — August 2 (happening today)
  • Seattle — August 15 and 16
  • New York — August 23 and 24
  • Los Angeles — September 2
This ADL series isn’t another set of introduction-to-Android sessions, nor any other kind of general overview. It's specifically aimed at optimizing Android apps for tablets, in particular creating high-quality tablet apps with an emphasis on polish and user-experience.
Registration is a two-step process. Anyone can register, but we can only accommodate a relatively small number of attendees from among the registrants, based on whether they already have an Android app with the potential to be a top-tier tablet app in terms of quality, fit, and finish. The goal is to bring your app to the ADL, and leave equipped to make it into one that makes Android tablet users smile.
Do you think you qualify? Sign up and show us!

Custom Class Loading in Dalvik

admin

The Dalvik VM provides facilities for developers to perform custom class loading. Instead of loading Dalvik executable (“dex”) files from the default location, an application can load them from alternative locations such as internal storage or over the network.
This technique is not for every application; In fact, most do just fine without it. However, there are situations where custom class loading can come in handy. Here are a couple of scenarios:

  • Big apps can contain more than 64K method references, which is the maximum number of supported in a dex file. To get around this limitation, developers can partition part of the program into multiple secondary dex files, and load them at runtime.
  • Frameworks can be designed to make their execution logic extensible by dynamic code loading at runtime.
We have created a sample app to demonstrate the partitioning of dex files and runtime class loading. (Note that for reasons discussed below, the app cannot be built with the ADT Eclipse plug-in. Instead, use the included Ant build script. See Readme.txt for detail.)
The app has a simple Activity that invokes a library component to display a Toast. The Activity and its resources are kept in the default dex, whereas the library code is stored in a secondary dex bundled in the APK. This requires a modified build process, which is shown below in detail.
Before the library method can be invoked, the app has to first explicitly load the secondary dex file. Let’s take a look at the relevant moving parts.

Code Organization

The application consists of 3 classes.
  • com.example.dex.MainActivity: UI component from which the library is invoked
  • com.example.dex.LibraryInterface: Interface definition for the library
  • com.example.dex.lib.LibraryProvider: Implementation of the library
The library is packaged in a secondary dex, while the rest of the classes are included in the default (primary) dex file. The “Build process” section below illustrates how to accomplish this. Of course, the packaging decision is dependent on the particular scenario a developer is dealing with.

Class loading and method invocation

The secondary dex file, containing LibraryProvider, is stored as an application asset. First, it has to be copied to a storage location whose path can be supplied to the class loader. The sample app uses the app’s private internal storage area for this purpose. (Technically, external storage would also work, but one has to consider the security implications of keeping application binaries there.)
Below is a snippet from MainActivity where standard file I/O is used to accomplish the copying.
  // Before the secondary dex file can be processed by the DexClassLoader,
// it has to be first copied from asset resource to a storage location.
File dexInternalStoragePath = new File(getDir("dex", Context.MODE_PRIVATE),
SECONDARY_DEX_NAME);
...
BufferedInputStream bis = null;
OutputStream dexWriter = null;

static final int BUF_SIZE = 8 * 1024;
try {
bis = new BufferedInputStream(getAssets().open(SECONDARY_DEX_NAME));
dexWriter = new BufferedOutputStream(
new FileOutputStream(dexInternalStoragePath));
byte[] buf = new byte[BUF_SIZE];
int len;
while((len = bis.read(buf, 0, BUF_SIZE)) > 0) {
dexWriter.write(buf, 0, len);
}
dexWriter.close();
bis.close();

} catch (. . .) {...}
Next, a DexClassLoader is instantiated to load the library from the extracted secondary dex file. There are a couple of ways to invoke methods on classes loaded in this manner. In this sample, the class instance is cast to an interface through which the method is called directly.
Another approach is to invoke methods using the reflection API. The advantage of using reflection is that it doesn’t require the secondary dex file to implement any particular interfaces. However, one should be aware that reflection is verbose and slow.
  // Internal storage where the DexClassLoader writes the optimized dex file to
final File optimizedDexOutputPath = getDir("outdex", Context.MODE_PRIVATE);

DexClassLoader cl = new DexClassLoader(dexInternalStoragePath.getAbsolutePath(),
optimizedDexOutputPath.getAbsolutePath(),
null,
getClassLoader());
Class libProviderClazz = null;
try {
// Load the library.
libProviderClazz =
cl.loadClass("com.example.dex.lib.LibraryProvider");
// Cast the return object to the library interface so that the
// caller can directly invoke methods in the interface.
// Alternatively, the caller can invoke methods through reflection,
// which is more verbose. 
LibraryInterface lib = (LibraryInterface) libProviderClazz.newInstance();
lib.showAwesomeToast(this, "hello");
} catch (Exception e) { ... }

Build Process

In order to churn out two separate dex files, we need to tweak the standard build process. To do the trick, we simply modify the “-dex” target in the project’s Ant build.xml.
The modified “-dex” target performs the following operations:
  1. Create two staging directories to store .class files to be converted to the default dex and the secondary dex.
  2. Selectively copy .class files from PROJECT_ROOT/bin/classes to the two staging directories.
          <!-- Primary dex to include everything but the concrete library
    implementation. -->
    <copy todir="${out.classes.absolute.dir}.1" >
    <fileset dir="${out.classes.absolute.dir}" >
    <exclude name="com/example/dex/lib/**" />
    </fileset>
    </copy>
    <!-- Secondary dex to include the concrete library implementation. -->
    <copy todir="${out.classes.absolute.dir}.2" >
    <fileset dir="${out.classes.absolute.dir}" >
    <include name="com/example/dex/lib/**" />
    </fileset>
    </copy>     
  3. Convert .class files from the two staging directories into two separate dex files.
  4. Add the secondary dex file to a jar file, which is the expected input format for the DexClassLoader. Lastly, store the jar file in the “assets” directory of the project.
        <!-- Package the output in the assets directory of the apk. -->
    <jar destfile="${asset.absolute.dir}/secondary_dex.jar"
    basedir="${out.absolute.dir}/secondary_dex_dir"
    includes="classes.dex" />
To kick-off the build, you execute ant debug (or release) from the project root directory.
That’s it! In the right situations, dynamic class loading can be quite useful.

Horizontal View Swiping with ViewPager

admin

Whether you have just started out in Android app development or are a veteran of the craft, it probably won’t be too long before you’ll need to implement horizontally scrolling sets of views. Many existing Android apps already use this UI pattern, such as the new Android Market, Google Docs and Google+. ViewPager standardizes the implementation.
ViewPager was released as part of the Compatibility Package revision 3 and works with Android 1.6 upwards. After following the instructions to obtain the package you can right-click on your Android project in Eclipse, choose ‘Android Tools’ and ‘Add Compatibility Library’, making the new classes available.

ViewPager is a ViewGroup and works in a similar manner to AdapterViews (like ListView and Gallery) so it shouldn’t feel too foreign. Note that if you use ViewPager in an xml layout, be sure to use the full class reference, e.g.

 <android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
… />
ViewPagers source their views from PagerAdapters which give you have full control over the reuse and recycling of the views. A PagerAdapter implementation called FragmentPagerAdapter is provided to facilitate the use of Fragments in a ViewPager; This is immensely powerful and as simple as implementing getCount() and getItem(). There is a sample called Fragment Pager Support provided in the Support Demos to illustrate this.
    public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}

@Override
public int getCount() {
return NUM_ITEMS;
}

@Override
public Fragment getItem(int position) {
return ArrayListFragment.newInstance(position);
}
}
FragmentPagerAdapter will detach each fragment as you swipe through the list, but keep them in memory so they can simply be reattached when the user swipes back. If you have a larger number of Fragments, the FragmentStatePagerAdapter is worth considering as it will remove them, with the downside being they need to be rebuilt as the user swipes back to them. So, if you have fewer, more complex fragments the FragmentPagerAdapter makes sense, but consider FragmentStatePagerAdapter for larger sets.
On the more simplistic side I recently wrote a ViewPager/PagerAdapter example that serves up simple TextViews. One thing to note is that if you are implementing your own PagerAdapter it is up to you, the developer, to add and remove your views to and from the ViewGroup. To facilitate this the ViewPager is passed into the PagerAdapter methods instantiateItem() and destroyItem().
    @Override
public Object instantiateItem(View collection, int position) {
View v = layoutInflater.inflate(...);
...
((ViewPager) collection).addView(v,0);
return tv;
}

@Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((TextView) view);
}
The source code for ViewPager is also included and available in <android-sdk>/extras/android/compatibility/v4/src. It is worth checking as you can generate the reference documentation from it using Javadoc. In the reference docs / source you’ll find other useful methods, for example setOnPageChangeListener(), which enables your application to track which View is currently visible.
If you are launching an app onto Android Market that uses ViewPager then please ping me on Google+ or Twitter, I’d love to see how widely it is being used and the innovative scenarios in which it appears.

Preview of Google TV Add-on for the Android SDK

admin

 At Google I/O, we announced that Android Market is coming to Google TV. Today, we’re announcing a preview of the Google TV Add-on for the Android SDK. With the upcoming OS update to Honeycomb, Google TV devices will be Android compatible. That means developers can build great new Android apps for TV, optimize existing mobile or tablet apps for TV, and distribute those apps through Android Market.
While the add-on does not contain all features of Google TV, it enables developers to emulate Google TV and build apps using standard Android SDK tools. It also provides new APIs for TV interaction, such as TV channel line-up. Google TV emulation is currently supported on Linux with KVM only, and we are working on support for other operating systems. We’re very happy that through KVM we’ve been able to create a fast Android emulator for TV.
Depending on the design and use case, an existing Android app may work well on Google TV as is, or it may require fixes. With the add-on you can test your apps to determine if they would be a good fit for TV and whether any tweaks are required. We are also publishing UI guidelines to help you with topics like optimizing for D-pad navigation, presenting information for 10-foot viewing, designing apps that work well across devices, etc. The guidelines include information on how certain UI elements on Google TV differ from other Android devices.
As with other devices, apps that require features not supported on Google TV won’t appear in Android Market on Google TV. For example, Google TV-based devices do not have a touchscreen; hence apps which require touchscreen will not appear. Conversely, if the manifest says touchscreen is not required, the app will appear. Please follow our guidelines carefully.
These are still early days for Google TV, and this release is another step in providing developer tools for the big screen. While the number of apps available on TV will initially be small, we expect that through this early release of the add-on you'll be able to bring optimized TV apps into the ecosystem more quickly. To start doing this, download the Google TV add-on today. Also, please continue to reach out to us on the Google TV Android Developer Community forum. We look forward to your contributions!

Multiple APK Support in Android Market

admin

At Google I/O we announced our plans to add several new capabilities to help developers manage their products more effectively in Android Market. We’re pleased to let you know that the latest of those, multiple APK support, is now available. Multiple APK support is a new publishing option in Android Market for those developers who want extra control over distribution.
Until now, each product listing on Android Market has included a single APK file, a universal payload that is deliverable to all eligible devices — across all platform versions, screen sizes, and chipsets. Broad distribution of a single APK works very well for almost all applications and has the advantage of simplified product maintenance.
With multiple APK support, you can now upload multiple versions of an APK for a single product listing, with each one addressing a different subset of your customers. These APKs are complete, independent APKs that share the same package name, but contain code and resources to target different Android platform versions, screen sizes, or GL texture-compression formats. When users download or purchase your app, Android Market chooses the right APK to deliver based on the characteristics of the device.
When you upload multiple APK files, Android Market handles them as part of a single product listing that aggregates the app details, ratings, and comments across the APKs. All users who browse your app’s details page see the same product with the same description, branding assets, screenshots, video, ratings, and comments. Android Market also aggregates the app’s download statistics, reviews, and billing data across all of the APKs.
Multiple APK support gives you a variety of ways to control app distribution. For example, you could use it to create separate APKs for phones and tablets under the same product listing. You could also use it to take advantage of new APIs or new hardware capabilities without impacting your existing customer base.
To support this new capability, we’ve updated the Developer Console to include controls for uploading and managing APKs in a product listing — we encourage you to take a look. If you’d like to learn more about how multiple APK support works, please read the developer documentation. As always, please feel free to give us feedback on the feature through the Market Help Center.

Debugging Android JNI with CheckJNI

admin

Although most Android apps run entirely on top of Dalvik, some use the Android NDK to include native code using JNI. Native code is harder to get right than Dalvik code, and when you have a bug, it’s often a lot harder to find and fix it. Using JNI is inherently tricky (there’s precious little help from the type system, for example), and JNI functions provide almost no run-time checking. Bear in mind also that the developer console’s crash reporting doesn’t include native crashes, so you don’t even necessarily know how often your native code is crashing.

What CheckJNI can do

To help, there’s CheckJNI. It can catch a number of common errors, and the list is continually increasing. In Gingerbread, for example, CheckJNI can catch all of the following kinds of error:
  • Arrays: attempting to allocate a negative-sized array.
  • Bad pointers: passing a bad jarray/jclass/jobject/jstring to a JNI call, or passing a NULL pointer to a JNI call with a non-nullable argument.
  • Class names: passing anything but the “java/lang/String” style of class name to a JNI call.
  • Critical calls: making a JNI call between a GetCritical and the corresponding ReleaseCritical.
  • Direct ByteBuffers: passing bad arguments to NewDirectByteBuffer.
  • Exceptions: making a JNI call while there’s an exception pending.
  • JNIEnv*s: using a JNIEnv* from the wrong thread.
  • jfieldIDs: using a NULL jfieldID, or using a jfieldID to set a field to a value of the wrong type (trying to assign a StringBuilder to a String field, say), or using a jfieldID for a static field to set an instance field or vice versa, or using a jfieldID from one class with instances of another class.
  • jmethodIDs: using the wrong kind of jmethodID when making a Call*Method JNI call: incorrect return type, static/non-static mismatch, wrong type for ‘this’ (for non-static calls) or wrong class (for static calls).
  • References: using DeleteGlobalRef/DeleteLocalRef on the wrong kind of reference.
  • Release modes: passing a bad release mode to a release call (something other than 0, JNI_ABORT, or JNI_COMMIT).
  • Type safety: returning an incompatible type from your native method (returning a StringBuilder from a method declared to return a String, say).
  • UTF-8: passing an invalid Modified UTF-8 byte sequence to a JNI call.
If you’ve written any amount of native code without CheckJNI, you’re probably already wishing you’d known about it. There’s a performance cost to using CheckJNI (which is why it isn’t on all the time for everybody), but it shouldn’t change the behavior in any other way.

Enabling CheckJNI

If you’re using the emulator, CheckJNI is on by default. If you’re working with an Android device, use the following adb command:
adb shell setprop debug.checkjni 1
This won’t affect already-running apps, but any app launched from that point on will have CheckJNI enabled. (Changing the property to any other value or simply rebooting will disable CheckJNI again.) In this case, you’ll see something like this in your logcat output the next time each app starts:
D Late-enabling CheckJNI
If you don’t see this, your app was probably already running; you just need to force stop it and start it again.

Example

Here’s the output you get if you return a byte array from a native method declared to return a String:
W JNI WARNING: method declared to return 'Ljava/lang/String;' returned '[B'
W              failed in LJniTest;.exampleJniBug
I "main" prio=5 tid=1 RUNNABLE
I   | group="main" sCount=0 dsCount=0 obj=0x40246f60 self=0x10538
I   | sysTid=15295 nice=0 sched=0/0 cgrp=default handle=-2145061784
I   | schedstat=( 398335000 1493000 253 ) utm=25 stm=14 core=0
I   at JniTest.exampleJniBug(Native Method)
I   at JniTest.main(JniTest.java:11)
I   at dalvik.system.NativeStart.main(Native Method)
I 
E VM aborting
Without CheckJNI, you’d just die via SIGSEGV, with none of this output to help you!

New JNI documentation

We’ve also recently added a page of JNI Tips that explains some of the finer points of JNI. If you write native methods, even if CheckJNI isn’t rejecting your code, you should still read that page. It covers everything from correct usage of the JavaVM and JNIEnv types, how to work with native threads, local and global references, dealing with Java exceptions in native code, and much more, including answers to frequently-asked JNI questions.

What CheckJNI can’t do

There are still classes of error that CheckJNI can’t find. Most important amongst these are misuses of local references. CheckJNI can spot if you stash a JNIEnv* somewhere and then reuse it on the wrong thread, but it can’t detect you stashing a local reference (rather than a global reference) and then reusing it in a later native method call. Doing so is invalid, but currently mostly works (at the cost of making life hard for the GC), and we’re still working on getting CheckJNI to spot these mistakes.
We’re hoping to have more checking, including for local reference misuse, in a future release of Android. Start using CheckJNI now, though, and you’ll be able to take advantage of our new checks as they’re added.

Android 3.2 Platform and Updated SDK tools

admin

Today we are announcing the Android 3.2 platform, an incremental release that adds several new capabilities for users and developers. The new platform includes API changes and the API level is 13.
Here are some of the highlights of Android 3.2:

Optimizations for a wider range of tablets. A variety of refinements across the system ensure a great user experience on a wider range of tablet devices.
Compatibility zoom for fixed-sized apps. A new compatibility display mode gives users a new way to view these apps on larger devices. The mode provides a pixel-scaled alternative to the standard UI stretching, for apps that are not designed to run on larger screen sizes.
Media sync from SD card. On devices that support a removable SD card, users can now load media files directly from the SD card to apps that use them.
Extended screen support API. For developers who want more precise control over their UI across the range of Android-powered devices, the platform’s screen support API is extended with new resource qualifiers and manifest attributes, to also allow targeting screens by their dimensions.
For a complete overview of what’s new in the platform, see the Android 3.2 Version Notes.
We would also like to remind developers that we recently released new version of the SDK Tools (r12) and of the Eclipse plug-in (ADT 12). We have also updated the NDK to r6.
Visit the Android Developers site for more information about Android 3.2 and other platform versions. To get started developing or testing on the new platform, you can download it into your SDK using the Android SDK Manager.

A New Android Market for Phones

admin


Earlier this year, we launched several important features aimed at making it easier to find great applications on Android Market on the Web. Today, we're very excited to launch a completely redesigned Android Market client that brings these and other features to phones.
The new Market client is designed to better showcase top apps and games, engage users with an improved UI, and provide a quicker path to downloading or purchasing your products. For developers, the new Android Market client means more opportunities for your products to be merchandised and purchased.
In the home screen, we've created a new promotional page that highlights top content. This page is tiled with colorful graphics that provide instant access to featured apps and games. The page also lets users find their favorite books and movies, which will help drive even more return visits to Market.
To make it fun and easy for users to explore fresh content, we've added our app lists right to the Apps and Games home pages. Users can now quickly flip through these lists by swiping right or left, checking out what other people are downloading in the Top Paid, Top Free, Top Grossing, Top New Paid, Top New Free, and Trending lists. To keep the lists fresh and relevant, we've made them country-specific for many of the top countries.

To help you convert visitors to customers, we’ve made significant changes to the app details page. We've moved the app name and price into a compact action bar at the top of the page, so that users can quickly download or purchase your app. Directly below, users can flip through screen shots by swiping right or left, or scroll down to read your app's description, what's new, reviews, and more. To help you promote your product more effectively, the page now also includes a thumbnail link to your product video which is displayed at full screen when in landscape orientation.
For users who are ready to buy, we've streamlined the click-to-purchase flow so that users can complete a purchase in two clicks from the app details page. During the purchase, users can also see a list of your other apps, to help you cross-sell your other products.
With a great new UI, easy access to app discovery lists, a convenient purchase flow, and more types of content, we believe that the new Market client will become a favorite for users and developers alike.
Watch for the new Market client coming to your phone soon. We've already begun a phased roll-out to phones running Android 2.2 or higher — the update should reach all users worldwide in the coming weeks. We encourage you to try the update as soon as you receive it. Meanwhile, check out the video below for an early look.

A Deep Dive Into Location

admin

I'm a big fan of location-based apps, but not their seemingly-inevitable startup latency.
Whether it's finding a place to eat or searching for the nearest Boris Bike, I find the delay while waiting for the GPS to get a fix, and then for the results list to populate, to be interminable. Once I’m in a venue and ready to get some tips, check-in, or review the food, I’m frequently thwarted by a lack of data connection.
Rather than shaking my fist at the sky, I’ve written an open-source reference app that incorporates all of the tips, tricks, and cheats I know to reduce the time between opening an app and seeing an up-to-date list of nearby venues - as well as providing a reasonable level of offline support — all while keeping the impact on battery life to a minimum.

Show Me the Code

You can check-out the Android Protips for Location open source project from Google Code. Don’t forget to read the Readme.txt for the steps required to make it compile and run successfully.

What Does it Actually Do?

It uses the Google Places API to implement the core functionality of apps that use location to provide a list of nearby points of interest, drill down into their details, and then check-in/rate/review them.
The code implements many of the best-practices I detailed in my Google I/O 2011 session, Android Protips: Advanced Topics for Expert Android Developers (video), including using Intents to receive location updates, using the Passive Location Provider, using and monitoring device state to vary refresh rates, toggling your manifest Receivers at runtime, and using the Cursor Loader.
The app targets Honeycomb but supports Android platforms from 1.6 and up.
Nothing would make me happier than for you to cut/copy/borrow / steal this code to build better location-based apps. If you do, I’d love it if you told me about it!

Now that you’ve got the code, let’s take a closer look at it

My top priority was freshness: Minimize the latency between opening the app and being able to check in to a desired location, while still minimizing the impact of the app on battery life.
Related requirements:
  • The current location has to be found as quickly as possible.
  • The list of venues should update when the location changes.
  • The list of nearby locations and their details must be available when we’re offline.
  • Check-ins must be possible while we’re offline.
  • Location data and other user data must be handled properly (see our prior blog post on best practices).

Freshness means never having to wait

You can significantly reduce the latency for getting your first location fix by retrieving the last known location from the Location Manager each time the app is resumed.
In this snippet taken from the GingerbreadLastLocationFinder, we iterate through each location provider on the device — including those that aren't currently available — to find the most timely and accurate last known location.
List<String> matchingProviders = locationManager.getAllProviders();
for (String provider: matchingProviders) {
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
float accuracy = location.getAccuracy();
long time = location.getTime();

if ((time > minTime && accuracy < bestAccuracy)) {
bestResult = location;
bestAccuracy = accuracy;
bestTime = time;
}
else if (time < minTime && 
bestAccuracy == Float.MAX_VALUE && time > bestTime){
bestResult = location;
bestTime = time;
}
}
}
If there is one or more locations available from within the allowed latency, we return the most accurate one. If not, we simply return the most recent result.
In the latter case (where it’s determined that the last location update isn't recent enough) this newest result is still returned, but we also request a single location update using that fastest location provider available.
if (locationListener != null &&
(bestTime < maxTime || bestAccuracy > maxDistance)) { 
IntentFilter locIntentFilter = new IntentFilter(SINGLE_LOCATION_UPDATE_ACTION);
context.registerReceiver(singleUpdateReceiver, locIntentFilter);      
locationManager.requestSingleUpdate(criteria, singleUpatePI);
}
Unfortunately we can’t specify “fastest” when using Criteria to choose a location provider, but in practice we know that coarser providers — particularly the network location provider — tend to return results faster than the more accurate options. In this case I’ve requested coarse accuracy and low power in order to select the Network Provider when it’s available.
Note also that this code snippet shows the GingerbreadLastLocationFinder which uses the requestSingleUpdate method to receive a one-shot location update. This wasn’t available prior to Gingerbread - check out the LegacyLastLocationFinder to see how I have implemented the same functionality for devices running earlier platform versions.
The singleUpdateReceiver passes the received update back to the calling class through a registered Location Listener.
protected BroadcastReceiver singleUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(singleUpdateReceiver);

String key = LocationManager.KEY_LOCATION_CHANGED;
Location location = (Location)intent.getExtras().get(key);

if (locationListener != null && location != null)
locationListener.onLocationChanged(location);

locationManager.removeUpdates(singleUpatePI);
}
};

Use Intents to receive location updates

Having obtained the most accurate/timely estimate of our current location, we also want to receive location updates.
The PlacesConstants class includes a number of values that determine the frequency of location updates (and the associated server polling). Tweak them to ensure that updates occur exactly as often as required.
// The default search radius when searching for places nearby.
public static int DEFAULT_RADIUS = 150;
// The maximum distance the user should travel between location updates. 
public static int MAX_DISTANCE = DEFAULT_RADIUS/2;
// The maximum time that should pass before the user gets a location update.
public static long MAX_TIME = AlarmManager.INTERVAL_FIFTEEN_MINUTES; 
The next step is to request the location updates from the Location Manager. In this snippet taken from the GingerbreadLocationUpdateRequester we can pass the Criteria used to determine which Location Provider to request updates from directly into the requestLocationUpdates call.
public void requestLocationUpdates(long minTime, long minDistance, 
Criteria criteria, PendingIntent pendingIntent) {

locationManager.requestLocationUpdates(minTime, minDistance, 
criteria, pendingIntent);
}
Note that we're passing in a Pending Intent rather than a Location Listener.
Intent activeIntent = new Intent(this, LocationChangedReceiver.class);
locationListenerPendingIntent = 
PendingIntent.getBroadcast(this, 0, activeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
I generally prefer this over using Location Listeners as it offers the flexibility of registering receivers in multiple Activities or Services, or directly in the manifest.
In this app, a new location means an updated list of nearby venues. This happens via a Service that makes a server query and updates the Content Provider that populates the place list.
Because the location change isn’t directly updating the UI, it makes sense to create and register the associated LocationChangedReceiver in the manifest rather than the main Activity.
<receiver android:name=".receivers.LocationChangedReceiver"/>
The Location Changed Receiver extracts the location from each update and starts the PlaceUpdateService to refresh the database of nearby locations.
if (intent.hasExtra(locationKey)) {
Location location = (Location)intent.getExtras().get(locationKey);
Log.d(TAG, "Actively Updating place list");
Intent updateServiceIntent = 
new Intent(context, PlacesConstants.SUPPORTS_ECLAIR ? EclairPlacesUpdateService.class : PlacesUpdateService.class);
updateServiceIntent.putExtra(PlacesConstants.EXTRA_KEY_LOCATION, location);
updateServiceIntent.putExtra(PlacesConstants.EXTRA_KEY_RADIUS, PlacesConstants.DEFAULT_RADIUS);
updateServiceIntent.putExtra(PlacesConstants.EXTRA_KEY_FORCEREFRESH, true);

context.startService(updateServiceIntent);
}

Monitor inactive providers for a better option

The snippet from PlacesActivity below shows how to monitor two important conditions:
  • The Location Provider we are using being deactivated.
  • A better Location Provider becoming available.
In either case, we simply re-run the process used to determine the best available provider and request location updates.
// Register a receiver that listens for when the provider I'm using has been disabled. 
IntentFilter intentFilter = new IntentFilter(PlacesConstants.ACTIVE_LOCATION_UPDATE_PROVIDER_DISABLED);
registerReceiver(locProviderDisabledReceiver, intentFilter);

// Listen for a better provider becoming available.
String bestProvider = locationManager.getBestProvider(criteria, false);
String bestAvailableProvider = locationManager.getBestProvider(criteria, true);
if (bestProvider != null && !bestProvider.equals(bestAvailableProvider))
locationManager.requestLocationUpdates(bestProvider, 0, 0, 
bestInactiveLocationProviderListener, getMainLooper());

Freshness means always being up to date. What if we could reduce startup latency to zero?

You can start the PlacesUpdateService in the background to refresh the list of nearby locations while your app is in the background. Done correctly, a relevant list of venues can be immediately available when you open the app.
Done poorly, your users will never find this out as you’ll have drained their battery too quickly.
Requesting location updates (particularly using the GPS) while your app isn’t in the foreground is poor practice, as it can significantly impact battery life. Instead, you can use the Passive Location Provider to receive location updates alongside other apps that have already requested them.
This extract from the FroyoLocationUpdateRequester enables passive updates on Froyo+ platforms.
public void requestPassiveLocationUpdates(long minTime, long minDistance, PendingIntent pendingIntent) {
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER,
PlacesConstants.MAX_TIME, PlacesConstants.MAX_DISTANCE, pendingIntent);    
}
As a result receiving background location updates is effectively free! Unfortunately the battery cost of your server downloads aren’t, so you’ll still need to carefully balance how often you act on passive location updates with battery life.
You can achieve a similar effect in pre-Froyo devices using inexact repeating non-wake alarms as shown in the LegacyLocationUpdateRequester.
public void requestPassiveLocationUpdates(long minTime, long minDistance, 
PendingIntent pendingIntent) {

alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,   
System.currentTimeMillis()+PlacesConstants.MAX_TIME, 
PlacesConstants.MAX_TIME, pendingIntent);    
}
Rather than receiving updates from the Location Manager, this technique manually checks the last known location at a frequency determined by the maximum location update latency.
This legacy technique is significantly less efficient, so you may choose to simply disable background updates on pre-Froyo devices.
We handle updates themselves within the PassiveLocationChangedReceiver which determines the current location and starts the PlaceUpdateService.
if (location != null) {
Intent updateServiceIntent = 
new Intent(context, PlacesConstants.SUPPORTS_ECLAIR ? EclairPlacesUpdateService.class : PlacesUpdateService.class);

updateServiceIntent.putExtra(PlacesConstants.EXTRA_KEY_LOCATION, location);
updateServiceIntent.putExtra(PlacesConstants.EXTRA_KEY_RADIUS, 
PlacesConstants.DEFAULT_RADIUS);
updateServiceIntent.putExtra(PlacesConstants.EXTRA_KEY_FORCEREFRESH, false);
context.startService(updateServiceIntent);   
}

Using Intents to passively receive location updates when your app isn't active

You’ll note that we registered the Passive Location Changed Receiver in the application manifest.

<receiver android:name=".receivers.PassiveLocationChangedReceiver"/>
As a result we can continue to receive these background updates even when the application has been killed by the system to free resources.
This offers the significant advantage of allowing the system to reclaim the resources used by your app, while still retaining the advantages of a zero latency startup.
If your app recognizes the concept of “exiting” (typically when the user clicks the back button on your home screen), it’s good form to turn off passive location updates - including disabling your passive manifest Receiver.

Being fresh means working offline

To add offline support we start by caching all our lookup results to the PlacesContentProvider and PlaceDetailsContentProvider.
Under certain circumstances we will also pre-fetch location details. This snippet from the PlacesUpdateService shows how pre-fetching is enabled for a limited number of locations.
Note that pre-fetching is also potentially disabled while on mobile data networks or when the battery is low.
if ((prefetchCount < PlacesConstants.PREFETCH_LIMIT) &&
(!PlacesConstants.PREFETCH_ON_WIFI_ONLY || !mobileData) &&
(!PlacesConstants.DISABLE_PREFETCH_ON_LOW_BATTERY || !lowBattery)) {
prefetchCount++;

// Start the PlaceDetailsUpdateService to prefetch the details for this place.
}
We use a similar technique to provide support for offline checkins. The PlaceCheckinService queues failed checkins, and checkins attempted while offline, to be retried (in order) when the ConnectivityChangedReceiver determines that we’re back online.

Optimizing battery life: Smart Services and using device state to toggle your manifest Receivers

There's no point running update services when we aren’t online, so the PlaceUpdateService checks for connectivity before attempting an update.
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
If we’re not connected, the Passive and Active Location Changed Receivers are disabled and the the ConnectivityChangedReceiver is turned on.
ComponentName connectivityReceiver = 
new ComponentName(this, ConnectivityChangedReceiver.class);
ComponentName locationReceiver = 
new ComponentName(this, LocationChangedReceiver.class);
ComponentName passiveLocationReceiver = 
new ComponentName(this, PassiveLocationChangedReceiver.class);

pm.setComponentEnabledSetting(connectivityReceiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 
PackageManager.DONT_KILL_APP);

pm.setComponentEnabledSetting(locationReceiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 
PackageManager.DONT_KILL_APP);

pm.setComponentEnabledSetting(passiveLocationReceiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 
PackageManager.DONT_KILL_APP);
The ConnectivityChangedReceiver listens for connectivity changes. When a new connection is made, it simply disables itself and re-enables the location listeners.

Monitoring battery state to reduce functionality and save power

When your phone is on its last 15%, most apps are firmly in the back seat to conserving what watts you have remaining. We can register manifest Receivers to be alerted when the device enters or leaves the low battery state.
<receiver android:name=".receivers.PowerStateChangedReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_BATTERY_LOW"/>
<action android:name="android.intent.action.ACTION_BATTERY_OKAY"/>
</intent-filter>
</receiver>
This snippet from the PowerStateChangedReceiver disables the PassiveLocationChangedReceiver whenever the device enters a low battery state, and turns it back on once the battery level is okay.
boolean batteryLow = intent.getAction().equals(Intent.ACTION_BATTERY_LOW);

pm.setComponentEnabledSetting(passiveLocationReceiver,
batteryLow ? PackageManager.COMPONENT_ENABLED_STATE_DISABLED :
PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,  
PackageManager.DONT_KILL_APP);
You can extend this logic to disable all prefetching or reduce the frequency of your updates during low battery conditions.

What’s Next?

This is already a monster post, so I’m going to leave it there. I’ll follow up in the next week with a post on my personal blog, The Radioactive Yak, that will go in to more detail on the psychic and smooth elements of this app like using the Backup Manager and the Cursor Loader.
I also plan to build a similar reference app for news apps, so that I can spend more time reading and less time waiting.
In the mean time, happy coding!

New Mode for Apps on Large Screens

admin

 Android tablets are becoming more popular, and we're pleased to note that the vast majority of apps resize to the larger screens just fine. To keep the few apps that don't resize well from frustrating users with awkward-looking apps on their tablets, a near-future release of Honeycomb is introducing a new screen compatibility mode to make these apps more usable on tablets. If your app is one of the many that do resize well, however, you should update your app as soon as possible to disable screen compatibility mode so that users experience your app the way you intend.
Beginning with the upcoming release, any app that does not target Android 3.0 (set either android:minSdkVersion or android:targetSdkVersion to “11” or higher) or does not explicitly set android:xlargeScreens="true" in the <supports-screens> element will include a button in the system bar that, when touched, allows users to select between two viewing modes on large-screen devices.

“Stretch to fill screen” is normal layout resizing (using your app’s alternative resources for size and density) and “Zoom to fill screen” is the new screen compatibility mode.
When the user enables this new screen compatibility mode, the system no longer resizes your layout to fit the screen. Instead, it runs your app in an emulated normal/mdpi screen (approximately 320dp x 480dp) and scales that up to fill the screen---imagine viewing your app at the size of a phone screen then zooming in about 200%. The effect is that everything is bigger, but also more pixelated, because the system does not resize your layout or use your alternative resources for the current device (the system uses all resources for a normal/mdpi device). Here’s a comparison of what it looks like (screen compatibility mode enabled on the right):

In cases where an app does not properly resize for larger screens, this screen compatibility mode can improve the app’s usability by emulating the app’s phone-style look, but zoomed in to fill the screen on a tablet.
However, most apps (even those that don’t specifically target Honeycomb) look just fine on tablets without screen compatibility mode, due to the use of alternative layouts for different screen sizes and the framework’s flexibility when resizing layouts. Unfortunately, if you haven’t said so in your manifest file, the system doesn’t know that your application properly supports large screens. Thus, if you’ve developed your app against any version lower than Android 3.0 and do not declare support for large screens in your manifest, the system is going to offer users the option to enable screen compatibility mode.
So, if your app is actually designed to resize for large screens, screen compatibility mode is probably an inferior user experience for your app and you should prevent users from using it. The easiest way to make sure that users cannot enable screen compatibility mode for your app is to declare support for xlarge screens in your manifest file’s <supports-screens> element. For example:

<manifest ... >
<supports-screens android:xlargeScreens="true" />
...
</manifest>
That’s it! No more screen compatibility mode.
Note: If your app is specifically designed to support Android 3.0 and declares either android:minSdkVersion or android:targetSdkVersion with a value of “11” or greater, then your app is already in the clear and screen compatibility mode will not be offered to users, but adding this attribute certainly won’t hurt.
In conclusion, if your app has set the android:minSdkVersion and android:targetSdkVersion both with values less than “11” and you believe your app works well on large and xlarge screens (for example, you’ve tested on a Honeycomb tablet), you should make the above addition to your manifest file in order to disable the new screen compatibility mode.
If your app does not resize properly for large screens, then users might better enjoy your app using screen compatibility mode. However, please follow our guide to Supporting Multiple Screens so that you can also disable screen compatibility mode and provide a user experience that’s optimized for large-screen devices.

Things That Cannot Change

admin

Sometimes a developer will make a change to an application that has surprising results when installed as an update to a previous version — shortcuts break, widgets disappear, or it can’t even be installed at all. There are certain parts of an application that are immutable once you publish it, and you can avoid surprises by understanding them.

Your package name and certificate

The most obvious and visible of these is the “manifest package name,” the unique name you give to your application in its AndroidManifest.xml. The name uses a Java-language-style naming convention, with Internet domain ownership helping to avoid name collisions. For example, since Google owns the domain “google.com”, the manifest package names of all of our applications should start with “com.google.” It’s important for developers to follow this convention in order to avoid conflicts with other developers.
Once you publish your application under its manifest package name, this is the unique identity of the application forever more. Switching to a different name results in an entirely new application, one that can’t be installed as an update to the existing application.
Just as important as the manifest package name is the certificate that application is signed with. The signing certificate represents the author of the application. If you change the certificate an application is signed with, it is now a different application because it comes from a different author. This different application can’t be uploaded to Market as an update to the original application, nor can it be installed onto a device as an update.
The exact behavior the user sees when installing an application that has changed in one of these two ways is different:
  • If the manifest package name has changed, the new application will be installed alongside the old application, so they both co-exist on the user’s device at the same time.
  • If the signing certificate changes, trying to install the new application on to the device will fail until the old version is uninstalled.
If you change the signing certificate of your application, you should always change its manifest package name as well to avoid failures when it’s installed. In other words, the application coming from a different author makes it a different application, and its package name should be changed appropriately to reflect that. (Of course it’s fine to use the same package name for the development builds of your app signed with your test keys, because these are not published.)

Your AndroidManifest.xml is a public API

More than just your package name that is immutable. A major function of the AndroidManifest.xml is essentially to declare a public API from your application for use by other applications and the Android system. Every component you declare in the manifest that is not private (that is whose android:exported state is true) should be treated as a public API and never changed in a way that breaks compatibility.
A subtle but important aspect of what constitutes a break in compatibility is the android:name attribute of your activity, service, and receiver components. This can be surprising because we think of android:name as pointing to the private code implementing our application, but it is also (in combination with the manifest package name) the official unique public name for that component, as represented by the ComponentName class.
Changing the component name inside of an application can have negative consequences for your users. Some examples are:
  • If the name of a main activity of your application is changed, any shortcuts the user made to it will no longer work. A shortcut is an Intent that directly specifies the ComponentName it should run.
  • If the name of a service implementing a Live Wallpaper changes, then a user who has enabled your Live Wallpaper will have their wallpaper revert to the system default when getting the new version of your app. The same is true for Input Methods, Accessibility Services, Honeycomb’s new advanced Widgets, and so on.
  • If the name of a receiver implementing a Device Admin changes, then as with the live wallpaper example, the device admin will be disabled when the application is updated. This also applies to other kinds of receivers, such as App Widgets.
These behaviors are an outcome of how the Intent system is used on Android. There are two main kinds of Intents:
  • Implicit Intents only specify “what” they should match, using actions, categories, data, MIME types, and so on. The exact components that they will find are only determined at run-time, by the Package Manager matching it against the current applications.
  • Explicit Intents specify a single explicit “who” they should match, through a ComponentName. Regardless of whatever else is in the Intent, it is only associated with the exact manifest package name and class name as given in its ComponentName.
Both of these types of Intents are important to how Android interacts with your application. A typical example of this is how users browse and select live wallpapers.
To let the user pick a live wallpaper, the first thing Android must do is show them a list of the available live wallpaper services. It does this by building an implicit Intent with the appropriate action for a live wallpaper and asking the Package Manager for all services that support this Intent. The result is then the list of live wallpapers shown to the user.
When the user actually selects a specific live wallpaper they want to use, however, Android now must build an explicit Intent that identifies that particular live wallpaper. This is what is handed to the WallpaperManager to tell it which wallpaper to show.
This is why changing the name of the component in your manifest will cause the wallpaper to disappear: the explicit Intent that was previously saved is now invalid because the ComponentName it references no longer exists. There is no information available to indicate what the new name of the component is. (For example consider if your application had two different live wallpaper services the user could select.) Instead, Android must treat that live wallpaper as uninstalled and revert to its default wallpaper.
This is how input methods, device administrators, account managers, app widgets, and even application shortcuts work. The ComponentName is the public unique name of the components you declare in your manifest, and must not change if they are visible to other applications.
In conclusion: There are some parts of your application that can not change. Please be careful.

New Editing Features in Eclipse plug-in for Android

admin

At the Google I/O conference a month ago, we demonstrated the next version of the Android Development Tools (ADT) plugin. Today we’re happy to announce that version 11 is done and available for download!
ADT 11 focuses on editor improvements. First, it offers several new visual refactoring operations, such as “Extract Include” and “Extract Style,” which help automatically extract duplicated layout fragments and style attributes into reusable layouts, styles, and themes.
Second, the visual layout editor now supports fragments, palette configurations, and improved support for custom views.
Last, XML editing has been improved with new quick fixes, code completion in more file types and many “go to declaration” enhancements.
ADT 11 packs a long list of new features and enhancements. Please visit our ADT page for more details. For an in-depth demo, check out the video of our Android Development Tools session at Google I/O, below.

Please note that the visual layout editor depends on a layout rendering library that ships with each version of the platform component in the SDK. We are currently working on a number of improvements to this library as well, which we plan to release soon for all platform versions. When we release the updates, some new features in ADT 11 will be “unlocked” - such as support for ListView previewing - so keep an eye on this blog for further announcements.