Monday, October 10, 2011

Trouble in Android Wifi land

It has been a while since I posted last, but there are some issues with how Android handles the WPA/WPA2-Enterprise modes. Hopefully making these issues a little more public will help get them fixed. (And, before you start throwing things, yes, Google is aware of these issues.)

Let's start with an easy, common issue. Self signed certificates. There are many tutorials on the net about how to configure WPA/WPA2-Enterprise using self signed certificates. I would imagine that for any IT person that is trying to wrap their heads around 802.1X/WPA/WPA2-Enterprise, they are one of the first stops. Hopefully, Android isn't running on their primary test device.

If you attempt to use a self signed certificate on Android, it will usually fail. I have run across the occasional device that doesn't have this problem, but 'stock' Android like that found on the Nexus series generally has this problem.

Not being able to use self signed certificates is annoying, and it leads us nicely in to the next Android annoyance. To paraphrase, "If an Android fails to authenticate, and nobody is watching the logs, did the authentication actually fail?" I think the best answer is, "If I didn't get my network access, then yes, it failed." However, because Android didn't tell you that it failed, you may be sitting there for some time before you realize something is wrong.

Let's jump back to the self signed certificate issue I mentioned above. I like to say that in the event of an error case, the program usually has some idea of what went wrong. It just needs to present that information to the user in a useful way. This case is no different.

Under the hood, Android uses wpa_supplicant to handle authentication 802.11 management and authentication. In the self signed certificate case, wpa_supplicant will produce an error such as this :

TLS: Certificate verification failed, error 18 (self signed certificate)

This error is usually surrounded with a bunch of OpenSSL error codes so many people just "check out" when reading the logs, and don't notice it. On Android, it is a little bit worse. This error message is buried in a log that the average user probably doesn't even know exists. So, how does the user know what went wrong?

In this example, the user figures it out after sitting there for a while and they don't get a connection to the network. But, once they have come to the conclusion that they can't get on the network, what are they supposed to do? Worse, what is the helpdesk call going to sound like? I need you to summon your best red-neck, inbred, hillbilly with buck teeth accent and said, "It's broke". ("It don't work" is another wonderfully helpful description.)

Since most users have a really short attention span, at this point they wander off to complain to anyone they can that the network is broken. When a coworker or friend says, "Yeah, but it works for me." that will change to "Wireless is broken on Android."

The reality is that Android's wireless is NOT broken. Well, maybe not very broken. When the wireless hardware is behaving itself, wpa_supplicant does a fine job of getting you connected. You just have to be running something like CatLog, or have a development environment set up that will let you run "adb logcat". Then, you have to know enough about 802.1X authentications, and certificates to be able to recognize the one log line that tells you everything you need to know about the failure. That should be easy enough. (In case you are missing my sarcasm, consider trying to talk your mom through figuring this out over the phone.)

While I use the self-signed certificate issue as an example of the problem, it is just the tip of the iceberg. Other similar issues, that you won't hear about, include :

  • The certificate isn't yet valid.
  • The certificate is no longer valid.
  • Your authentication failed.
  • MS-CHAPv2 messages such as 'invalid password', or 'your password has expired'.
  • And many, MANY others.

Let's assume that you understand these issues, have the tools to figure them out when they happen, and work in a small enough business that the helpdesk can go through this dance with everyone in the company. Out of nowhere, you get slammed with an issue you CAN'T fix!


Here, you will find your next issue. Section F, item 2 basically says that CAs can no longer sign certificates with their root certificate. Or, in other words, all certificates have to be signed by an intermediate CA cert. Now, I understand that Microsoft isn't a standards setting body, so CAs don't have to comply with these rules. However, as Microsoft is still a dominant OS provider, CAs that don't comply won't be allowed in the shipping Microsoft cert store. Based on this, it is pretty reasonable to assume that most CAs will follow these rules.

The problem this creates for Android shows itself when you try to install a chain of certificates on Android. I was unable to find any sane way that worked. Digging in the Android source code seems to indicate that cert chains can be installed using PKCS#12 certificate bundles. However, Android seems to insist that PKCS#12 certificate bundles contain a user cert. In other words, if you are using anything but EAP-TLS, you probably can't use PKCS#12 bundles to get your certificates in the store.

It may seem reasonable that creating a PEM file that has multiple certificates in it would get around this issue. However, if you try that, you are presented with the following dialog :




Note that the dialog indicates that there is only one CA certificate that will be installed. If you complete the installation, and set up a new wireless authentication using this certificate, you will find the connection doesn't work. If you happen to have CatLog, or a development machine around you will see in the logs that the certificate chain failed to validate.

If you can't use self signed certificates, and can only buy certificates that are chained, it starts to become clear that the 802.1X/WPA-Enterprise/WPA2-Enterprise authentication on Android is darn near unusable. You either need to find a CA that is willing to go against Microsoft. Or, you have to choose not to use certificates in your authentications. (Which, is a *BAD* idea!)

I just want to restate that Google has been made aware of these issues. However, it was recent enough that they probably haven't had time to do anything about it, let alone get anything fixed and released. Also, since I get really annoyed with people that like to complain, but don't offer any real solutions, I will be submitting patches to Google that will hopefully start to fix some of these issues. At a minimum, hopefully Google can use my patches as a jumping off point for a good fix.

Monday, April 11, 2011

Color changing rounded rectangles and Android

I recently came across an interesting problem. I needed to have a rounded rectangle as the background of one of my widgets, but I needed to allow the border color of the rounded rectangle to be set by a configuration setting.

Before the color changing requirement showed up, I was using a 9-patch to create my rounded rectangle. It was simple, and worked quite well. So, after some digging I came to the conclusion that I would need to change the colors in the 9-patch image in order to achieve my goals. I ended up burning a lot of time trying to figure out how to do this. (It isn't as simple as changing the colors in a normal .png file, unfortunately.)

While digging, I came across this post that hinted that I might not need the 9-patch to do what I wanted. But, the documentation for the shape XML is pretty much non-existent. Which made things hard.

A little more digging found an article that linked to this page. This provided me the attributes for the XML that allow me to do what I needed to do. So, I set out to give it a shot. I started with a rounded rectangle with a white background and a black line around the outside. The XML looked like this :

<!--?xml version="1.0" encoding="utf-8"?-->
<shape android="http://schemas.android.com/apk/res/android" shape="rectangle">
<solid color="#ffffffff">
<stroke width="2dip" color="#ff000000">
<corners radius="75dip">
</corners></stroke></solid></shape>


When I created the XML file in eclipse, there wasn't an option to create a shape XML file. So, I picked one of the other types, and just deleted what was automatically created, and replaced it with the code above. However, I also needed to move the XML file so that it was in the drawable directory. (If you are like I was, you are thinking, "But an XML file isn't a drawable!" But, you'll just have to trust me.)

This provided me the basic rounded rectangle that I needed. But, changing colors on-the-fly was still an issue. After a bit of digging, I found that using this XML to create a drawable would give me everything I needed to get the job done.

I decided to set the background for the layout that contained everything I was going to use. (Which is why I am using a LinearLayout instead of some other widget. But, any widget that allows a background to be set should work.)

For a test, I changed my onCreate() method to include this code :

workareaLayout = (LinearLayout)findViewById(R.id.rightColumnInner);

GradientDrawable sd = (GradientDrawable)this.getResources().getDrawable(R.drawable.roundrect);
sd.setColor(0xff00ff00);
sd.setStroke(10, 0xffff0000);
workareaLayout.setBackgroundDrawable(sd);

This created a nice rounded rectangle that is suitable for Christmas. (It has a green background with a large red border.)

The sd.setColor() call sets the background color for the rectangle. The color is an ARGB value, so we start with 0xff since we don't want any transparency. The 00ff00 portion indicates that we want to be the brightest green we can have.

The sd.setStroke() call specifies the width of the border line, along with the color. For this example, the width is 10, and the color is bright red, with no transparency. The documentation isn't clear what a width of "10" means. (Is it pixels? Or one of the other measures commonly used in Android development?) But, it appears that it is probably pixels.

And with that, you should have the ability to create all kinds of crazy rounded rectangles. However, keep in mind that this same method should work for other types of shapes that can be created with the shape XML.

Thursday, November 11, 2010

Getting ADB to work with the Samsung Tablet

It is a neat little device, the Samsung Galaxy Tablet. However, as soon as I got one, I wanted to hook it to my computer and run some of my code on it. Easy enough, right? Well, not exactly.

After fighting with it for several hours yesterday, I gave up and called it a day. This morning I posted to the Android developers list looking for help. Then, on a hunch, I installed the Samsung Galaxy S driver pack, and managed to make progress.

I downloaded the driver from here. Make sure that you click on the link that says "Softpedia Secure Download" as there seem to be a lot of ads on the page that try to get you to install other crap.

Once you have the driver downloaded, unzip it someplace. (I threw it on the desktop, because it was easy.) Then, open the control panel, go to System, then Device Manager, and find the SAMSUNG_Android device that should be listed in the "Unknown Devices" section. Right click the device, and select "Update Driver Software...".

Next, select the option to "Browse my computer for driver software", then enter the path to the "USB Drivers" directory you extracted from the download. Make sure that the "Include subfolders" option is checked, and click Next.

At this point, the main USB driver should be found. After waiting a second, you should see a couple of new USB devices show up in the "Unknown Devices" section. One will be a modem interface, the other is the ADB interface that we want to use.

If you follow the same procedure above on these new devices you should be able to get the correct drivers installed. Once all of the drivers are installed, you should be ready to go! Running "adb devices" should show your Samsung tablet.

Sunday, October 17, 2010

Fancy List Items in a ListView

A while ago, I was working on a project where I wanted to be able to have Android show a ListView, with custom entries in the list. In most other languages and toolkits, doing this is a bit of a pain. You have to implement a special painter to pain the list cell in just the right way. Unless you are a pretty die-hard developer for that toolkit you may find yourself horribly confused as to how to handle the situation.

Fortunately, Android made this REALLY easy. If you know how to do a layout for a form, you know almost everything you need to know in order to make a fancy list item.

First, you want to create a small layout that specifies how a single list entry should look. For my purposes, I wanted to have a single line of large text, with smaller text below. I also wanted the large text to be bright white, and the smaller text to be a darker gray color. Finally, the smaller text should be indented on both sides to indicate that it is subordinate to the larger text.

No problem! A basic linear layout will do the job nicely. My final layout looks like this :


<linearlayout android="http://schemas.android.com/apk/res/android" layout_height="wrap_content" layout_width="fill_parent" orientation="vertical">
<textview layout_height="wrap_content" id="@+id/LargeText" text="Large Text" textcolor="@color/white" textsize="25dip" layout_width="fill_parent"></textview>
<textview layout_height="wrap_content" layout_width="fill_parent" layout_marginright="10dip" layout_marginleft="10dip" id="@+id/SmallText" text="Smaller Text" textcolor="#c0c0c0"></textview>
</linearlayout>


Easy enough. Now that we have that, we need to actually write some code that will use it. I find it easiest to create a convenience class that lets me manipulate the list easily. So, I create a class called MultiLineList, that looks something like this :


import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.widget.SimpleAdapter;

public class MultiLineList {

private ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
private Activity parentActivity;
private SimpleAdapter taskAdapter;

public MultiLineList(Activity parent)
{
parentActivity = parent;

taskAdapter = new SimpleAdapter(parentActivity, list,
R.layout.multi_item_layout, new String[] { "largetext","smalltext" },
new int[] { R.id.LargeText, R.id.SmallText } );
}

public void clear()
{
list.clear();
}

public void addItem(String largeText, String smallText)
{
HashMap<String,String> item = new HashMap<String,String>();
item.put("largetext", largeText);
item.put("smalltext", smallText);
list.add(item);
}

public SimpleAdapter getData()
{
return taskAdapter;
}
}


In the constructor, we create a SimpleAdapter that we use to map our text in to the different rows of the list view we will show the user. "R.layout.multi_item_layout" is the name of the layout we created above. (You may need to change this if you called your layout something else.) The two strings, followed by the two ints give us a mapping in a hash table for how to identify the two different TextEdits that we put in the layout. There is nothing special about only having two items. We could easily have 10 strings and 10 matching ints. What is important is that each string has a corresponding int that maps to a text edit in your layout.

The addItem() method is where the good stuff happens. As part of creating the SimpleAdapter in the constructor, we told it to use the "list" variable to get its data out of. So, the addItem() method allows us to easily put new text in to the list to be used. So, calling addItem("I am big", "I am not") would give us a single entry in the list view that contained the text "I am big" in the large font, and "I am not" in the small font.

Now that we have all of the ground work in place, it is time to put the pieces together. Moving forward, I am going to assume that you have a basic form set up with a list view configured in it. Also, that a ListView variable points to it called "listView". From there, using our fancy list widgets would look something like this :


myList = new MultiLineList(this);
myList.addItem("Large 1", "Small 1");
myList.addItem("Large 2", "Small 2");

listView.setAdapter(myList.getData());



Now, the next time out list view is drawn, it will contain two items in the list. The first one will have "Large 1" in the larger text, and "Small 1" in the smaller text. The second one will contain "Large 2" in the larger text, and "Small 2" in the smaller text.

From this simple example, you should be able to easily expand your list items to contain any just about any widget type you would want. But, I leave that up to you to experiment with.

Saturday, August 7, 2010

Its all about the layers..

For an Android project I am currently working on, I wanted to take an image of the last state of my game board, and overlay another image on it. While this seems like a simple thing it wasn't terribly simple to figure out. (Though, it is surprisingly simple to implement.)

To make this easy, lets assume you have two bitmaps. We will call them bitmap1, and bitmap2. Also to make it easy, we will assume they are stored as drawables in your Eclipse project.

It is also important to note that bitmap2 must have some transparent areas on it. If bitmap2 is completely opaque, you won't see any of bitmap1, and this code will be a waste of effort. (Since you could just draw bitmap2 by itself.)

The first thing we want to do is get our drawables stored in Bitmap objects. These bitmap objects should be called bitmap1 and bitmap2. This is easily done with the following code :


BitmapDrawable draw1 = (BitmapDrawable)res.getDrawable(R.drawable.bitmap1);
Bitmap bitmap1 = draw1.getBitmap();

BitmapDrawable draw2 = (BitmapDrawable)res.getDrawable(R.drawable.bitmap2);
Bitmap bitmap2 = draw2.getBitmap();



That was easy. Now, we have to figure out how to combine the two. This is where things start to get a little less obvious. After Googling around, I found several different methods that could do it. But, the method I am going to use below seemed the most straightforward to me.

First, the code, then the explanation :



Bitmap layers = Bitmap.createBitmap(bitmap1.getWidth(), bitmap1.getHeight(), bitmap1.getConfig());
Canvas c = new Canvas(layers);
c.drawBitmap(bitmap1, new Matrix(), null);
c.drawBitmap(bitmap2, new Matrix(), null);



Believe it or not, you now have a merged bitmap in memory. (But how? It looks like all I did was draw on a canvas!?)

Simple, if you look at the Canvas class, you will find that one of the constructors allows you to pass in a Bitmap object. When you do this, anything that is drawn on the canvas is put in to the Bitmap that was passed in. So, in our example above, if we wanted to see the result, we could draw the Bitmap object 'layers' to the screen, and we would have the image of bitmap2 laid over bitmap1.

Or, to look at it another way. If you were working with a SurfaceView, and wanted to draw the bitmaps there, you would create a Canvas object, draw the two bitmaps in order, and pass the Canvas to the SurfaceView where it would be drawn. The code here does the same basic thing. However, instead of having the code drawn immediately on the SurfaceView, you have the output sent to a Bitmap.

But, lets look at some assumptions in this code real quick. When we create the 'layers' Bitmap object, we have to tell the Bitmap object a little bit about the bitmap we want to create. Specifically, we have to tell it what the size of the bitmap is, and what the configuration of the bitmap is. The size is fairly obvious. But, in the sample code above, we are assuming that either the two bitmaps are the same size, or that bitmap2 is smaller than bitmap1. If bitmap1 is actually smaller than bitmap2, then the final bitmap will be the same size as bitmap1, and bitmap2 will be clipped to fit. But what about the configuration? What is that? The configuration is a value that tells the bitmap what kind of data it will be storing. Or, another way to look at it, how big each pixel will be in memory. Without getting in to a bunch of detail, under normal circumstances, you will want to use ARGB_8888.

Why the heck would you ever do this? Well, if you needed a composite image that would be used repeatedly in your program you could either try to draw it in real-time every time it was needed, or draw it once and just reuse the drawing. If the image is more than a few pixels, recreating the overlay each time could be an expensive operation. Caching the result and using that instead can save you a fair bit of processing time that you can use for other cool effects in your program!

Monday, July 12, 2010

The right way to do databases in Android

Feel free to comment below on what a loser I am. I am sitting in a cabin outside of Yellowstone National Park, writing a blog entry about doing databases on Android. However, I do think I should get a little geek cred as I am posting it from an EDGE connection on T-Mobile across the FroYo wireless tether. But, anyway...

When I first started working with Android, I found a simple tutorial on how to build SQLite databases. A few weeks ago, I was trying to track down the information again for project for my day job. After searching a bit, I was unable to find the original tutorial, but I found one that was a little better. The newer tutorial pointed me toward a much better way to handle databases.

In the Android SDK is a class called SQLiteOpenHelper. This class has two methods that Eclipse will force you to implement. The first is onCreate(), the second is onUpdate().

The onCreate() method is automagically called when you instantiate your descendant class, and the target database doesn't exist. In this method, you should issue all of the necessary SQLite commands to create the tables in your database. But, hold on a second. How can you put tables in the database when you didn't specify the database name? Simple, when the class is instantiated, the database name is passed in. The SQLiteOpenHelper class then takes care of creating the database for you, before the onCreate() method is called.

The onUpdate() method is also really handy and cool. When you instantiate the descendant class, you also pass in a database version number. If the version number you pass in is higher than the version number when the database was created, the onUpdate() method is called with version number stored in the database, and the version number presented when the class is instantiated. onUpdate() is responsible for issuing the correct SQLite commands needed to bring the database up to the schema version specified when the class was instantiated.

Okay, so blah, blah, blah.. Sample code!?


public class DBOpenHelper extends SQLiteOpenHelper {

private final String MY_DATA_TABLE = "t_Data";
private final String MY_DATA2_TABLE = "t_Data2";

public DBOpenHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}

@Override
public void onCreate(SQLiteDatabase myDB) {

/* Create a Table in the Database. */
myDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ MY_DATA_TABLE
+ " (mystring1 VARCHAR, mystring2 VARCHAR);");

myDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ MY_DATA2_TABLE
+ " (mystring3 VARCHAR);");
}

@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// We don't use this just yet.
}

}




Great! So the database gets created, but how do we actually use it?

Well, I am glad you asked. The SQLiteOpenHelper has methods that will return a handle to the database in either read only, or read/write flavors. So, if we wanted to use our open helper to create the database, and add a record to the second table, it would look something like this :



public void addDbData()
{
DBOpenHelper dbHelper = new DBOpenHelper(this, "my_database", null, 1);
SQLiteDatabase myDb = dbHelper.getWriteableDatabase(); // Open for write.

// Now, use the normal SQLiteDatabase methods to work with the DB.
myDb.execSQL("insert into " + MY_DATA2_TABLE + " set mystring3='Foo!';");
}


After you call addDbData(), you will now have a new database created with the name 'my_database', with schema version 1. The MY_DATA2_TABLE will also contain a single record containing the string "Foo!".

Two things worth pointing out in the addDbData() method. First, if you only want to read data from your database, you can change "getWriteableDatabase()" to "getReadableDatabase()". Second, always be sure you close your database after you are finished with it! The Java garbage collector won't do it for you, and you will get leak errors sent to your logcat console.

I am not going to get in to the update method of the SQLiteOpenHelper. I leave that as an exercise for you.

Wednesday, June 9, 2010

Something simple. Get text from a ListView.

Perhaps this topic is considered too simple for most people, which is why there aren't more postings about it. But, it seems like a useful thing to know. Specifically, when you are using a ListView with the android.R.layout.simple_list_item_1 view, how the heck do you get the text from the item clicked in the OnItemClickListener class?

It is pretty simple. The second parameter of the onItemClick is a View that contains just the item that was clicked. (Or tapped, whatever.) If you used Eclipse to automagically generate the callback method for you, the variable will be named "arg1", which is what we will assume for this example.

Inside of the onItemClick method, you can figure out the text using the following code :

String s = ((TextView)arg1.findViewById(android.R.id.text1)).getText().toString();


Pretty simple, huh? But, the code doesn't quite explain itself. So, I'll take a stab at it.

A ListView is exactly what the name says. It is a list of views. When you create the ArrayAdapter that you will use to display the data, you also tell the ArrayAdapter what view it should use. In our case, we chose "android.R.layout.simple_list_item_1" so we could use a simple array for the data. What we are doing is referencing a very simple layout that only displays a single line of text. I am sure if you Google around you can find the XML definition.

Inside the layout is a single definition. It is a TextView named "text1". Since it is a built-in layout, we will find the layout information under "android.R", instead of just "R" where our layout definitions show up.

So, by executing findViewById() on the view that was clicked, and passed in as "arg1", we can get the text that the user clicked on.

Pretty simple huh?