Instantiating a custom view in Android

Creating a custom view/control in Android is fairly simple – here are the steps I used:

  1. Create a new class which extends from the ‘View’ abstract base class. E.g.
    public class MyCustomControl extends View
  2. Provide constructor overloads for ALL of the following prototypes, where initView() is a method in which you perform initialization of things such as Paint objects:
    public MyCustomControl(Context context)
    	{
    		super(context);
    		initView();
    	}
    	
    	public MyCustomControl(Context context, AttributeSet attrs)
    	{
    		super(context, attrs);
    		initView();
    	}
    
    	public MyCustomControl(Context context, AttributeSet attrs, int defStyle)
    	{
    		super(context, attrs, defStyle);
    		initView();
    	}
    
  3. Override onMeasure() in order to scale your control to the parent drawing area, such as shown in this good example.
  4. Do your canvas drawing operations in onDraw on the supplied Canvas object.
  5. Instantiate your custom view in a layout xml file (e.g. main.xml), for example:
    <?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"
        >
    	<com.android.samples.MyCustomControl
    		android:id="@+id/myCustomControl"
        	android:layout_width="fill_parent" 
        	android:layout_height="fill_parent" 
        />
    </LinearLayout>

I found that if I didn’t add the 2nd and 3rd constructors, I got an exception when calling setContentView(R.layout.main) from onCreate() of the main Activity. You can instead construct an instance of the view manually in onCreate() of the main Activity, and then call setContentView(yourCustomViewInstance) if you don’t want to use XML layout.

Fastest way to delete a directory tree in Windows

Our nightly build was taking > 30 minutes to delete our source tree before getting latest (Windows is not quick to delete a large number of small files), which was comparable to the time taken to actually compile the source. There are stackoverflow and superuser articles that discuss the fastest way to do deletes, however there’s no magic solution. If you find you are regularly needing to delete large amounts of files (e.g. as part of the nightly build process), your best option is to create a new partition on your HDD (or install a new HDD) and store all the files you will be deleting on there. Then you can erase them all in about 2 seconds by doing a quick format of the drive! The only trick is how to programatically format a drive, since there is no (documented) API for this in Windows. There’s Win32_Volume.Format (WMI) but it’s only available in server OSs, and then there’s SHFormatDrive, which shows a dialog.

However, provided your partition (in this case Z:) has no label, you can do this:

echo Y | format Z: /FS:NTFS /X /Q
An inferior alternative to this is to use a VBScript that uses SendKeys like this:

set WshShell = CreateObject("WScript.Shell")
wshShell.run "c:windowssystem32format.com Z: /FS:NTFS /V:QuickWipeDrive /X /Q"
wscript.sleep 1000
wshshell.sendkeys "QuickWipeDrive" & "{ENTER}"
wscript.sleep 1000
wshshell.sendkeys "Y" & "{ENTER}"
wscript.sleep 5000

The downside of this script is that it will only work when the computer is not locked since SendKeys requires a console session that is logged in an active.

Bluetooth Service Connector

Bluetooth is still a relatively new technology when it comes to Windows. Although Windows 7 now has a reasonably decent bluetooth stack baked-in, it’s certainly not bug-free. It is not straightforward to control connection of bluetooth services, such as AudioSink, HeadSet, RemoteControl etc. And depending on how ‘dumb’ your bluetooth device is, your only option to get it connected to Windows in some cases (e.g. your device was last connected to a different host, such as your phone) is to completely uninstall and re-discover the device, as discussed on this thread. Weeeak.

I’ve written a small utility that may help with issue (it works for me, but I’ve only tested on my own bluetooth headphones – Sony DR-BT50). It works in conjunction with another utility I recently posted (that allows a program to set the default audio device), and provides control over connecting / disconnecting the available bluetooth services for all your paired bluetooth devices in Windows. It also provides a shortcut specifically for bluetooth audio devices which automates the process of getting a frustratingly silent pair of headphones / speaker to spring into life with a single click.

Download the utility here. I hope it works for you!

Setting default audio device in Windows

Since the audio revamp in Windows Vista, many things that were possible to do in code in the past (i.e. XP) are now difficult or impossible. One of those tasks that was easy in XP was setting the default audio device for playback. In XP this just required a registry change, but in Vista & Windows 7, Microsoft decided that developers should not have access to change the default audio device, so they locked down the registry and provided no documented API to achieve this. Their reasoning was that if two programs both wanted to set the default audio device, they would end up fighting each other for it, which of course is bad. But I believe this is a very short-sighted decision, since there are plenty of legitimate cases where a program needs to do this. These are discussed on this amazingly long-living thread (started in 2006 and still going).

The end result is that, no thanks to Microsoft, we finally have a way to do this, and I’ve created a console application in case others would like to control this as well:

Usage: SetDefaultAudioDevice.exe [deviceID] [role]
Where:
[deviceID] is a GUID including braces
[role] is either ‘console’, ‘multimedia’ or ‘communications’.

Example: SetDefaultAudioDevice {24dfc80a-680f-4748-8627-c340cb14f187} multimedia

Your audio device IDs can be found in the registry under HKLMSOFTWAREMicrosoftWindowsCurrentVersionMMDevicesAudioRender.

Feel free to download this utility here, source code is in my SVN repo.

Thank-you to EreTIk and Jonny Best and everyone else on the above forum post!

Upgrading your Android SD card

Short version:

To move data between SD cards in your Android phone, just copy it to a computer (with the phone plugged in – via enabling USB mass storage mode from the phone), power down the phone, insert new SD card, boot up, and copy data from computer back to new SD card in the phone. Easy.

Detailed version:

My Android (LG Optimus One) came with a 2Gb micro SD card, which did the job for about 6 months. Now I use my phone for listening to music in the car and elsewhere, and the apps I installed started to consume space as well, so I needed upgrade the SD card to something bigger. The biggest the most phones support right now is 32Gb, so I bought a Lexar 32 Gb micro SD card (class 10) for $AU100 (retail). I was a little concerned about the exact procedure to move the data from the 2Gb to the 32Gb card, but it turns out it was really simple (assuming you have not partitioned your SD card):

1. Connect phone to PC via USB (with old SD card install still inserted), and copy everything off the SD card into a folder on your HDD. I got a few errors trying to copy some ThinkFree Office files, probably due to the path length being too long, so I just skipped those files (they didn’t look too important anyway).

2. Power off phone, insert new SD card, boot up phone.

3. Connect phone to PC via USB, copy everything from the folder in step 1 to phone’s SD card, and disconnect USB.

That’s it.

Unknown Build Error RG1000

After manually merging a set of source changes to a .csproj file, my project would no longer build, giving this error:

Common.targets(588,5): error RG1000: Unknown build error, ‘An item with the same key has already been added.’

Not particularly helpful, especially if there are a large number of changes in the .csproj file. To get more information in such a case, in VS2010 you can go to Tools->Options->Projects and Solutions->Build and Run and set the MSBuild output verbosity to ‘Diagnostic’. After attempting to build again, the error now becomes much more useful:

Error 2 The item “ViewsFeedbackView.xaml.cs” was specified more than once in the “Sources” parameter. Duplicate items are not supported by the “Sources” parameter. C:WindowsMicrosoft.NETFrameworkv4.0.30319Microsoft.CSharp.targets 160 9 MyCompany.MyProduct.WebClient

Interestingly, after I reset the verbosity level back to Minimal (without making any code changes), the more detailed error still appeared. Weird.

Integrating Agent Ransack with FreeCommander

FreeCommander is my Windows Explorer replacement of choice, however it’s search feature is pretty basic. It pails in comparison to the free Agent Ransack which is fast, simple, and most importantly, lets you view snippets of the file contents in which a search term was found without having to open the file itself. Luckily, it is easy to replace FreeCommander’s built-in search feature with Agent Ransack instead:

  1. Install Agent Ransack.
  2. In FreeCommander, go to Extras->Favorite Tools->Edit
  3. Click the blue drop-down triangle next to the ‘Program’ field and seek to ‘C:Program Files (x86)MythicsoftAgent RansackAgentRansack.exe’
  4. Set the ‘Parameter’ field to ‘-d “%ActivDir%”‘ (without the single quotes, but including the double quotes around %ActiveDir% to ensure it works when there are spaces in the current directory path).
  5. Optionally set the icon by selecting AgentRansack.exe from the installation location.
  6. Select ‘Maximized’.
  7. Most importantly, set the HotKey to something and choose ‘global hotkey’.

Now you can press the defined hotkey (I use Ctrl+0) to launch Agent Ransack in the active folder, ready to search.

Error when opening Word documents

OS: Windows 7 64-bit
Office: 2010 Premium

When double-clicking a .doc/x file in Windows Explorer, or launching it via a different explorer, such as FreeCommander, you may see this error message:

Many, many people have seen this issue. I tried several solution, including deleting the word Data key, as recommended by Microsoft, checking that ‘Run this program as an administrator’ is not checked and renaming normal.dotm, but all failed to fix the error. Finally, here’s what fixed it for me:

  1. Right-click a .doc/x file -> Open With -> Choose program
  2. Select Word 2007 and hit OK.

After doing that, I could open word documents from outside word successfully.

Interop.ComAdmin exception when using IIS on a 64-bit OS

If you install IIS on a 64-bit operating system, you may get the following error when navigating to your website locally:

Could not load file or assembly ‘Interop.COMAdmin’ or one of its dependencies. An attempt was made to load a program with an incorrect format.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.BadImageFormatException: Could not load file or assembly ‘Interop.COMAdmin’ or one of its dependencies. An attempt was made to load a program with an incorrect format.

The clue here is the BadImageFormatException, which hints that this is a 32/64 bit issue. To fix it, in IIS Services Manager, go to Application Pools, select the application pool under which your website/application is running, and choose ‘Advanced Settings’. Change ‘Enable 32-bit Applications’ from False (the default) to True. Recycle your app pool, and reload your browser page, no more error!

Pairing SPP bluetooth devices with Android phones

Update: I have turned the below class into an app which I’ve made available in the Google Play Store called Bluetooth Class Zero. It is a simple application which just enables pairing with bluetooth class zero devices without having to root & patch your phone.

————————————–

I bought a Bluetooth Bee from Seeed Studios, which is an SPP (Serial Port Profile) bluetooth device, with the intention of writing an app for Android that communicates with a remote data logger. Unfortunately, it turns out that there’s a bug in the BroadComm bluetooth stack that is used by most Android phone manufacturers (LG, HTC, Samsung are affected, but not the Google Nexus phones) that prevents discovery to this and all other bluetooth devices that report their Class of Device (CoD) code as 0x00. This is the case for many SPP bluetooth devices, and SPP is probably the most common bluetooth profile (at least it’s the most basic – just straight serial comms) so this bug is pretty nasty.

Basically, if you perform a scan for devices, your SPP device will not show up, and in the logs you will see:

ERROR/DTUN_HCID4(663): Device [00:18:E4:0C:6E:CA] class is 0x00 – skip it.

The code for the Broadcom bluetooth stack is open source, so the bug is plain for all to see here. The bug has been reported on StackOverflow and elsewhere.

Until Broadcom and/or all users of their bluetooth stack fix this issue (by simply removing the IF block that skips devices whose CoD is 0x00), the only way to connect to your SPP device from Android is to read the log files, looking for the above error, extract the device address, and manually initiate a connection in code. After this, your SPP device will appear along with all your other bluetooth devices in the bluetooth settings page on your phone, and you can successfully communicate using the bluetooth API provided by Google.

I have written a re-usable class that implements this workaround, which you can download from here.

How to use (from your Activity class):

(new BluetoothClassZeroDiscoveryTask(
    this, 
    new BluetoothDiscoveryCallback())).execute();

Where BluetoothDiscoveryCallback is a class defined e.g. in your Activity. The call method will be called after the discovery task completes, and is passed the complete list of paired bluetooth devices, including those that are undiscoverable due to the above bug.

private class BluetoothDiscoveryCallback
    implements Action<ArrayList<BluetoothDevice>>
{
	public void call(ArrayList<BluetoothDevice> devices)
	{
		// Now you have the list of ALL available devices, 
		// including those that report class 0x00.
	}
}

// Java equivalent of the built-in Action from C#.
public interface Action<T>
{
	void call(T target);
}

You’ll also need to add READ_LOGS permission to your manifest file:

<uses-permission android:name="android.permission.READ_LOGS" />

Feel free to suggest improvements to the code, I’m new to Android and haven’t done Java in ages 🙂

P.S. Hassle your phone manufacturer to fix this bug so this workaround is not needed!

App Screenshots:

After pressing “Start Discovery”, if any bluetooth class zero devices were found (but ignored), you will get the standard pairing dialog:

After entering the correct PIN code, your device will be listed alongside others in your bluetooth settings:

The app requires Android 2.1+. It’s been tested on the following phones:

Manufacturer Model Android Version Affected Results
LG Optimus One 2.2 Yes Works
HTC Desire HD 2.2 Yes Works, but unfortunately may interfere with networking / bluetooth operation.
Samsung Galaxy S (I9000) 2.2 Yes Fails
Samsung Galaxy Player 50 2.1 Yes Works

The app is free to use, if you find it useful, feel free to make small donation 🙂