Jul 30 2009

First steps in Android programming

Published by at 8:03 pm under Android,Java,Mobile phones,programming,Solutions,work

Last week I finished my first Android application. All through the development stage I had to Google a lot for examples which some were really hard to find (even though you can find reference for everything in the SDK, for me, it's easier to understand from a code sample).

My mobile company allows you to send 10 free daily SMS through their website, and after that each text message is still half priced, so I decided to take a challenge and create a UI that allows me to send my messages from the phone through the website automatically.

The core of my software was pure java, so even though it wasn't straight forward to accomplish, I kinda know the material.

The main issues were after – when I got to the android implementation and UI

Here are the issues I needed, and will supply examples for in this post:
(Of course – for you that are more experienced than me with Android development, please forgive if I'm not doing everything 'by the book', it's simply what I could find. So if you have any suggestions or improvement please send them to me or post a comment J )

  • How to find out if there is an active network on the device
  • How to create options menu
  • How to create and clear notification in the notification area
  • How to declare your program as "SMS Sender" ('Complete action using…')
  • Taking care of orientation (Landscape and Portrait mode for UI)

Here is the code I ended up using. Hope you find it helpful

This sample method returns a Boolean that states if there is an active network

private boolean anyNetworkActive() {
         TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
         WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
         WifiInfo wi = wm.getConnectionInfo();
         return !((wi == null || WifiInfo.getDetailedStateOf(wi.getSupplicantState()) == DetailedState.IDLE) &&
tm.getDataState() != TelephonyManager.DATA_CONNECTED);
}

These events populate the menu with text-only options, and do the proper action when pressed

@Override
public boolean onCreateOptionsMenu(Menu menu) {
      menu.add(getString(R.string.menuconfig));
      menu.add(getString(R.string.menuclear));
      menu.add(getString(R.string.menucontact));
      return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
      if (item.getTitle().equals(getString(R.string.menuconfig)))
      // Show config screen
      startActivity(new Intent(this, Prefs.class));
      if (item.getTitle().equals(getString(R.string.menuclear))) {
      // Clear all fields on screen
           messageBody.setText("");
           smsTarget.setText("");
      }
      if (item.getTitle().equals(getString(R.string.menucontact))) {
            getcontact = true; // for sync issues
           // Delete the contactnum variable
           prefs.edit().putString("contactnum", "").commit();
           // Show contact selection screen
           startActivity(new Intent(this, ContactList.class));
       }
       return (true);
}

The first method will create a notification for your user (an icon must be present in the drawable folder)
The second one will clear the notification

public void notifyString(String sTickerText, String sContentTitle, String sContentText) {
          String ns = Context.NOTIFICATION_SERVICE;
          NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
          int icon = R.drawable.notification_icon;
          CharSequence tickerText = sTickerText;
          long when = System.currentTimeMillis();

          Notification notification = new Notification(icon, tickerText, when);
          Context context = getApplicationContext();
          CharSequence contentTitle = sContentTitle;
          CharSequence contentText = sContentText;
          Intent notificationIntent = new Intent(this, PeleSms.class);
          PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

          notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
          final int HELLO_ID = 1;

          mNotificationManager.notify(HELLO_ID, notification);
}

public void clearNotification() {
          String ns = Context.NOTIFICATION_SERVICE;
          NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
          mNotificationManager.cancel(1);
}

These methods and AndroidManifest.xml changes will declare your program as an SMS Sender, and the user will be asked if he/she wants to use it instead of the built in messaging client when trying to send a text message (with the "Complete action using..." menu, screenshot above)

AndroidManifest.xml:

<intent-filter>
     <action android:name="android.intent.action.VIEW" />
     <action android:name="android.intent.action.SENDTO" />
     <category android:name="android.intent.category.DEFAULT" />
     <category android:name="android.intent.category.BROWSABLE" />
     <data android:scheme="sms" />
     <data android:scheme="smsto" />
</intent-filter>

Catching the intent in the beginning of activity:

@Override
public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         String param = getIntent().getDataString();
          ....

Orientation:

The grand finale. This is as simple as can be… no code needed. All you need to do, is create two folders under the root of your project: layout-port and layout-land
Then, move your UI XML to the layout-port folder, and create a copy of it with the same name in layout-land folder. That's about it. Of course, you need to adjust the layout for each. Android will know when to use which

Well, I hope I got you through rough times if you found this post useful. I know I wish I bumped into one like it J

Last thing: This is a ListActivity I created using some examples I found... It displays a list of your contacts and by clicking one, saves his phone number in a Shared Preference. Note that you must grant permission for reading contact in your AndroidManifest.xml

public class ContactList extends ListActivity{
private ListAdapter mAdapter;
SharedPreferences prefs;

/** Called when the activity is first created. */
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        Cursor contactsCursor = this.managedQuery(People.CONTENT_URI,
                     null, null, null, "People.NAME ASC");
        startManagingCursor(contactsCursor);

        String[] columnsToMap = new String[] {People.NAME};
        int[] mapTo = new int[] {android.R.id.text1};

        mAdapter = new SimpleCursorAdapter(this,
                     android.R.layout.simple_list_item_1,
                     contactsCursor, columnsToMap, mapTo);
        this.setListAdapter(mAdapter);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Cursor C = (Cursor) mAdapter.getItem(position);
String phoneNumber;
int phoneColumn = C.getColumnIndex(People.NUMBER);
phoneNumber = C.getString(phoneColumn);

//SharedPreferences.Editor editor =
prefs.edit().putString("contactnum", phoneNumber).commit();

finish();
}
}

That's about it... If you need more info on anything I've posted here just contact me or leave a comment

UPDATE: I have added some code to our project repository SVN.
It does not contain the actual backend SMS sending, since this is pure java thing, and I don't want to piss off my cellular company (making them stop giving away 10 free per day maybe? ). The project name is AndroidFirstSteps
http://morethantechnical.googlecode.com/svn/trunk/

Share

12 responses so far

12 Responses to “First steps in Android programming”

  1. Coy Hickleyon 09 Jan 2010 at 6:33 am

    Hello, I recently bought a Samsung Galaxy i5700 Spica and I have to say that I love Android it is by far the best mobile os I have tested. The endless supply of apps makes every day with my phone an new experience.Sorry for my rant I just wanted to tell you my experience with the android os. Have a great day and thanks for a superb blog.

  2. Gregoria Bruinson 02 Feb 2010 at 4:35 pm

    I favor articles like this becaus they always seem to provide to you a completely different perspective on things. I am no expert during this area however wish to expand my information by reading things of this nature.

  3. Nagrajon 07 Dec 2010 at 3:15 pm

    Hi, I am an Engineering student studying in my final year, as my final year project i have chosen a client server like project on a Android Platform. As I have no guide for learning Android SDK and its various features, I am finding it a bit difficult to mo ahead. Please let me know if u can provide me some help with this regard.
    Thank you.

  4. Arnonon 07 Dec 2010 at 5:13 pm

    I cannot share any specific guide to give you a headstart. I usually look for specific things and examples when I want to do things on Android. Basically a client-server model in Android shouldn't differ much from Java
    I know it can be hard to start with Android, it's not that trivial. I would advise you to start with the examples provided with the SDK.
    I myself spend hours and hours googling for specific solutions.
    If you have any specific question, please drop me a line to my mailbox (found in the About us page)

  5. Jimon 25 Jan 2011 at 9:17 pm

    Hey nice tutorial! This is a pretty good web series to learn android for beginners as well: http://www.youtube.com/cornboyzandroid

  6. abdulon 05 Aug 2011 at 9:57 pm

    @Nagraj, i started working on an app not long time ago, but i found this website really helpful, http://www.vogella.de/articles/Android/article.html#menu_overview , my comments are pretty late but it's still useful.

  7. LOKESH KUMAHARMA SJon 21 Feb 2012 at 4:32 pm

    i want to know about the android application and from where i need to start..................please reply.

  8. Arnonon 21 Feb 2012 at 7:24 pm

    You need to start by downloading eclipse and the Android SDK

  9. Royon 21 Feb 2012 at 10:21 pm

    @lokesh
    Start by downloading the Android SDK:
    http://developer.android.com/sdk/index.html

  10. Murlion 08 Mar 2012 at 12:06 am

    Cool post! Its has become so easy to make a simple app now!!!

    Heres my attempt at a simple hello world app for android!
    http://farasbee.com/blog/2012/03/07/developing-a-android-app-without-a-laptop-or-a-computer/

  11. Best of Androidon 14 Aug 2012 at 8:02 pm

    Very useful info for newbie android developers. Thank you very much.

    -----------

    Dhanaiah
    Best of Android | Android News | Best Android Apps | Android Games | Android Devices

  12. Linon 29 Aug 2014 at 1:57 am

    Good day! Do you use Twitter? I'd like to follow you if that
    would be ok. I'm definitely enjoying your blog and look forward to new updates.

Trackback URI | Comments RSS

Leave a Reply