Android Network Tools Open Source Library

Following my work on Portdroid (Network analysis android app), I decided to release some of the code I used to write it as an open source library on github. All contributions and suggestions are welcome!

The library offers a few very simple to use interfaces which encapsulate common networking operations that are more difficult that needed on android. Below are a couple examples, see the readme for more indepth examples, and the sample app for implementations.


     // Synchronously 
     PingResult pingResult = Ping.onAddress("").setTimeOutMillis(1000).doPing();

     // Asynchronously
     Ping.onAddress("").setTimeOutMillis(1000).setTimes(5).doPing(new Ping.PingListener() {
      public void onResult(PingResult pingResult) {

Port Scanning

    // Synchronously 
    ArrayList openPorts = PortScan.onAddress("").setPort(21).doScan();

    // Asynchronously
    PortScan.onAddress("").setTimeOutMillis(1000).setPortsAll().doScan(new PortScan.PortListener() {
      public void onResult(int portNo, boolean open) {
        if (open) // Stub: found open port

      public void onFinished(ArrayList openPorts) {
    // Stub: finished scanning
Read More

Nexus 7: A hackers toolkit. Part 3 – WEP cracking and MAC Spoofing

In the previous posts we looked at how to use a modified Nexus 7 to gain access to a WPA secured network by cracking the WPA handshake or by exploiting WPS. Now it is somewhat of a rarity to see WEP networks in existence these days, however for the sake of completeness this guide will look at how we can attack these networks. We will also look at how we can bypass MAC filtering.

TL:DR – Never use WEP

Disclaimer: the author and contributors to this document will accept no responsibility for the consequences of the actions of individuals concerning wireless networks. Penetration testing networks other than your own may be illegal in your country. It is your sole responsibility to act in compliance with all relevant legislation and regulations.

Wired Equivalent Privacy (WEP) is a RC4 stream cipher, which means a key is used to seed a pseudo-random keystream which is used for encoding (similar to a one-time pad). Because the keystream is not truly random it means the same key cannot be used twice to seed. Otherwise the key can be calculated by gathering enough data.

To combat this shortfall an Initialisation Vector (IV) is transmitted from the router to the client to add to the key so that it is not a constant value. The IV makes up 24 bits of the seed with the key making up the rest (either 36 bits or 100 bits depending on if we are using 64 bit or 128 bit WEP). Unfortunately 24 bits is not enough randomness for a busy network and there is still a 50% probability of a duplicate key after 5000 packets.

Because the first few bytes of a header of a packet are known or predictable (similar to how enigma was cracked) then it is possible to work out the key once we capture enough packets. Using the IV’s we can guess each letter of the key sequentially rather than having to bruteforce the complete key (see here.

This assumes we’ve got a device setup as discussed in the previous article. Now let’s have a go at this on our demo network:

  1. Enable monitor mode on the wifi interface
  2. Identify the network we are looking to attack
  3. Start listening and capturing ivs
  4. Deauthenticate connected clients to increase capture rate

For a complete guide to running these attacks please refer to the aircrack-ng simple wep cracking guide. For simplicity I will be using the wifite python script. This script handles all of the steps described above without us needing to remember all of the commands, and if you are interested in what is doing in each step you can view the source.

Enable monitor mode on the interface


Find the network to target.


Attack the target using wifite (automatically & recommended) or via aircrack-ng


Now we have the WEP key in plaintext and can use it to connect to the network or decrypt network traffic.

For added security a router can add MAC filtering which only allows devices with set MAC addresses access even once the password is known.

However it is pretty trivial to change the MAC address of our wireless interface and access the network as an imposter. This involves listening to a network to find the MAC address of a connected client and then setting their MAC address as our own.

  1. Find client to impersonate
  2. Disable monitor mode on the wireless interface
  3. Change MAC address of the interface
  4. Profit…

First we need to find a client to impersonate. We do this by using airodump-ng to monitor (assuming monitor mode is already enabled, see above for this step).

airodump-ng -i mon0 -c 5 -b 3C:81:D8:95:6B:EC

Where mon0 is our monitoring interface, 5 is the channel to lock to (optional), 3C:81:D8:95:6B:EC is the MAC address of our target router (optional).


Here we see that a client (AC:7B:A1:5B:CF:11) is connected to our target network (3C:81:D8:95:6B:EC).

airmon-ng stop wlan1

where wlan1 is the wireless interface to stop monitoring on

We can use ifconfig to list information about all the interfaces we have available. This will show us what our current mac address is.

ifconfig -a


macchanger -m AC:7B:A1:5B:CF:11 wlan1

Where AC:7B:A1:5B:CF:11 is the MAC address we want to change to, and wlan1 is the wireless interface we wish to change the MAC address of.


Now when we run ifconfig again we will see that the MAC address has changed

ifconfig -a


And voila! Your interface is now an imposter. Trying to connect to a MAC filtered network is not an issue as you have an approved MAC address.


This handy trick can be used to bypass time restrictions that some routers use to restrict internet usage to 30 mins or so before trying to make you pay. Change the MAC address, you appear as a new user.

We have shown how trivial it is to crack WEP keys and gain unauthorised access to a wireless network and how to bypass a MAC address filter if one is in place.

Read More

Nexus 7: A hackers toolkit. Part 2 – WPS hacking

In the last post we looked at how to obtain WPA handshakes and how to crack them in order to obtain the password using a modified Nexus 7. Now we will look at a simpler way to get the password by exploiting a vulnerability found in many routers.

TL:DR – disable WPS on your home router!


Disclaimer: the author and contributors to this document will accept no responsibility for the consequences of the actions of individuals concerning wireless networks. Penetration testing networks other than your own may be illegal in your country, it is your sole responsibility to act in compliance with all relevant legislation and regulations.

Wifi Protected Setup (WPS) is used to simplify setting up wifi networks by bypassing the need to know a complicated password. There are two main types of WPS; 1. Push button – Where a button is pressed on the router and the client device 2. Pin – Using an 8 digit number to bypass needing a complex password. Both WPS types can be seen in the images below:



We will be exploiting the pin method of WPS. Once you know the correct 8 digit pin the router will spit out the password in plain text.

So you’d think that with an 8 digit pin there would be 10^8 combinations, which would take a while to brute force as most routers can typically handle 1 guess every 10 seconds. However there are a few pitfalls with the implementation.

Our first win is that the last digit of the 8 digit number is a checksum of the previous 7 numbers. So that’s only 10^7 combinations… still a lot.

The second pitfall of the implementation is that the 8 digit pin is checked in two halfs, so you will be told when the first half is correct and then if it is, it will go on to check the second half.

So this means that you have 10,000 combinations for the first half, and then just 1000 combinations for the last half. This means you can brute force the combination in less than 11,000 attempts.


This assumes we’ve got a device setup as discussed in the previous article. Now let’s have a go at this on our demo network:

  1. Enable monitor mode on the wifi interface
  2. Identify the network we are looking to attack
  3. Run a wps attack against this network (Reaver or Bully)

Monitor mode allows us to listen to the raw packets coming into the wireless interface. We can start or stop monitor mode using airmon-ng.

airmon-ng start wlan1

where wlan1 is the interface we want to start monitor mode on.


Using aerodump-ng we can see the wireless network in range and some information about them.

airodump-ng -i mon0

Where mon0 is our newly created monitoring interface. There are lots of switches for airodump -c 1 for instance would lock the channel to 1 (see help for more airodump-ng –help).


Here we can see the ‘Intohand_Demo’ network we are looking for. Now we can use this information to start guessing WPS pins.

reaver -i mon0 -b 3c:81:d8:95:6b:ec -vv

where mon0 is the monitor mode interface to our wireless device, 3c:81:d8:95:6b:ec is
the MAC address of the router we are attacking, and -vv instructs reaver to be very verbose.


This will churn through all the possibilities (starting with a few common ones then sequentially). When we get the first 4 digits of the pin incorrect we only see messages 1 to 4, when this changes to get 5 and above the first 4 digits are correct.


When the pin is guessed correctly, the router will spit out the password in plaintext. Too easy right?!

Once the pin is known, if the user changes the password we can simply run reaver again, this time already knowing the correct pin and the new password will be revealed to us.

reaver -i mon0 -b 3c:81:d8:95:6b:ec -vv -p 27319734

Where 27319734 is the WPS pin to try.

Newer routers have a WPS lock out mode when they detect brute forcing attempt, which block WPS attempts for 5 mins to 1 day (Depending on model). This makes the bruteforcing take days to weeks rather than hours. Sometimes this lockout is MAC specific so it is possible to bypass this by changing mac address of our wireless interface. It can also be possible to force the router to restart by using a DOS style attack using MDK, however I’ve not had much success using this tool.

Some routers have attempted to bypass this method of brute forcing by using invalid pins. I.E Where the checksum is invalid. This increases the keyspace from 11,000 to 100,000. This dramatically increases the time it will take to crack a WPS pin, but does not prevent it entirely.

The best defence against WPS attacks is simply to disable WPS on your router.

It can still take a long time to crack a WPS pin, but thankfully some router manufacturers have made it easier for us. TalkTalk, a UK ISP, are a super cheap broadband provider and also it seems they have a flaw in the way the WPS pins are created.

On many routers the default ESSID (network name) has a string of randomly generated characters at the end, to avoid multiple networks with the same name. But this seemingly random string is actually the last 6 characters of the MAC address of the router. And now the security flaw: The WPS pin is calculated from the last part of this MAC address.

Extract partial MAC address from ESSID
Convert to decimal & limit to 7 digits
Calculate checksum (for last digit) & append to end
And here is a python script that can do that for you!

$ python
Essid: TALKTALK-33A3C0
WPS Pin: 33842561

We have demonstrated a devastating attack on WPS enabled networks which reveals the plaintext password in a relatively short amount of time, all using the Nexus 7. Hopefully this has convinced you to disable WPS on your home and work WiFi routers.

Read More

Nexus 7: A hackers toolkit. Part 1 – Setup and hacking WPA networks


This is the first of a series of posts where we will take an old Nexus 7 (2012 wifi) and convert it into a compact penetration testing toolkit. In this first article we’ll setup and install the Nexus 7 tablet and complete our first penetration test on a secure WPA network. It should make a good showcase for the flexibility and extensibility of the Android operating system.

This will be done by installing custom linux chroot onto our device and taking advantage of the freely available penetration testing tools that are available. We will then perform some basic penetration testing against our demo wireless networks in order to demonstrate the importance of understanding network security.

Disclaimer: the author and contributors to this document will accept no responsibility for the consequences of the actions of individuals concerning wireless networks. Penetration testing networks other than your own may be illegal in your country, it is your sole responsibility to act in compliance with all relevant legislation and regulations.

There is a choice of two popular distributions, both are built on the Kali Linux distribution – each with their own advantages and disadvantages, but with identical core functionality.

Kali Linux NetHunter

  • Supports newer version of android (4.4.4)
  • Offers an additional toolkit with a simple graphical interface that can carry out sophisticated attacks (HID Attack, BadUSB)


Pwnie Express Community Edition

  • Easier shortcuts to commonly used command line tools



  • Unlocking the bootloader will wipe all your data. So ensure your data is backed up before you start!
  • Although this process is reversible it can void your warranty

First you will need a compatible device. This will depend on which distro you decide to go with.

For Pwnie Express ( )

  • Nexus 7
  • Nexus 5

For Kali Linux NetHunter (

  • Nexus 10
  • Nexus 7
  • Nexus 5
  • OnePlus One


USB OTG Y-cable – You can use just a standard OTG cable however using a Y-cable allows us to charge the device at the same time as using a usb peripheral. Note that while the device will charge and the battery percent will increase the charging indicator may not show.

USB ethernet adapter – This allows us to connect the android device to a network via ethernet. I have had mixed success in using this as sometimes the device doesn’t seem to want to register on the network.

USB wifi adapter – It is important to select a wifi adapter that supports monitor mode. The TP­Link TL­WN722N is recommended.

Using a small amount of velcro tape we can attach the wifi and ethernet adapter to the back of the device which makes it easier to move around without accidentally unplugging them.


To install NetHunter or Pwnie Express you must first unlock the bootloader and root the device. This is explained in the respective guides, but is very similar to flashing custom roms (such as cyanogen) onto a device.


  1. Download the correct image for your device
  2. Follow this guide to install

Pwnie Express

  1. Ensure your device is running android 4.2.2, otherwise this will not work! Please downgrade to this version before continuing. You can find the factory images for Nexus devices here
  2. Download the correct image for your device and follow the installation guide here

Now we have our device set up it’s time to get to the good stuff! Below is a condensed list of some of the tools available to us:

  1. Aircrack-ng – a collection of wifi hacking tools
  2. airodump-ng – Sniffing tool
  3. aircrack-ng – Cracking tool (WEP/WPA2)
  4. airmon-ng – enabled/disables monitor mode of wireless devices connected
  5. besside-ng – useful script for capturing WPA handshakes however I’ve not had success getting it working on my Nexus 7.
    many more tools in this package, see for details.
  6. Dsniff – Script that watches an interface and scans for passwords and other sensitive strings
  7. EvilAP – Script that creates an access point and allows clients to connect to it in order to perform man-in-the-middle attacks between the client.
  8. Kismet – Sniffing tool similar to airodump
  9. MAC Changer – changes the mac address of interfaces
  10. Nmap – Powerful port scanner and OS-fingerprinting tool
  11. Tshark – command line version of wireshark for packet capture and analysis
  12. Strings Watch – Script that watches an interface and scans for strings
  13. Wifite – Python script that automates wireless attacks
  14. Ubertooth – bluetooth sniffing tool

Note that as we are running kali linux distro we can download more packages via the package manager (apt), but I have had mixed success with this.

Often we assume that our private wifi networks are secure just because they use a password and as a result sensitive information may be readily available to anyone able to connect/listen to the network. Let’s have a quick look at the wifi tools we can use to defeat basic wireless security.

There are two common types of security employed on wireless networks: Wired Equivalent Privacy (WEP) and Wi-Fi Protected Access (WPA). WEP has several flaws in it’s implementation and was not intended to be robust to attack, fortunately this has meant that it’s popularity has decreased significantly in recent years and now it is somewhat of a rarity to see WEP networks.

WPA is much more secure and only really vulnerable to dictionary attacks. These dictionary attacks can be performed offline by capturing the 4 way handshake as a client connects to the router.

To capture a handshake we need to do the following

  1. Put the wireless interface into monitor mode (so it can sniff networks)
  2. Select a network to attack
  3. Sniff the network until a handshake is sent (sent each time a client connects)
  4. Optional: Deauthenticate clients so they must reconnect (and thus send another handshake). This massively speeds up the capture.

Thankfully the wifite script will perform all of these steps for us, which is great considering typing on the Nexus 7 can be time consuming.




Now we have the handshake but brute forcing a password is somewhat beyond the power of our little Nexus 7’s hardware (although we could use a small dictionary). However there exist dedicated and distributed hardware / services that can do this for you we just need to upload the handshake to a website. We look at a couple below: This is a distributed network of volunteers running a cracking service for free in the interest of promoting better security. You upload the handshake files and it will be tested against several dictionaries. The statistics page shows that about 15.5% of submitted networks are successfully cracked. – This is a cracking service that charges bitcoins for attempting to crack a handshake. If you know the keyspace used by the key (say a default router password) then this can be very cost effective. For example Sky Routers use an 8 uppercase letters (A-Z), this costs 0.25BTC (current valued at about £40). However if the password has changed from the default then the cracking will be unsuccessful, however many users don’t change their password from the default. Helpfully they show the success rate of each dictionary in the FAQ section on the site. – Another cracking site that accepts credit card payments and offers numerous dictionaries.

By uploading this handshake file to the password to our network is cracked in minutes. Turns out the password to our wifi network was ‘password1’…


We’ve dusted off a rather old device going unused and turned it into a very powerful security auditing tool and demonstrated how to capture a WPA handshake in order to brute force the password. Pretty neat.
In the next post we’ll look at exploiting Wifi Protected Setup (WPS) as a quicker and potentially cheaper method of gaining access to WPA protected networks.

Read More

Nexus Dreams (Added daydream support in Nexus Live Wallpaper)

To celebrate getting over 3 million downloads, I pushed another update to my livewallpaper. This update adds supports for “dreams”. A dream in android is similar to a screensaver that is optionally display while a device is either charging, docked or both. It looks like the image below:

Nexus Dreams

Nexus Dreams

To turn on dreams on your device go to settings, display, daydreams.

Nexus Dreams

Nexus Dreams

You can download Nexus Revamped from the Google play store below:

Free Version

Android app on Google Play

Pro Version

Android app on Google Play

Read More

I’ll be attending droidcon again this year ^_^

Droidcon was awesome last year, so naturally I will be attending again this year. It was a great oppertunity to “network” and meet lots of like minded android developers, it also gave me the chance to meet lots of interesting companies (start-up software companies, app/game studios, phone providers, hardware specialists) which I may be even more interested in this year as I will be looking for employment soon.

Along with all of this come the additional benefits of: pizza, beer, competitions (there were an insane amount of competitions last year), freebies, and more free beer!

For those of you unfamiliar with droidcon here is an excerpt from their website:

Droidcon London 2011 is Europe’s largest conference that exclusively covers Android development and applications. The conference will take place in London on 6th-7th October 2011.

Droidcon London 2011 has grown tremendously since last year, in line with the exponential interest in the Android platform. This year, upward of 600 Android enthusiasts will rub shoulders with the premier experts in the field to dig into every aspect of Android and its ever-growing ecosystem. High on the agenda this time around are Android for the Tablet, Android in the Enterprise, Android for Games, Android for business, Augmented Reality, multi-mobile and a whole lot more.

The first day will be community led with a full-day Barcamp and Democamp. The second day will be conference day, with presentations from some of the world’s foremost Android experts, including two Google Developer Advocates Richard Hyndman and Nick Butcher, Mark Murphy (CommonsWare), Al Sutton, and Kieran Gutteridge (I’ve not had the pleasure of meeting the other speakers yet). A full list of presenters is available here.

You can register via the Droidcon London 2011 site: (

Follow Droidcon London 2011 on Twitter: @DroidconUK tags: #droidconUK #droidcon

Follow Droidcon London 2011 on Facebook:

Read More

Nexus Revamped updates (1.98.14)

Wallpaper has now past 600,000 downloads ^_^ and thought I should blog about the recent changes.

I made a promo image for the wallpapers that should be visible on the market place any time now. I have limited art skills so this is the best I could come up with:

Nexus Revamped promo image

Nexus Revamped promo image

Jazz-hands (multi-touch)

I managed to fix a bug with multi-touch in my code, thanks to this question on stackoverflow. This now means that my wallpaper will work with up to 10 fingers or “jazz-hands”. This also fixes some of the crashes that were occurring on devices with 3.1 and up.

Save / load themes

I’ve also added the option for users to save their own themes so that if you have a few you like you don’t have to keep changing all the settings back and forth. This is also a step towards the next update I have planned whereby users can upload/download themes with a rating system and all the junk.

Save custom themes

Save custom themes

Better tablet / honeycomb support
I’ve added several improvements for large screen devices / tablets, the whole wallpaper is scaled effectively so that it no longer is just a giant zoomed in version of the phone wallpaper, and multiple more graphical changes to improve usability.

Nexus Revamped on a xoom

Nexus Revamped on a xoom

Android Market Links
Either click the following android market links (in android phone) or search the market for nexus revamped.
Pro Version
Nexus Revamped Pro Live Wallpaper (com.stealthcopter.nexusrevampedpro)


Free Version

The free version is the same as the pro version but with some of the fancier features are missing, and some non-intrusive adverts. Both versions are fully supported.

Nexus Revamped Live Wallpaper (com.stealthcopter.nexusrevamped)


Full changelog (since last blog post at version 1.98.01)


  • Bug Fix: Multi-touch force close bug fixed
  • Improved: Due to above bug fix, multi-touch now supports more fingers. This is great for tablets with ‘jazz hands’ support (more than 5 fingers!)
  • Added: Ability to save custom themes (Preset > User)
  • Added: Red Grid theme
  • Improved: Thumbnail images in preset menu scaled to screensize


  • Added: New & exciting Color changer dialog!
  • Added: Loads of new textures, try adding a background tint to make these more personal!
  • Added: German translation (thanks Steven!)
  • Added: Danish translation (thanks Johan!)
  • Added: Russian translation (thanks Dmitry!)
  • Added: Licence information
  • Improved: Transparent theme consistent throughout all settings now
  • Improved: Wallpaper changes scale based on screensize to better suit tablets etc.
  • Improved: Honeycomb background was a bit shoddy, fixed!
  • Improved: Icons/gfx more suitable for range of screensizes
  • Improved: Background tints are applied once on bitmaps rather than every frame, saving cpu time 🙂
  • Removed: Some unused functions and boring code
  • Bug Fix: Appearance bug in changelog fixed (doh!)


  • Added: Spanish translation (thanks Hector!)
  • Added: Swedish translation (thanks Joar!)
  • Added: Preset option for quick setting of common themes
  • Help me: if you want to add translations please email me!
  • Added: Added a cool carbon fibre background option!
  • Added: Differentiation between market places
  • Bug Fix: When configuring livewallpaper via launcher pro or similar some settings were not automatically updated
  • Bug Fix: Email in the about section will actually fill in my email address, surprise nobody spotted this sooner! Also added some information into each email to help me with issues.


  • Bug Fix: Minor bug in revert to default settings
  • Bug Fix: Minor bug in open application from market or settings


  • Added: Power saver in the reactions menu, can make the wallpaper static when battery reaches a certain percentage.
  • Added: Norwegian translation added (thanks Dan!)
  • Added: Obfuscation for improved efficiency and to help decrease piracy
  • Bug Fix: Glow size was forgotten on screen power off


  • Added: Particle scaling, like the Nexus S live wallpaper
  • Improved: Got sexy transparent menus working again, enjoy!
  • Improved: Dialogs look better on small screens and with different orientations; some screens are now scrollable in the next version this will be replaced with a better solution 🙂
  • Moved: Disable analytics is now in advanced menu
  • Bug Fix: Fixed a FC bug
  • Bug Fix: Using a custom background then renaming the file will no longer cause a FC


  • Added: Option to display FPS on screen (Advanced > FPS)
  • Added: Rotation on battery level
  • Bug fix: Memory leak from using custom backgrounds fixed (hopefully)
  • Bug fix: When Multi-touch option was disabled normal touch would not function
  • Improved: Code backend made more efficient by combining some classes
  • Added: Cool new background called “The Grid”
Read More

Alarm Clock Plugin for Sony Ericsson LiveView uploaded to market

Following my previous two posts about Sony Ericssons LiveView (Quick Review and SDK & development) I have released my Alarm Clock Plugin for Sony Ericsson LiveView!

Find it on the android market:

Would love some feedback from anyone with a LiveView, there must be someone else out there who has one right?

Sony Ericsson LiveView Alarm Clock Plugin

Sony Ericsson LiveView Alarm Clock Plugin

Read More

Sony Ericsson LiveView SDK and my Alarm Clock Plugin

So as I mentioned in a previous post I recently got a Sony Ericson LiveView watch, I decided to download the SDK and have a go at writing a plugin for use with the watch. The SDK is easy to use (developer world) and the examples and documentation (available here) is very clear and easy to understand. Unfortunately there is no emulator so you will have to go to the trouble of owning one of these devices if you want to test your app on it.

There are two types of plugins.
1. Announce plug-in

Announce plug-ins can send announcements to the LiveView™ device. This is done in
the same way as the predefined announce features, like Facebook and Twitter.

Gmail Plugin Emails

Gmail Plugin Emails

The SDK Announce plugin (helloWorldPlugin) example is very simple and and mostly contains code scheduling a timer to send events to the phone along. This is a single class which is supported by a small number of helper classes and the plugin only contains a few things foreign to a typical android application:

Just extend the class provided by the SDK for plugins:

public class HelloWorldService extends AbstractPluginService {

Send updates to the phone using the following function:

mLiveViewAdapter.sendAnnounce(mPluginId, mMenuIcon, header, body, System.currentTimeMillis(), "");

mPluginId – identifies which app send the update
mMenuIcon – the icon the update will appear with
header – the title (IE: email subject)
body – the main text (IE: email text)
timestamp – timestamp of the announcement
link – action to perform when user clicks at end of message (event to occur on phone). This is interpreted by overriding the function below:

	protected void openInPhone(String openInPhoneAction) {
		Log.d(PluginConstants.LOG_TAG, "openInPhone: " + openInPhoneAction);
		// Open in browser.
		final Uri uri = Uri.parse(openInPhoneAction);
		final Intent browserIntent = new Intent();
		browserIntent.setClassName("", "");

2. Sandbox

The sandbox plug-in can take complete control of the LiveView™ device by sending
images to it and control its ability to vibrate and display different colors on the LED. All
user activities are propagated to the plug-in, so that it can take appropriate actions.

Contact Call Plugin

Contact Call Plugin

We extend the same class however this time we say yes when we are asked if we are a sandbox plugin:

	protected boolean isSandboxPlugin() {
        return true;

So now rather than using sendAnnounce to send text to the liveview we directly send images. Below is a function used that draws some text to a bitmap and then sends it to be displayed.

    public static void sendTextBitmap(LiveViewAdapter liveView, int pluginId, String text, int bitmapSizeX, int fontSize) {
        // Empty bitmap and link the canvas to it
        Bitmap bitmap = null;
        try {
            bitmap = Bitmap.createBitmap(bitmapSizeX, fontSize, Bitmap.Config.RGB_565);
        catch(IllegalArgumentException  e) {
        Canvas canvas = new Canvas(bitmap);

        // Set the text properties in the canvas
        TextPaint textPaint = new TextPaint();

        // Create the text layout and draw it to the canvas
        Layout textLayout = new StaticLayout(text, textPaint, bitmapSizeX, Layout.Alignment.ALIGN_CENTER, 1, 1, false);
            liveView.sendImageAsBitmap(pluginId, centerX(bitmap), centerY(bitmap), bitmap);
        } catch(Exception e) {
            Log.d(PluginConstants.LOG_TAG, "Failed to send bitmap", e);

So we can create a similar function drawing whatever we want to a bitmap and then passing it onto the screen.

Only one thing left (I think). Intercepting button presses:

	protected void button(String buttonType, boolean doublepress, boolean longpress) {

Where the the following buttons are defined:

  • PluginConstants.BUTTON_UP
  • PluginConstants.BUTTON_DOWN
  • PluginConstants.BUTTON_LEFT
  • PluginConstants.BUTTON_RIGHT
  • PluginConstants.BUTTON_SELECT

and we can see if the were tapped or held down with the boolean longpress. Note that we cannot detect longpresses of select as that will exit your plugin and the power button at all as that controls the screen.

My Attempt at a plugin: Alarm Clock
So I thought given that this thing is pretty much a watch, it would be useful to be able to set an alarm with it.

Plugin Icon

Plugin Icon

12hr clock (select sets alarm)

12hr clock (select sets alarm)

24hr clock

24hr clock

Unfortunately I don’t think it is possible to set the alarm programatically in android in versions prior to gingerbread (posted a stackoverflow question about it). So the user base is very limited, only users with gingerbread and higher with a LiveView will be able to use it so I don’t expect a massive response. Also I have no idea if this will work with non-stock alarm clock apps as I’m not aware of any manufacturers modification of gingerbread as of yet.

The LiveView application on the phone handles links to all the shared preferences for the plugins (they’re mandatory just for the enable/disable option) but an example is included in all the examples and it is very simple to just add more options to the preferences.xml and grab them in the code.

LiveView plugin settings

LiveView plugin settings

Alarm set via plugin

Alarm set via plugin

If you want more info please read the documentation linked at the start of this post. I will probably release the liveview alarm clock plugin onto the market soon, but I don’t expect the reception to be that good as it will only work on a few phones / tablets. Anyway I had fun programming for mine, enjoy!

Read More