Wednesday 20 April 2011

Alternative ways of developing for Android

Besides the Google SDK for Android, there are other unconventional ways to develop native applications for Android. I have listed a few alternative frameworks and cross-platform development tools.


  • Phonegap - Allows you to develop cross-platform applications for iOS, Android, Palm, Blackberry and Symbian OS. Phonegap has plans to bring MeeGo and bada support too.
  • Titanium Appcelerator - Appcelerator allows you to use web technologies to develop applications for Android, iPhone, iPad, Windows and Mac.
  • Rhomobile - Cross-platform development tool based on Rhodes. Allows you to use MVC for mobile applications. Supported platform includes Android, iPhone, Windows Mobile, Blackberry and Symbian.
  • Google App Inventor - App Inventor is a GUI based web application that involves no coding, users can drag and drop controls and logic to create Android applications for personal use.
  • Anscamobile's Corona SDK - A cross-platform game development tools. You should use Lua for developing games for Android and iPhone.
  • MonoDroid - Mono for Android enables developers to use Microsoft Visual Studio to create C# and .NET based applications that run on Android phones and tablets.
  • Sencha Touch - Use web technologies to develop applications for Android, iPhone and Blackberry.

Most of the above listed frameworks empowers web developers to use their existing skills to develop application for mobile platforms. However a few of the cross-platform tools are not very mature for one or more of the supported platforms and there is no guarantee that you will be able to develop for the most recent mobile platform releases. Despite the cons, these tools provide opportunity for developers to step confidently into the mobile jungle with existing equipments. You as a developer must ensure to check the pros and cons of any tool before proceeding. 

If you are aware of any such cross-platform tools you are welcome to join the conversation. Leave your comments and let us know.

Tuesday 19 April 2011

Android - Accelerometer Tutorial

Android devices come with various sensors such as proximity sensors, pressure sensors, accelerometer, gyroscope, light sensor, magnetometer, thermometer, etc.,

In this tutorial we will be using accelerometer. To summarize the tasks:
1. Obtain a reference to the SensorManager.
2. Register a sensor listener for the accelerometer.
3. Make updates from the SensorListener callbacks.

MainActivity.java
 package com.mobsandgeeks.ad;  
   
 import android.app.Activity;  
 import android.content.Context;  
 import android.hardware.SensorListener;  
 import android.hardware.SensorManager;  
 import android.os.Bundle;  
 import android.widget.TextView;  
   
 @SuppressWarnings("deprecation")  
 public class MainActivity extends Activity implements SensorListener {  
      //References to the TextViews defined in main.xml  
      private TextView xValue;  
      private TextView yValue;  
      private TextView zValue;  
      
      //Reference to the SensorManager  
      private SensorManager sensorManager;  
        
      @Override  
      public void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.main);  
       
           //Obtain references to the Views from the content view  
           xValue = (TextView) findViewById(R.id.x_value);  
           yValue = (TextView) findViewById(R.id.y_value);  
           zValue = (TextView) findViewById(R.id.z_value);  
       
           sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); //Reference to the SensorManager  
           sensorManager.registerListener(this, SensorManager.SENSOR_ACCELEROMETER); //Registering the sensor listener for the accelerometer  
      }  
   
      @Override  
      public void onAccuracyChanged(int sensor, int accuracy) {  
      }  
   
      @Override  
      public void onSensorChanged(int sensor, float[] values) {  
           float x = values[SensorManager.RAW_DATA_X]; //Raw X value for the accelerometer  
           float y = values[SensorManager.RAW_DATA_Y];     //Raw X value for the accelerometer  
           float z = values[SensorManager.RAW_DATA_Z];     //Raw X value for the accelerometer  
             
           //Update TextViews  
           xValue.setText("X: " + x);  
           yValue.setText("Y: " + y);  
           zValue.setText("Z: " + z);  
      }  
 }  

Source Code
You can download the source code from here.

Screenshot

Monday 18 April 2011

Android - Auto Complete Tutorial

Auto Complete feature is a great feature for applications that involve fields that have to be filled manually. In Android the AutoCompleteTextView brings this feature. This is a relatively simple control to use and a fully functional auto complete feature can be implemented in just 4 lines of code.

Here is what we are going to do:
  1. Define the AutoCompleteTextView in XML (or Java).
  2. Create a ArrayAdapter for the AutoCompleteTextView.
  3. Set the adapter you created in step 2 to the AutoCompleteTextView.
  4. Set the threshold value for the AutoCompleteTextView. The threshold value defines the number of characters that has to be typed before the auto complete list is displayed on the screen.
main.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:orientation="vertical"  
   android:layout_width="fill_parent"  
   android:layout_height="fill_parent">  
      <AutoCompleteTextView   
        android:id="@+id/autocomplete_textview"   
        android:layout_width="fill_parent"   
        android:layout_height="wrap_content" />  
 </LinearLayout>  

MainActivity.java
 package com.mobsandgeeks.acd;  
   
 import android.app.Activity;  
 import android.os.Bundle;  
 import android.widget.ArrayAdapter;  
 import android.widget.AutoCompleteTextView;  
   
 public class MainActivity extends Activity {  
        
      private static final String[] FRUITS = {  
           "Apple", "Orange", "Banana", "Avacado", "Pear",  
           "Peach", "Lemon", "Pineapple", "Strawberry", "Gooseberry",  
           "Grapes", "Watermelon", "Mango", "Papaya", "Dragonfruit",  
           "Guava", "Honeydew", "Jackfruit", "Kiwifruit", "Olive",  
           "Pomegranate", "Raspberry", "Fig", "Custard Apple"  
      };  
        
      @Override  
      public void onCreate(Bundle savedInstanceState) {  
             super.onCreate(savedInstanceState);  
             setContentView(R.layout.main);  
       
             AutoCompleteTextView actv = (AutoCompleteTextView) findViewById(R.id.autocomplete_textview);  
       
             ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,   
                      android.R.layout.simple_dropdown_item_1line, FRUITS);  
       
             actv.setThreshold(1);  
             actv.setAdapter(adapter);  
      }  
 }  

Source Code
You can download the source code from here.

Screenshot

Saturday 16 April 2011

Android - Intents and Broadcast Receivers

Intents
Intents are messages that are passed between Android components. They are used to do specific jobs inside the Android platform. Most of the actions that are carried out in Android involve intents. For instance, you as an application developer should send intents for starting activities, starting / stopping services, completing an action using other applications like taking a photograph, sending email, text messages, etc.,

The primary pieces of an Intent are:
  1. Action - The general action to be performed
  2. Data - The data to operate on, generally a URI
You can also define your own actions and receive those intents using broadcast receivers.

Broadcast Receivers a.k.a Intent Receviers
Broadcast Receivers receive intents that sent by sendBroadcast(). You can statically publish a receiver in the AndroidManifest.xml using the <receiver> tag or you can do the same using Context.registerReceiver(). In this example we will be registering out broadcast receiver statically.

MainActivity.java
 package com.mobsandgeeks.ire;  
   
 import android.app.Activity;  
 import android.content.Intent;  
 import android.os.Bundle;  
 import android.view.View;  
 import android.view.View.OnClickListener;  
 import android.widget.Button;  
   
 public class MainActivity extends Activity implements OnClickListener {  
      private Button sendIntentButton;  
     
      @Override  
      public void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.main);  
       
           sendIntentButton = (Button) findViewById(R.id.send_intent_button);  
           sendIntentButton.setOnClickListener(this);  
      }  
   
      public void onClick(View view) {  
           if(view == sendIntentButton) {  
                Intent i = new Intent();  
                i.setAction("com.mobsandgeeks.action.DEMO_ACTION");  //Our Action, use the same in the BroadcastReceiver too
                sendBroadcast(i);  //Broadcast the intent with the custom action
           }  
      }  
 }  

MyReceiver.java
 package com.mobsandgeeks.ire;  
   
 import android.content.BroadcastReceiver;  
 import android.content.Context;  
 import android.content.Intent;  
 import android.widget.Toast;  
   
 public class MyReceiver extends BroadcastReceiver {  
   
      @Override  
      public void onReceive(Context context, Intent intent) {  
           String action = intent.getAction();

           //This check is redundant since the intent-filter in the manifest only 
           //accepts our action. Use condition checking only when you use a receiver 
           //to handle multiple actions
           if(action.equals("com.mobsandgeeks.action.DEMO_ACTION")) {
                Toast.makeText(context, "Intent received", Toast.LENGTH_SHORT).show();  
           }  
      }  
 }  

AndroidManifest.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
    package="com.mobsandgeeks.ire"  
    android:versionCode="1"  
    android:versionName="1.0">  
   <uses-sdk android:minSdkVersion="4" />  
        
   <application android:icon="@drawable/icon" android:label="@string/app_name">  
     <activity android:name=".MainActivity" android:label="@string/app_name">  
          <intent-filter>
               <action android:name="android.intent.action.MAIN" />  
               <category android:name="android.intent.category.LAUNCHER" />  
          </intent-filter>  
     </activity>  
       
     <receiver android:name="MyReceiver">  
          <intent-filter>  
               <action android:name="com.mobsandgeeks.action.DEMO_ACTION" />  
          </intent-filter>  
     </receiver>  
   </application>  
 </manifest>  

Source Code
You can download the source from here.

Screenshot

Android - Image Switcher Example

This example demonstrates the use of an ImageSwitcher paired with a Gallery. ImageSwitcher is used to switch between two ImageViews seamlessly by playing an animation during the transition.

main.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:orientation="vertical"  
   android:layout_width="fill_parent"  
   android:layout_height="fill_parent">  
   
      <Gallery  
           android:id="@+id/gallery"  
           android:layout_width="fill_parent"  
           android:layout_height="wrap_content" />  
        
      <ImageSwitcher  
           android:id="@+id/image_switcher"  
           android:layout_width="fill_parent"  
           android:layout_height="fill_parent" />  
 </LinearLayout>

SwitcherActivity.java
 package com.mobsandgeeks.ise;  
   
 import android.app.Activity;  
 import android.content.Context;  
 import android.os.Bundle;  
 import android.view.View;  
 import android.view.ViewGroup;  
 import android.view.animation.AnimationUtils;  
 import android.widget.AdapterView;  
 import android.widget.AdapterView.OnItemSelectedListener;  
 import android.widget.BaseAdapter;  
 import android.widget.Gallery;  
 import android.widget.ImageSwitcher;  
 import android.widget.ImageView;  
 import android.widget.ViewSwitcher;  
   
 public class SwitcherActivity extends Activity implements ViewSwitcher.ViewFactory, OnItemSelectedListener {  
        
      private Gallery gallery;  
      private ImageSwitcher imageSwitcher;  
        
      private ImageAdapter ia;   
   
      @Override  
      public void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.main);  
   
           gallery = (Gallery) findViewById(R.id.gallery);  
           imageSwitcher = (ImageSwitcher) findViewById(R.id.image_switcher);  
             
           imageSwitcher.setFactory(this);  
           imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,  
                     android.R.anim.fade_in));  
           imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,  
                     android.R.anim.fade_out));  
             
   
           ia = new ImageAdapter(this);  
           gallery.setAdapter(ia);  
             
           //Event listener
           gallery.setOnItemSelectedListener(this);  
      }  
        
      private class ImageAdapter extends BaseAdapter {  
           private Context context;  
             
           private ImageAdapter(Context context) {  
                this.context = context;  
           }  
             
           private int[] IMAGE_IDS = {  
                R.drawable.android, R.drawable.gingerbread, R.drawable.honeycomb,  
                R.drawable.lg_optimus, R.drawable.nexus_one, R.drawable.nexus_s,  
                R.drawable.oha  
           };  
   
           public int getCount() {  
                return IMAGE_IDS.length;  
           }  
   
           public Object getItem(int position) {  
                return IMAGE_IDS[position];  
           }  
   
           public long getItemId(int position) {  
                return position;  
           }  
   
           public View getView(int position, View convertView, ViewGroup parent) {  
                ImageView iv = new ImageView(context);  
                iv.setImageResource(IMAGE_IDS[position]);  
                iv.setLayoutParams(new Gallery.LayoutParams(150, 100));  
                return iv;  
           }  
      }  
   
      public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {  
           int imageResourceId = (Integer) ia.getItem(position);  
           imageSwitcher.setImageResource(imageResourceId);  
      }  
   
      public void onNothingSelected(AdapterView<?> parent) {  
      }  
   
      public View makeView() {  
           ImageView i = new ImageView(this);  
           i.setScaleType(ImageView.ScaleType.FIT_CENTER);  
           return i;  
      }  
 }  

Source Code
You can download the source code from here.

Screenshot

Android - Finding current GPS Coordinates

This is a very simple example to find the current GPS coordinates and altitude. In order to use this example you should turn on your device's GPS.

main.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
      android:orientation="vertical"  
      android:layout_width="fill_parent"  
      android:layout_height="fill_parent">  
      <TextView  
           android:id="@+id/latitude_textview"  
           android:layout_width="fill_parent"  
           android:layout_height="wrap_content"  
           android:text="@string/latitude" />  
      <TextView  
           android:id="@+id/longitude_textview"  
           android:layout_width="fill_parent"  
           android:layout_height="wrap_content"  
           android:text="@string/longitude" />  
      <TextView  
           android:id="@+id/altitude_textview"  
           android:layout_width="fill_parent"  
           android:layout_height="wrap_content"  
           android:text="@string/altitude" />  
 </LinearLayout>  

GPSActivity.java
 package com.mobsandgeeks.gps;  
   
 import android.app.Activity;  
 import android.content.Context;  
 import android.location.Location;  
 import android.location.LocationListener;  
 import android.location.LocationManager;  
 import android.os.Bundle;  
 import android.widget.TextView;  
 import android.widget.Toast;  
   
 public class GPSActivity extends Activity implements LocationListener {  
      // UI References  
      private TextView latitudeTextView;  
      private TextView longitudeTextView;  
      private TextView altitudeTextView;  
   
      private LocationManager locationManager;  
   
      @Override  
      public void onCreate(Bundle savedInstanceState) {  
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.main);  
   
           latitudeTextView = (TextView) findViewById(R.id.latitude_textview);  
           longitudeTextView = (TextView) findViewById(R.id.longitude_textview);  
           altitudeTextView = (TextView) findViewById(R.id.altitude_textview);  
   
           locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
           locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,  
                     0, this);  
      }  
        
      public void onLocationChanged(Location location) {  
           String latitude = getString(R.string.latitude) + location.getLatitude();  
           String longitude = getString(R.string.longitude) + location.getLongitude();  
           String altitude = getString(R.string.altitude) + location.getAltitude();  
             
           latitudeTextView.setText(latitude);  
           longitudeTextView.setText(longitude);  
           altitudeTextView.setText(altitude);  
      }  
        
      public void onProviderDisabled(String provider) {  
           Toast.makeText(this, "GPS Disabled", Toast.LENGTH_SHORT).show();  
      }  
        
      public void onProviderEnabled(String provider) {  
           Toast.makeText(this, "GPS Enabled", Toast.LENGTH_SHORT).show();  
      }  
        
      public void onStatusChanged(String provider, int status, Bundle extras) {
      }
 }  

AndroidManifest.xml
 <?xml version="1.0" encoding="utf-8"?>  
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
    package="com.mobsandgeeks.gps"  
    android:versionCode="1"  
    android:versionName="1.0">  
   <uses-sdk android:minSdkVersion="4" />  
   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />  
   
   <application android:icon="@drawable/icon" android:label="@string/app_name">  
     <activity android:name=".GPSActivity"  
          android:label="@string/app_name">  
       <intent-filter>  
         <action android:name="android.intent.action.MAIN" />  
         <category android:name="android.intent.category.LAUNCHER" />  
       </intent-filter>  
     </activity>  
   </application>  
 </manifest>  

Source Code
You can download the entire source code from here.

Screenshot