AsyncTask class is specially designed in Android to handle processes which takes time to complete, and to make it independent from the user interface. For example, suppose in an application, if we want to load some content from the web when the user clicks a button, we can use AsyncTask. And if we don’t handle it properly, the time taking web fetch will block the user interface and the user might feel the application is not very responsive. AsyncTask is capable of taking such time consuming tasks into the background and execute it as a separate thread. AsyncTask provides methods to update the UI with progress information about the task as well. AsyncTask has the following methods.
doInBackground - It will do the real task using an independent thread - we can also usepublishProgress from inside this method to trigger the onProgressUpdate method.
onProgressUpdate - It can be used to update the user interface and it is triggered bypublishProgress from the doInBackground method.
onPostExecute - Once the doInBackground finished, this method gets fired, and it can update the user interface with the result retrieved from the task being just carried out.
Here is a very simple example in which, I use an AsyncTask in my main class to do a time consuming web fetch. I have not included the code to do the real web fetch, which is out of context here.
In this example I used an HTML parser class which is defined in another file. Developers can use any methods for doing this. In the parser class, I had a method named getDataFromWeb() which does nothing but the time consuming data fetch from the web. I’ve not use the publishProgress()method in this example since there is only one data fetch required. You can work on this code to develop your own AsyncTask applications. :)
Android promises many exciting opportunities. Kevin McDonagh, director of Android development consultancy Novoda, rounds up 10 essential tips that will help you make the most of your development time.
A smartphone war is raging, pitched as a neck and neck battle for market share; but I see it differently. Android is an open platform, iPhone is a lovely product, everything else is decoration. Android is most exciting in its incarnations outside of what is expected in mobile, desktop and tablets. I expect to see it in hundreds of future weird and wonderful products but in any case you’d best believe smartphone adoption isn’t going to slow down any time soon. Tinkering with Android technology today promises many exciting future opportunities.
Android makes it extremely easy to get started. The full contents of the Android source code are available online, withcomprehensive documentation and an eager and friendly community. A wealth of demos and tools for IDEs will ease an otherwise steep learning curve. And here I’m going to boost your an advantage even further with 10 tips to make the most of your development time.
01. Reserve your name space
The Google Android Market uses the package name that you declare in your manifest to uniquely identify you amongst the thousands of other apps available. If you know ahead of schedule that you’ll be releasing a certain application, it’s a good idea to get in there early and make sure you can reserve your place!
02. Listen to your users
Recently we were working for a client who believed that his application needed feature X and that the omission of feature X was the reason for a lot of the woeful complaints he was seeing on the Android Market comments. Instead of implementing the wrong thing, we analysed the comments and feedback on the Android Market ourselves and compiled a list of feature requests, along with a number correlating with their requested frequency. Lone behold feature X was actually at the bottom of the list!
Your own preconceptions and preferences can blind you to what the majority of people really care about. Gather as much feedback as you can about your application and more importantly, be sure to act upon it.
The love/hate relationship of feedback
03. Use Android's platform patterns
We all want our applications to be unique but there’s a saying that “To break the rules you first must know the rules”. There are a lot of apps out there and we want them to play well together, so before you start cutting out your unique niche in the Android Market, consider first trying to fit into the way people are already using Android applications. If you tie yourself into their existing habits you’ll already have an eager well educated bunch of users!
Consider how you can encourage people to share information into and out of your app. The most common way to share functionality is via platform intents. Exposing intents to your application is greatly advised and there are many intents from which your app may benefit documented in the official Google developer reference material and even more agreed upon at open intents. Probably the most popular of all is the generic Intent.ACTION_SEND option. Declare that you offer an ACTION_SEND option within your manifest and see users flock to your app through their normal message and picture sharing applications.
After you have shared functionality, consider offering the expected basics in how your application’s functionality is presented in its UI before taking any brave new directions. Dashboards, action bars, search bars, quick actions and widgets are all expected when you install an Android application and if you aren’t offering this, users are immediately forced to start learning something new before they start just using your application for what it best offers. Consider using a framework such as GreenDroid to get a headstart on the common aspects of your UI.
04. Use Hiearchy Viewer while creating views
<sdk>/tools/hierarchyviewer
The View Hierarchy gives you a way to statically explore activity UIs and can help you visualise complicated layouts. This is my favourite Android tool but for security reasons is only available only on devices flashed with a developer version of the Android Platform. So if you want to take advantage of this tool (you do), you’ll either need a phone with an Android OS development version or the emulator.
Alternatively, you can include Romain Guy’s ViewServer Classinto your application to enable the same views on any retail phone. When posed with a styling problem, large or small, I urge all developers to quickly turn to the Hierarchy Viewer. I’ve lost count of how many times during styling I developed further styling under erroneous assumptions. Later I’d open the Hierarchy Viewer and in light of the actual view model in memory I’d make a winning change instantly.
It has two contexts; HierarchyView and Pixel Perfect. HierarchyView is where the majority of interest lies. When revisting areas for UI polish, Pixel Perfect helps zero in on the fine placement details of images and make sure they are rendering appropriately on all densities.
The Hierarchy View will support you throughout the full development cycle of your Layouts and styling development.
First of all, you’re presented with a list of components, both system and your own activities currently sitting on the Dalvik stack. By selecting any of these you can view its associated tree view layout.
TreeView and Properties navigation
Drill into a view’s associated details through the collapsible properties area and highlighted nodes can be filtered by entering an id or class name.
Capture PNG/PSD
Various useful information can be exported to help when you’re debugging and compiling your designs. You can save a screenshot object model of the current view hierarchy tree or even export the current state as a collection of layers available to switch on and off, move around as layers in a PSD for use in Adobe Photoshop.
View Optimisation
Render times and performance indicators for each item are also available as coloured dots on each view. Each gives a high-level idea of view creation bottlenecks. Left to right, dots represent measuring, layout, and then draw time of a respective view in comparison to the rest of the nodes in the tree.
In comparison to the other items in the tree, a green dot is allocated to views 50 per cent faster, a yellow dot for items 50 per cent slower and a red dot for the overall slowest to render.
HierarchyViewer lets you delve deeper into your Android UIs
05. Optimise your XML layouts with layoutopt
<sdk>/tools/ layoutopt
Running layoutOpt against your XML layouts helps identify redundant views that could perhaps be removed. It also suggests areas where more effective platform attributes could be used in order to have fewer views rendered to the UI at run time. A common suggestion is the use of relative attributes such as android:layoutToRightOf=”id” and android:layoutToRightOf=”id”. These android attributes can be assigned to items in a relative layout instead of overly nesting views, whose only purpose is to contain other attributes.
Running the tool against a valid XML will result in a short description of the issue along with any suggested resolution and the line number of where to find it.
06. Use themes
Themes help you manage styles across an entire app. Searching for reference in how to best apply your themes to your application will not yield many results, yet this is still something I advise in managing an application of any scale. Designing your app with strict styling early on in the development of your application will make it much easier to deal with device idiosyncrasies later on when you are developing your app for the best presentation on multiple sizes and resolutions of screens.
Every single layout item in views is going to need a declared height and width. All together this adds up to lots and lots of extra lines in your XML layouts and styles. Instead, fallback on the sensible default of always wrapping your layouts. This way, unless you declare otherwise in your styles, you can expect your views to wrap their content and you can save space on all those redundant width/height declarations.
Styles are meant to cut down on redundancy and so I like to push this as far as possible. The previous tip spoke about the redundancy of width/height combinations. In order to take this even further each time, you actually need to apply a style: why not start from one of a set of sensible defaults? Here’s a selection from some of my most-used sensible default styles:
Google’s Android Market is a global marketplace. After all your hard work getting an app into the wild, you want as many users downloading your app as possible! Get a head start in tapping into a larger audience by simply providing a translated title and description for your app in the Android Market. Grow from this userbase to slowly offer localised text for specific regions that seem to be interested in your application. You can view the downloads pertaining to specific regions in the Android Market.
10. Standardise your naming convention
Under the res/values/directory you'll find a whole load of attributes, but try not to get carried away in creativity with your naming. Establish some sensible guidelines and then stick to them/ That way, later on down the line during an important bug fix, your development partner will be able to find items unassisted.
It's up to you how specific you'd like your resources to be targeted
For instance, I prefix icons with ‘ic_‘ activity layouts with ‘act_’. I also prefix the ids of each layouts view items with unique identifiers so you can clearly signpost to the user where this item is being used. When styling an item, if the item is unique then I’ll also tend to use the exact same name for an item’s style, dimens color and string.
3. Then, in the ActivityMain.java file add the below to the onCreate method. ActionBar ab = getActionBar(); ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#81a3d0")); ab.setBackgroundDrawable(colorDrawable);
4. Determine the Hex color you would like and update the Color.parColor above to your specific color.
Step 3: Implement SensorEventListener.onSensorChanged method public void onSensorChanged(SensorEvent event) { Sensor sensor = event.sensor; float[] values = event.values; int value = -1; if (values.length > 0) { value = (int) values[0]; } if (sensor.getType() == Sensor.TYPE_STEP_COUNTER) { textView.setText("Step Counter Detected : " + value); } else if (sensor.getType() == Sensor.TYPE_STEP_DETECTOR) { // For test only. Only allowed value is 1.0 i.e. for step taken textView.setText("Step Detector Detected : " + value); } }
Step 5: Update Android Manifest configuration for these new features res/values/strings.xml: <string name="step_counter"> android.hardware.sensor.stepcounter </string>
<string name="step_detector"> android.hardware.sensor.stepdetector </string> AndroidManifest.xml <uses-feature android:name="@string/step_detector" android:required="false"/> <uses-feature android:name="@string/step_counter" android:required="false"/> Step 6: Test run your simple pedometer application
Step 7: Your Homework : Extend and customize your application by managing step sensor data as per your ideas
Every app is just one drop in the vast ocean of the app store. If you want to stand out and have a chance of building a profitable user base, there are a few things you should know before you begin development:
1. Imitation is not always the sincerest form of flattery
If your product is good, people will copy you. The better it is, the likelihood of being ripped off increases exponentially. This is a multi-industry reality and it’s the first thing you should keep in mind as you develop your mobile app.
If you know you have an excellent product in the works, a strong launch is critical. The initial loyal user base you attract as a result of high visibility will help you stay on top when the imitators eventually end up publishing similar products.
The more active users you have, the better your app holds its ground in the store. Additionally, those are the users who convert to paying customers.
2. It is far too easy to get lost in the crowd
One of the biggest challenges mobile app developers face is discoverability. With more than a million mobile apps in each of the app stores (Apple and Android), it is becoming harder and harder to generate organic users.
To overcome this, you should plan on putting time and effort into app store optimization techniques. The app name, icon, description and screenshots – all of these need high attention and professional care to reach the best results.
Invest time and money to produce a unique presentation of your app before it is downloaded to grab the attention and pique the interest of users.
3. You don’t have to play by the rules to go viral
When it comes to distribution, developers often think the only path to topping the charts is through organic results. This is usually not the case! Going viral is rare, so developers should not be shy about opening their pockets and buying some downloads.
Set a budget and contact a solid network, target your audience, and get those users. This is particularly crucial for your launch to ensure a strong start.
Another area in which to exercise a bit of creativity is monetization. Do not be fearful of trying new monetization solutions. Far too many mobile app developers “settle” for the generic solution of placing a flat, boring banner in their ad because they feel it’s the only solution. Wrong! Get your creative juices flowing to come up with an innovative solution.
For example, users are far more tolerant of in-app advertising than you may think, particularly if your app is well-made and solves a problem for them, or even provides a few moments of fun.
A well-integrated, well-timed full-page ad, app wall, or video can generate revenue in a way that compliments the app experience rather than damaging or distracting from the experience.
4. There is a best time to launch your mobile app
You’ve probably heard the expression, “Good things come to those who wait.” This is especially true when it comes to choosing the right moment to launch your mobile app.
If you are accustomed to publishing on the Web, toss everything you know out the window, because the best times to publish mobile apps are during the summer and the December holidays. People are on the road and glued to their devices. Use this to your advantage and plan to boost your app just before the holidays for a massive wave of fresh users.
5. The new kids on the block are the most popular
Before you release your app, ask yourself the question, “What problem does this app solve?” Why will users be attracted to it? There are plenty of strange viral app sensations out there. They end up topping the charts but do not frequently last. The apps with staying power are the ones addressing a need in the lives of their users.
When people say, “I wish there was an app for that” and a search reveals your app, this generates excitement. Further, everyone loves being “the first” to know about a cool new product so they can tell their friends and colleagues about it. This can only help your user base grow.
What do you think? What are the things you take into consideration as you develop new mobile apps?