The NEW Android Location API

Android | Tuesday September 2 2014 11:18 | Comments (3)

Since the release of the new Google Play Services 4.2, some new APIs have been added and Google have changed their Client API Model. One such API model to be affected is the Location API.

If you are targeting the latest version of Android in your app, you will see that your existing Location API code will now be flagged as being deprecated.

Previously, you would interact with the Location API as follows:

    LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    String provider = locationManager.getBestProvider(criteria, false);
    locationManager.requestLocationUpdates(provider, updateInterval, 0, this);

    ....
    public void onLocationChanged(Location location) {
        //Handle location update
    }

Now with the new Location API, it will look similar to this:

    GoogleApiClient mGoogleApiClient;
    LocationRequest mLocationRequest;
    ...
    mGoogleApiClient = new GoogleApiClient.Builder(this)
    .addApi(LocationServices.API)
    .addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this)
    .addOnConnectionFailedListener(this)
    .build();

    ....
    public void onConnected(Bundle arg0) {
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

        ...
    public void onLocationChanged(Location location) {
        //Handle location update
    }

You’ll need to import:
com.google.android.gms.location.LocationServices (thanks Mark)
com.google.android.gms.common.api.GoogleApiClient;
com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener
(note it’s the GoogleApiClient, instead of the GooglePlayServicesClient version).

As well as LocationListener, your class also needs to implement ConnectionCallbacks and OnConectionFailedListener (assuming the same class is handling all the callbacks).

Also, onDisconnected() has been renamed to onConnectionSuspended(int cause).

Quick android tip, with ems (setEms())

Android | Saturday April 13 2013 14:26 | Comments (0)

I recently ran into an issue with my TextView not wrapping text. For some reason, if the line was too long, it would continue off screen.
I tried many different fixes from across the web, but none worked. I thnk the main problem was that I was not using a defined layout in XML, but rather creating the textview dynamically upon encountering an error.

The answer that I finally settled on was the use of em’s (http://en.wikipedia.org/wiki/Em_(typography)). This type or measurement relates to font sizes, and in Android, helps keep fonts and other objects the same relative sizes across any screen size or resolution.
Loosely speaking, a typical screen width in ems, is equivalent to (the screen width / 24). Going back to my original problem, where I had the text go off the screen, I could use this calculation to set a max width of the text view, and manually make it wrap the text.

Since I also target older versions of android, eg 1.6 and 2.2, I had to use an older deprecated method to get he screen width. If you only target newer versionm eg API 17+, you can use the DisplayManager, but if like me, you want to have maximum compatibility, then you can use the following code to set the width of a layout to be equal to the screen size of whatever device you’re on:.

Display display = activity.getWindowManager().getDefaultDisplay();
int width = display.getWidth(); // deprecated
TextView tvError = new TextView(this);
tvError.setEms(width/24);

Android does come with some built in functions to help text wrap, but from some discussions online, I saw that certain themes, eg Holo, can cause issues like what I’ve experienced. This fix only came about because I didn’t want to change from the Holo Theme.

I hope this helps someone.

EDIT:
Since the above method uses deprecated methods to get the width, I think its best to update this post with the current recommended methods of getting both the width, and the height of a screen in Android:


final DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
final int height = displayMetrics.heightPixels;
final int width = displayMetrics.widthPixels;

Free Blackberry PlayBook for Android developers

Android,Blackberry,Mobile Development | Tuesday February 14 2012 22:21 | Comments (1)

I recently got an email from a tech magazine I’m subscribed too. Usually they have interesting articles, and all the news in the world of Computers and Technology, as would be expected. However, in last weeks magazine, there was an interesting article relating to Blackberry and their flagship tablet, the PlayBook.

With the imminent release (at time of writing) of their OS2.0 software, Blackberry have decided to give away free (yes, FREE) PlayBooks to any developer who submits an app specifically for the tablet before the deadline. Since the new OS contains its own implementation of Android, which allows Android Apps to run pretty much natively, the offer was originally open exclusively to Android developers. However, with a flood of complaints from existing Blackberry devs, and some noise from iOS and WP7 developers, Blackberry decided to open up the offer to any dev, of any platform, who submits an app before the deadline. Originally the deadline was Monday 13th Feb 2011, but since they’ve had an overwhelming response (over 6000 new devs submitting at least 1 app) since last week, they have extended the deadline. Developers have until Wednesday the 15th of Feb to register as a dev, and until March 2nd to submit an app.

Blackberry PlayBook

There is a bit of small print, however. Not every app will be accepted, and qualify for the free PlayBook. The app has to be of sufficient complexity, and be deemed (by a human tester) to be something that people will be interested in. Examples of apps that will be rejected are: Web Browsers, shortcuts, themes/wallpapers and web apps. They’ll also reject apps with a single function like a “Fart Button” or Buzzer app.

Since I stumbled across this offer, I have submitted my Lotto App, which has been accepted. I even got the email asking for my shipping address, and expect the tablet to be shipped any day now, all for the one time fee of ZERO!! 😀

For anyone looking for info, here’s the latest link with info on the deadline extension:

Free PlayBook offer extended

Technical Specs of PlayBook:
1Ghz dual core processor
1GB RAM
HTML5 / Flash 10.2
Proper multitasking due to QNX
7 inch screen
Weight: 0.9lb/425g
Width: 7.6/194mm
Height: 5.1/130mm
Thickness: 0.4/10mm

1080p Playback
3MP front camera
5MP back camera

New Android app: Medical Student MCQ App

Android | Saturday October 22 2011 18:08 | Comments (0)

So, after being bitten by the Android Publishing bug with my first app, the Irish Lotto helper app, it’s no surprise that I jumped at the chance to create a 2nd app, when the opportunity came knocking.

My 2nd app, which has just been published, is called Medical Student MCQ App.

The purpose of this app is to aid Medical Students who are in their final year of med school, by asking them a difficult multiple choice question (MCQ) once per day, for the entire duration of their college year. The theory behind it is if they can learn that one piece of information each day, then by the end of the year they should fair much better in their exams!

The idea for the app came about when my brother, who is an experienced paediatrician, asked me if it would be possible to make such an app. I responded positively and we decided to take it from there, with me doing the technical side, and him writing the questions.

For this to be as efficient as possible, I had to write a basic web form in PHP, using a MySQL backend. He could simply fill in the form with a question, 5 possible answers, a radio button representing the correct answer, and a textarea at the bottom for him to fill in the “tip”. The tip pops up when the user gets the correct answer, and gives them an expanded explanation of why the answer is correct.

Anyway, due to time constraints, we had to enlist 2 other doctors to help with the questions. This worked out well as now we have a team of 3 doctors, each with their own specialised field, able to write relevant and helpful questions.

On the client side, I had to choose between including the full database, or forcing the user to download the database on first run. I chose the latter, and for good reason.

Due to the number of questions, it is possible that errors could sneak in somewhere. Rather than releasing a new app version for each spelling mistake, and hoping everyone upgrades promptly, I thought it would be better to have direct control over the content they see every day. To achieve this, I have put in an “update” button in the menu, whereby the user can download the latest database at the touch of a button. This will include all the updated/refined questions, without forcing an app update through the market. Also, if we want to add new questions, or remove questions completely (maybe due to curriculum changes) I can do so through my little web front end that I built for this.

Medical Student MCQ app, available for 4 euro from the Android Market

The app is available now, for a small price of €4, and is available for download from the Android Market here:
Medical Student MCQ App

-Eoin

New Android app: Lotto Helper IE

Android | Saturday October 22 2011 17:49 | Comments (1)

So, after dipping my toes in the Android water over the summer, I began working on my own app.

I took me roughly one month to do it, from start to finish. Admittedly, I slowed down once college started, but that’s to be expected since I did have to learn Python, and Django, as well as how to parse websites!

So, what does my first app do exactly? Well, its called Lotto Helper IE. It is an app to show the user what the most common lotto numbers are in the Irish lottery since its inception in 1988. I basically parsed a website with all the numbers, put them into an XML file, and from there I counted each number and sorted them in order. The problem with this method is that, in 1992 the Irish Lottery Commission added some new numbers, extending them from 35 to 38. The Bonus ball was also added. A few years later, the numbers were then extended to 42. Now, based on frequency alone, this would lead to inaccuracies, since the draw began in 1988 and some numbers were only added 4-6 years later.
To counter-act this, I’ve made a few tweaks. Firstly, I counted how many draws were missed by each new number. Then I subtracted that from the total amount. I could then work out an accurate percentage and sort the numbers by this.

On top of this, I have also added in support for the Euromillions. Similarly, I parse the numbers, store in XML, and then do some calculations. The result gives me an ordered list of the monst common numbers, and how many times they’ve come out.

On the Irish Lotto website, there is a number checker. I’ve checked my predicted numbers and they seem to be doing well. Over the last month, anyone who had played these numbers would have netted themselves over €30! Not bad for a free app!

Apparently, there is big business in betting shops where people can bet on number pairs to come out in each lotto draw. I’m hoping to extend the app to include a feature like this. In the meantime, I’ve a “stats” screen, which displays the raw data for each number in both the Irish Lotto, and the euromillions. I’ve a few hundred downloads so far, which is cool, ranging from Ireland, the UK, and America to Eastern Europe, China and even Brazil!

Lotto Helper IE available for free from the Android Market

My first personally publish app can be download, for free, from the Android Market here:
Lotto Helper IE

-Eoin

Android read sms inbox fields

Android | Wednesday March 30 2011 23:41 | Comments (0)

While I was doing some work on an android app (possibly related to my previous post ;)) I came across a problem. Google don’t seem to want people messing with their SMS inbox, for whatever reason, so have decided to put as little documentation on their site as possible.

So, in order to retrieve data from an SMS inbox you need 3 things:

  1. The URI of the inbox
  2. A Cursor to traverse the texts
  3. Some idea of what fields will be returned by the cursor.

After some Googling, I have found that most people use the inbox URI like so:

Uri uriSms = Uri.parse(“content://sms/inbox”);
Cursor c = getContentResolver().query(uriSms, null,null,null,null);

I have tried this and it works, if you want to retrieve the texts that people have sent you, but not for ones you’ve sent.Here is the complete list of URI’s for SMS.

All: content/all
Inbox: content/inbox
Sent: content/sent
Draft: content/draft
Outbox: content/outbox
Failed: content/failed
Queued: content/queued
Undelivered: content/undelivered
Conversations: content/conversations

Others have said online, this is not the best way to do it. You can also use the built in SmsManager class but I haven’t had time to look at that yet. Hopefully its easy enough to use.

Next up is the cursor, which is easy enough, and is used as follows:

Cursor myCursor = getContentResolver(UriSMS,null,null,null);

The 2nd “null” here is for the fields you want to retrieve. Putting “null” is effectively like saying “SELECT * FROM inbox”. We can specify other fields to retrieve like “body” or “date” or “person” but what I had trouble with was actually finding documentation on which fields are available.

Which brings me to my 3rd point. There is a built in method on the cursor that can return the name of each field. Using this, I’ve made a list of what fields can be retrieved from the outbox.

Starting from myCursor(0) to myCursor(15):
0: _id  (long)
1: thread_id   (long)
2: address   (String)
3: person   (String)
4: date     (long)
5: protocol
6: read
7: status
8: type
9: reply_path_present
10: subject    (String)
11: body    (String)
12: service_center
13: locked
14: error_code
15: seen

So there ya have it. Some basic SMS retrieval info. I might update this when I look into the SmsManager class in more detail.

C ya.

Double Snap!!

Android,College | Saturday March 26 2011 14:44 | Comments (0)

As with everything in the world of IT, ideas move fast! And they get replaced with ideas even faster.

About 5 minutes after I posted my last blog entry, I joined up with another group of programmers, who are making an app. Its a good idea for an app, and I reckon it should be good experience and look good on my CV.

With this app, there is scope to market it, in cooperation with some marketing people who have expressed interest in it. Also, we will be entering it in a competition, sponsored by Vodafone, called App-o-vation. The winners of this get backing from Vodafone, who will then distribute it through their channels and make it available through their web store.

I can’t give too much away, but put simply…..watch this space!!

A little side project

Android,College | Tuesday March 8 2011 00:16 | Comments (0)

Following on from my last post about RESTful services, I’ve recently gotten an Android phone (HTC Desire) and have downloaded the Android SDK to have a little play around with it. I’ve managed a simple “Hello World” app, but nothing more yet. I have another subject in college that deals with mobile computing where, as part of our grade, we have to develop a smartphone app.

As it stands, to test the project, there will be a need to commandeer either a college computer, or bring in my own laptop to demo the server backend, but ideally I’d like to combine both the year long project and this other mini-project and create a server on an Android phone, which is capable of running a RESTful service and spitting out XML to be consumed by the iPhone, or indeed any client running on the network that is capable of displaying Google Map data.

So, this would be handy for 2 reasons:

  1. I always have my Android phone on me.
  2. I wont need to bring my laptop to college.

If this is possible, it would really look good on my CV, and would probably be something that would get a lot of downloads on the Android Market….which would nicely pad out my CV more, and kick start my portfolio, which at the moment is depressingly empty!! 🙁

However, if its not possibly, or feasibly for someone with basic knowledge, such as myself, then I suspect a little game of SNAP on the Android might be “on the cards…”!

Google Maps API – Intro

Android | Wednesday February 9 2011 16:44 | Comments (0)

I’ve gotten down to the nitty gritty of actually making an app that uses Google Maps, which means finally trying to get a map on the screen and at least pick up my location automatically.

To get a basic Google Maps app up and running, its surprisingly easy! Yes, to just have the app pinpoint your location using GPS, its shockingly simple! The reason for this is that Google have done all the hardwork for you. All we, as developers, have to do is call the javascript file on the Google servers and hey presto. For example: Geolocation test . Yes, its that easy, providing you have internet access, obviously! The source code, if needed, can be found here: Maps source

In case you’re interested, there are lots of examples on Googles website here: Google Map Examples

So, now we have a basic application that detects the users location and centres the map on it. However, as you can see in the first link above, the zoom level is a bit too high. Also, we will want to add markers on the street corresponding to the coordinates of the bike stations, or whatever place of interest you’re intending to map. This is more complicated and will be covered in the next section! 😀

SQLite – Database Intro

Android | Wednesday January 26 2011 17:56 | Comments (0)

Since I finished my exams last week, I’ve began working on a little small personal project. In my research for that, I’ve come across SQLite.

For those of you not familiar with it, SQLite is basically a really light database, built in C, that doesnt require its own server, thus requires no installation of any kind. You can literally just include the database file and not have to worry about anything else.

Using Visual Studio 2010, you can do one of two things:

  1. Get the installer from sqlite.phxsoftware.com that automatically integrates with Visual Studio, or
  2. Download the SQLite DLL and add it as a reference in your Project Solution.

The first option is probably easiest, as you can use Visual Studio to create and edit the database through Server Explorer, eg right-click on Data Connections, select New Connection and select SQLite.

The second way, you will need to get 3rd party software to create and edit the database. Of course, you’ll probably be writing software that does edit your database, so you just really need the DB created initially. I’m not sure if it can be edited within Visual Studio, but I could be wrong, as I was using the first method in my testing.

SQLite is really handy for small projects, and portable projects, and in fact, is probably the most widely used database in the world!! Firefox uses SQLite, iPhones use SQLite, and probably a lot of other mobile platforms like Android might use it too! This isnt even taking into account all the private projects developers use it for, and a lot of other personal projects, like mine! With Firefox and iPhone alone though, it still covers a wide user base!

Anyway, to tie in with my college project, I’ve decided that SQLite will be the official database technology of the iPhone app. I’ve used mySQL before so have experience with using SQL statements and SQLite uses most of them, with the exception of GRANT and a few others that I won’t be using anyway!

Is there a better database solution than SQLite for lightweight, portable, speedy applications? Let me know…

Eoin