Blog

Android Services – Monitoring Downloads and Printing to a Zebra printer

November 24th, 2011

Recently we had a request to build an Android application that could monitor the downloads folder for lbl files and then print them on a Zebra mobile printer. The goal was to print lablel files to a Zebra RW series printer every time a new file was downloaded from the users web browser. The project allowed us to bridge a gap between web based mobile applications and a native application.

In this particular scenario, our team didn’t have any control over how the web based mobile application worked.  The only control we had was over the native application on the Android tablet. The application needed a front end to setup the printer and monitor files that were found and it needed to keep running in the background when the user navigated to other applications on the device. We accomplished this utilizing and Android service class to monitor the downloads folder and then send broadcasts from the service back to the main activity that ran our applications UI.

Here is the basic workflow:

  1. The MainActivity allows a user to start or stop a service.  The service is responsible for monitoring the /sdcard/Download folder, sending any lbl files to the Zebra printer endpoint and deleting the lbl file.  When the user selects to start the service, we fire an intent from the main activity to start the service.
  2. On creation of the service, we create a File object that references the download folder.
  3. The service then starts an AsyncTask to begin monitoring the download folder.  It’s important to note that although Android services can run while you switch between applications, that they still do their processing on the main thread of their hosting process.  For this reason, we moved the monitoring to a background thread.  Starting a background thread is trivial when using AsyncTask.  Check out the Android Docs for more information on how the service works.The PollTask monitors the file system every 3 seconds and calls ExamineFiles.  ExamineFiles is responsible for looking for lbl files, sending them to the Zebra printer and then firing off a Broadcast intent to indicate that a file has been found.  This broadcast intent can be consumed by the main activity to update the user visually that a file has been found.

Running this process as a service allowed the user to navigate back to the web browser to find files and print automatically, removing the manual steps of locating the file on the SDCard and then printing.  There are a number of scenarios where a worker might be off site and need to print remotely or on the go.  This application helped enable that for our customer.

On a side note, check out Zebra mobile printers.  We ended up utilizing a RW series.  The print and spooling time were exceptionally fast.