Wednesday, 4 June 2014

AsyncTask example in Android

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.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
public class StockWatch extends Activity {
 
String myData;
Button refresh;
myHtmlParser myParser;
 
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
refresh = (Button)findViewById(R.id.refresh);
myParser = new myHtmlParser();
refresh.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
myAsyncTask myWebFetch = new myAsyncTask();
myWebFetch.execute();
}
});
}
 
// All the methods in the following class are
// executed in the same order as they are defined.
class myAsyncTask extends AsyncTask<Void, Void, Void> {
 
TextView tv;
 
myAsyncTask() {
tv = (TextView)findViewById(R.id.tv);
}
 
// Executed on the UI thread before the
// time taking task begins
@Override
protected void onPreExecute() {
super.onPreExecute();
tv.setText("Ready to start async task....");
}
 
// Executed on a special thread and all your
// time taking tasks should be inside this method
@Override
protected Void doInBackground(Void... arg0) {
tv.setText("Running task....");
myData = myParser.getDataFromWeb();
return null;
}
// Executed on the UI thread after the
// time taking process is completed
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
tv.setText("Completed the task, and the result is : " + myData);
}
}
}

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.   :)

Wednesday, 14 May 2014

10 amazing Android development tips

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
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
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.
In your Android Manifest:
<application android:icon="@drawable/icon"android:theme="@style/Theme.YourApp" android:name="com.demo.App">

Then in your res/values/styles.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
        <style name="Theme" parent="android:Theme" />

<style name="Theme.YourApp" parent="android:style/Theme.Light">

<!-- customisable theme items-->
        </style>
</resources>
At the moment, the only way to really see each of the customisable attributes for a theme is in exploring the Android open source project here:
You can now override all your own themed widget items! Here is an example of overriding a button with your own declared style of ‘Widget.Button’.
...
<item name="android:buttonStyle">@style/Widget.Button</item>
...

07. Add layout defaults to your theme

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.
Simply add the following within your theme:
<style name="Theme.YourApp" parent="android:style/Theme.Light">
                       <item name="android:layout_width">wrap_content</item>
                 <item name="android:layout_height">wrap_content</item>
        </style>

08. Extend sensible parents in your styles

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:
<style name="Fill">
         <item name="android:layout_width">fill_parent</item>
         <item name="android:layout_height">fill_parent</item>
         <item name="android:orientation">vertical</item>
    </style>
    <style name="Wrap">
         <item name="android:layout_width">wrap_content</item>
         <item name="android:layout_height">wrap_content</item>
         <item name="android:orientation">vertical</item>
    </style>
    <style name="Fill.Height" parent="@style/Fill">
         <item name="android:layout_width">wrap_content</item>
    </style>
    <style name="Fill.Width" parent="@style/Fill">
         <item name="android:layout_height">wrap_content</item>
    </style>

09. Offer translations but start simple

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
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.

Saturday, 5 April 2014

Android change Background color on Action Bar

1. Add Action Bar to your project.

2. Open the ActivityMain.java file and add the below imports to the imports section.

    import android.app.ActionBar;
    import android.graphics.drawable.ColorDrawable;

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.

Friday, 4 April 2014

Capture Speech/Voice Input for Google Glass

This tutorial will walk you through the steps and code snippets for capturing user speech/voice input in your GDK based Glassware.
Step 1:
Create an Android project as shown below. If you haven’t tried installing any sample Glassware on your Google Glass, please visit this tutorial.
Create an Android Project
Create an Android Project
Step 2:
Create an Android Activity and edit the AndroidManifest.xml as shown below:
<activity
android:name=”com.example.capturespeechinput.MainActivity”
android:label=”@string/app_name” >
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<action android:name=”com.google.android.glass.action.VOICE_TRIGGER” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
<meta-data
android:name=”com.google.android.glass.VoiceTrigger”
android:resource=”@xml/voice_trigger_start” />
</activity>
Step 3:
Now, create a folder called xml under res and create an xml file called voice_trigger_start.xml.
Paste the following content inside:
<?xml version=”1.0″ encoding=”utf-8″?>
<trigger keyword=”Capture Speech” >
         <input prompt=”Speak now!” />
</trigger>
Step 4:
Edit the activity_main.xml (Your activity’s layout page) to include a TextView with the id – ‘capturedSpeechToText’ as follows:
<TextView
android:id=”@+id/capturedSpeechToText”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”" />
Step 5:
Edit your MainActivity Java Class to include the following code snippet to captured the spoken text in the onCreate() method:
ArrayList<String> voiceResults = getIntent().getExtras().getStringArrayList(RecognizerIntent.EXTRA_RESULTS);
if (voiceResults != null && voiceResults.size() > 0) {
String spokenText = voiceResults.get(0);
TextView capturedSpeechToTextViewObj = ((TextView) findViewById(R.id.capturedSpeechToText));
capturedSpeechToTextViewObj.setText(spokenText);
}
Step 6:
Now, build and deploy the Android application on to your Google Glass and enjoy the output:
Capture Speech - Launch Application
Capture Speech – Launch Application
Voice Prompt - Speak Now
Voice Prompt – Speak Now
Voice Input for Google Glass
Voice Input for Google Glass
Voice captured in your GDK Application
Voice captured in your GDK Application

ANDROID 4.4 – KITKAT – STEP DETECTOR CODE

One of the new features in Android 4.4, KitKat is the “Step Counter” and “Step Detector” sensors.

I hope this example will be good enough and helpful in getting started with new Step related features on Android 4.4. 
Step 1: Create SensorEventListener

public class MainActivity extends Activity implements SensorEventListener{



private TextView textView;

private SensorManager mSensorManager;

private Sensor mStepCounterSensor;

private Sensor mStepDetectorSensor;


Step 2: Get SensorManager and Step Sensors

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textview);

mSensorManager = (SensorManager)        
            getSystemService(Context.SENSOR_SERVICE);
mStepCounterSensor = mSensorManager
  .getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
mStepDetectorSensor = mSensorManager
  .getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
}

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 4: Register and Unregister Sensors

 protected void onResume() {

super.onResume();

     mSensorManager.registerListener(this, mStepCounterSensor,

SensorManager.SENSOR_DELAY_FASTEST);  
     mSensorManager.registerListener(this, mStepDetectorSensor,

SensorManager.SENSOR_DELAY_FASTEST);

}

 protected void onStop() {
super.onStop();
mSensorManager.unregisterListener(this, mStepCounterSensor);
mSensorManager.unregisterListener(this, mStepDetectorSensor);
}

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

Wednesday, 2 April 2014

5 things every beginning Android app developer should know

The world has entered a mobile age, and the app industry is booming as a result. Worth $53 billion in 2012, the global app economy is expected to grow to $143 billion by 2016. Everyone wants a piece of the digital pie, but few mobile app developers are armed with the facts.
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?