Development and remote installation of Java service for the Android Devices
Development and remote installation of Java service for the Android Devices
Written by:
Igor Darkov, Software Developer of Device Team, Apriorit Inc.
In this article Iâve described:
How to develop simple Java service for the Android Devices; How to communicate with a service from the other processes and a remote PC; How to install and start the service remotely from the PC. 1. Java Service Development for the Android Devices
Services are long running background processes provided by Android. They could be used for background tasks execution. Tasks can be different: background calculations, backup procedures, internet communications, etc. Services can be started on the system requests and they can communicate with other processes using the Android IPC channels technology. The Android system can control the service lifecycle depending on the client requests, memory and CPU usage. Note that the service has lower priority than any process which is visible for the user.
Letâs develop the simple example service. It will show scheduled and requested notifications to user. Service should be managed using the service request, communicated from the simple Android Activity and from the PC.
First we need to install and prepare environment:
Download and install latest Android SDK from the official web site (http://developer.android.com); Download and install Eclipse IDE (http://www.eclipse.org/downloads/); Also weâll need to install Android Development Tools (ADT) plug-in for Eclipse.
After the environment is prepared we can create Eclipse Android project. It will include sources, resources, generated files and the Android manifest.
1.1 Service class development
First of all we need to implement service class. It should be inherited from the android.app.Service (http://developer.android.com/reference/android/app/Service.html) base class. Each service class must have the corresponding <service> declaration in its package’s manifest. Manifest declaration will be described later. Services, like the other application objects, run in the main thread of their hosting process. If you need to do some intensive work, you should do it in another thread.
In the service class we should implement abstract method onBind. Also we override some other methods:
onCreate(). It is called by the system when the service is created at the first time. Usually this method is used to initialize service resources. In our case the binder, task and timer objects are created. Also notification is send to the user and to the system log: public void onCreate() { super.onCreate(); Log.d(LOG_TAG, “Creating service”); showNotification(“Creating NotifyService”); binder = new NotifyServiceBinder(handler, notificator); task = new NotifyTask(handler, notificator); timer = new Timer(); } onStart(Intent intent, int startId). It is called by the system every time a client explicitly starts the service by calling startService(Intent), providing the arguments it requires and the unique integer token representing the start request. We can launch background threads, schedule tasks and perform other startup operations. public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Log.d(LOG_TAG, “Starting service”); showNotification(“Starting NotifyService”); timer.scheduleAtFixedRate(task, Calendar.getInstance().getTime(), 30000); } onDestroy(). It is called by the system to notify a Service that it is no longer used and is being removed. Here we should perform all operations before service is stopped. In our case we will stop all scheduled timer tasks. public void onDestroy() { super.onDestroy(); Log.d(LOG_TAG, “Stopping service”); showNotification(“Stopping NotifyService”); timer.cancel(); } onBind(Intent intent). It will return the communication channel to the service. IBinder is the special base interface for a remotable object, the core part of a lightweight remote procedure call mechanism. This mechanism is designed for the high performance of in-process and cross-process calls. This interface describes the abstract protocol for interacting with a remotable object. The IBinder implementation will be described below. public IBinder onBind(Intent intent) { Log.d(LOG_TAG, “Binding service”); return binder; }
To send system log output we can use static methods of the android.util.Log class (http://developer.android.com/reference/android/util/Log.html). To browse system logs on PC you can use ADB utility command: adb logcat.
The notification feature is implemented in our service as the special runnable object. It could be used from the other threads and processes. The service class has method showNotification, which can display message to user using the Toast.makeText call. The runnable object also uses it:
public class NotificationRunnable implements Runnable { private String message = null; public void run() { if (null != message) { showNotification(message); } } public void setMessage(String message) { this.message = message; } }
Code will be executed in the service thread. To execute runnable method we can use the special object android.os.Handler. There are two main uses for the Handler: to schedule messages and runnables to be executed as some point in the future; and to place an action to be performed on a different thread than your own. Each Handler instance is associated with a single thread and that thread’s message queue. To show notification we should set message and call post() method of the Handlerâs object.
1.2 IPC Service
Each application runs in its own process. Sometimes you need to pass objects between processes and call some service methods. These operations can be performed using IPC. On the Android platform, one process can not normally access the memory of another process. So they have to decompose their objects into primitives that can be understood by the operating system , and “marshall” the object across that boundary for developer.
The AIDL IPC mechanism is used in Android devices. It is interface-based, similar to COM or Corba, but is lighter . It uses a proxy class to pass values between the client and the implementation.
AIDL (Android Interface Definition Language) is an IDL language used to generate code that enables two processes on an Android-powered device to communicate using IPC. If you have the code in one process (for example, in Activity) that needs to call methods of the object in another process (for example, Service), you can use AIDL to generate code to marshall the parameters.
Service interface example showed below supports only one sendNotification call:
interface INotifyService { void sendNotification(String message); }
The IBinder interface for a remotable object is used by clients to perform IPC. Client can communicate with the service by calling Contextâs bindService(). The IBinder implementation could be retrieved from the onBind method. The INotifyService interface implementation is based on the android.os.Binder class (http://developer.android.com/reference/android/os/Binder.html):
public class NotifyServiceBinder extends Binder implements INotifyService { private Handler handler = null; private NotificationRunnable notificator = null; public NotifyServiceBinder(Handler handler, NotificationRunnable notificator) { this.handler = handler; this.notificator = notificator; } public void sendNotification(String message) { if (null != notificator) { notificator.setMessage(message); handler.post(notificator); } } public IBinder asBinder() { return this; } }
As it was described above, the notifications could be send using the Handler objectâs post() method call. The NotificaionRunnable object is passed as the methodâs parameter.
On the client side we can request IBinder object and work with it as with the INotifyService interface. To connect to the service the android.content.ServiceConnection interface implementation can be used. Two methods should be defined: onServiceConnected, onServiceDisconnected:
ServiceConnection conn = null; ⦠conn = new ServiceConnection() { public void onServiceConnected(ComponentName name, IBinder service) { Log.d(“NotifyTest”, “onServiceConnected”); INotifyService s = (INotifyService) service; try { s.sendNotification(“Hello”); } catch (RemoteException ex) { Log.d(“NotifyTest”, “Cannot send notification”, ex); } } public void onServiceDisconnected(ComponentName name) { } };
The bindService method can be called from the client Activity context to connect to the service:
Context.bindService(new Intent(this, NotifyService.class), conn, Context.BIND_AUTO_CREATE);
The unbindService method can be called from the client Activity context to disconnect from the service:
Context.unbindService(conn); 1.3 Remote service control
Broadcasts are the way applications and system components can communicate. Also we can use broadcasts to control service from the PC. The messages are sent as Intents, and the system handles dispatching them, including starting receivers.
Intents can be broadcasted to BroadcastReceivers, allowing messaging between applications. By registering a BroadcastReceiver in applicationâs AndroidManifest.xml (using <receiver> tag) you can have your applicationâs receiver class started and called whenever someone sends you a broadcast. Activity Manager uses the IntentFilters, applications register to figure out which program should be used for a given broadcast.
Letâs develop the receiver that will start and stop notify service on request. The base class android.content.BroadcastReceiver should be used for these purposes (http://developer.android.com/reference/android/content/BroadcastReceiver.html):
public class ServiceBroadcastReceiver extends BroadcastReceiver { ⦠private static String START_ACTION = “NotifyServiceStart”; private static String STOP_ACTION = “NotifyServiceStop”; ⦠public void onReceive(Context context, Intent intent) { ⦠String action = intent.getAction(); if (START_ACTION.equalsIgnoreCase(action)) { context.startService(new Intent(context, NotifyService.class)); } else if (STOP_ACTION.equalsIgnoreCase(action)) { context.stopService(new Intent(context, NotifyService.class)); } } }
To send broadcast from the client application we use the Context.sendBroadcast call. I will describe how to use receiver and send broadcasts from the PC in chapter 2.
1.4 Android Manifest
Every application must have an AndroidManifest.xml file in its root directory. The manifest contains essential information about the application to the Android system, the system must have this information before it can run any of the application’s code. The core components of an application (its activities, services, and broadcast receivers) are activated by intents. An intent is a bundle of information (an Intent object) describing a desired action â including the data to be acted upon, the category of component that should perform the action, and other pertinent instructions. Android locates an appropriate component to respond to the intent, starts the new instance of the component if one is needed, and passes it to the Intent object.
We should describe 2 components for our service:
NotifyService class is described in the <service> tag. It will not start on intent. So the intent filtering is not needed. ServiceBroadcastReceived class is described in the <receiver> tag. For the broadcast receiver the intent filter is used to select system events: <application android:icon=”@drawable/icon” android:label=”@string/app_name”> ⦠<service android:enabled=”true” android:name=”.NotifyService” android:exported=”true”> </service> <receiver android:name=”ServiceBroadcastReceiver”> <intent-filter> <action android:name=”NotifyServiceStart”></action> <action android:name=”NotifyServiceStop”></action> </intent-filter> </receiver> ⦠2. Java service remote installation and start 2.1 Service installation
Services like the other applications for the Android platform can be installed from the special package with the .apk extension. Android package contains all required binary files and the manifest.
Before installing the service from the PC we should enable the USB Debugging option in the device Settings-Applications-Development menu and then connect device to PC via the USB.
On the PC side we will use the ADB utility which is available in the Android SDK tools directory. The ADB utility supports several optional command-line arguments that provide powerful features, such as copying files to and from the device. The shell command-line argument lets you connect to the phone itself and issue rudimentary shell commands.
We will use several commands:
Remote shell command execution: adb shell <command> <arguments> File send operation: adb push <local path> <remote path> Package installation operation: adb install <package>.apk
Iâll describe the package installation process in details. It consists of several steps which are performed by the ADB utility install command:
First of all the .apk package file should be copied to the device. The ADB utility connects to the device and has limited âshellâ user privileges. So almost all file system directories are write-protected for it. The /data/local/tmp directory is used as the temporary storage for package files. To copy package to the device use the command: adb push NotifyService.apk /data/local/tmp Package installation. ADB utility uses special shell command to perform this operation. The âpmâ (Package Manager?) utility is present on the Android devices. It supports several command line parameters which are described in the Appendix I. To install the package by yourself execute the remote shell command: adb shell pm install /data/local/tmp/NotifyService.apk Cleanup. After the package is installed, ADB removes the temporary file stored in /data/local/tmp folder using the ârmâ utility: adb shell rm /data/local/tmp/NotifyService.apk. To uninstall package use the âpmâ utility: adb shell pm uninstall <package> 2.2 Remote service control
To be able to start and stop the NotifyService from the PC we can use the âamâ (Activity Manager?) utility which is present on the Android device. The command line parameters are described in the Appendix II. The âamâ utility can send system broadcast intents. Our service has the broadcast receiver which will be launched by the system request.
To start NotifyService we can execute remote shell command:
adb shell am broadcast âa NotifyServiceStart
To stop the NotifyService we can execute remote shell command:
adb shell am broadcast âa NotifyServiceStop
Note, that the NotifyServiceStart and NotifyServiceStop intents were described in the manifest file inside the <receiver> ⦠<intent-filter> tag. Other requests will not start the receiver.
Appendix I. PM Usage (from Android console) pm [list|path|install|uninstall] pm list packages [-f] pm list permission-groups pm list permissions [-g] [-f] [-d] [-u] [GROUP] pm path PACKAGE pm install [-l] [-r] PATH pm uninstall [-k] PACKAGE The list packages command prints all packages. Use the -f option to see their associated file. The list permission-groups command prints all known permission groups. The list permissions command prints all known permissions, optionally only those in GROUP. Use the -g option to organize by group. Use the -f option to print all information. Use the -s option for a short summary. Use the -d option to only list dangerous permissions. Use the -u option to list only the permissions users will see. The path command prints the path to the .apk of a package. The install command installs a package to the system. Use the -l option to install the package with FORWARD_LOCK. Use the -r option to reinstall an exisiting app, keeping its data. The uninstall command removes a package from the system. Use the -k option to keep the data and cache directories around after the package removal. Appendix II. AM Usage (from Android console) am [start|broadcast|instrument] am start -D INTENT am broadcast INTENT am instrument [-r] [-e <ARG_NAME> <ARG_VALUE>] [-p <PROF_FILE>] [-w] <COMPONENT> INTENT is described with: [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>] [-c <CATEGORY> [-c <CATEGORY>] …] [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...] [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...] [-e|--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...] [-n <COMPONENT>] [-f <FLAGS>] [<URI>] Resources used: Android Installation Guide.
http://developer.android.com/sdk/1.5_r2/installing.html
Android Developer reference.
http://developer.android.com/reference/classes.html
Jesse Burns. Developing Secure Mobile Applications for Android.
https://www.isecpartners.com/files/iSEC_Securing_Android_Apps.pdf
Designing a Remote Interface Using AIDL
http://developer.android.com/guide/developing/tools/aidl.html
More Android Articles
Apple Applications: Way To Enhance Your Device’s Performance
Empower yourself using the latest communication gadgets manufactured by the stalwarts in the scene. Apple can be one of those mobile majors for you which have shown the world the real fervor to communicate during the last few years. Apple is a brand that never compromises in its products, no matter whatever it may be. The Apple iPhone is a gadget for those brave hearts. Its superb connectivity, smart mobility, entertainment on the go, massive memory modules etc. have made it one of the top-selling products now in the scene. Apple applications those are available on the web for downloading and work intelligent with all versions of the product can just be a boon for you if not more! There are a large number of software development firms which have now jumped into the development of programs for the device. Also, independent and exclusive Apple iPhone developers have marked their potential entry into the thriving communication cum entertainment world.
Apple application development has shown a steady rise over the years – thanks to the onshore as well as offshore development units which tackle all kinds of iPhone programs quite effortlessly. These development facilities take pride in developing user-oriented Apple applications for different purposes. Even customized application development is now a reality with them.
Apple application design and development demand high levels of creativity. Every user wants an application that looks smart and easy to use, and on top of all should be able to perform as per his/her expectations. SDKs used for their developments are of very high standard and these are used only after strenuous research.
If you are more of a business minded guy and you need to travel a lot and stay online all time, then business applications for your iPhone can do the trick for you. The smartest business applications that Apple software developers have in store for you are just the best picks that you can easily choose for a nominal payment. Applications of entertainment, health, email, weather updtes, news etc. are also getting popular among every user. Browse the web, for a complete list of Apple applications developed by different Apple iPhone developers.
need a website? want to be #1 on Google? visit our florida web design company homepage
Future Apple Devices Looking to Solar Power
Solar power could help make devices truly portable, freeing from the need for wires to connect them to a power supply.
The larger the solar cell panel is the better it is for generating electricity, but as the patent “Solar cells on portable devices” warns, after allowing space for buttons, screens and a way to hold the device, only a small area is left on most devices for solar cells.
One of the ways around this dilemma is suggested in the patent as to stack a touch-sensitive layer, a display and solar panel on top of one another. That could make Apple’s iPhone and iPod Touch good candidates for such a power supply, as the display occupies almost the entire face of those devices.
The use of solar powered charging in portable devices is starting to get more attention, for more immediate consumer use as well.
When Vodafone announced its plan in April 2008, to reduce its emissions of the greenhouse gas CO2 by 50 percent by 2020, it also announced plans for solar-powered phone chargers and universal phone chargers for Vodafone-branded handsets.
At the recent ITU Telecom Africa 2008 conference, Ugandan Minister for Communications and Information and Communication Technologies Ham-Mukasa Mulira talked about trials of solar-powered charging conducted there, which had showed promising results.
need a website? want to be #1 on Google? visit our florida web design company homepage
Apple Ipod Nano: Most Popular Devices Among All Ipods
Enjoying your favourite music on the go is a very old one. From leather cased transistors to big stereo cassette players on shoulder – people have done many things to be surrounded by the kind of music he likes, all the time. The concept of an entirely new compact solution saw its inception in Japan by Sony. Since then, mobile music has attracted music enthusiast from all sphere of life.
Cassette playing Walkmans and Walkys became obsolete after media format changed from analog to digital. Digital revolution made it possible to carry hundreds and thousands of songs in a tiny shell or a Compact Disc. Portable CD players or Discman too were no more than just a passing fad. However, extremely petite media players got immense popularity and still are one of the major sources of mobile music industry.
The name Apple iPod is synonymous with the digital mobile music revolution as Sony’s Walkman brand was with mobile cassette players. Its manufacturers have not just confined to one type of media player, but have branched out to offer customized solutions according to care of a user’s specific needs. iPod shuffle – an extremely petite digital music player with 1GB memory is ideal for those who only listens to music for a short period of time, while iPod video is not just for audio files, but high definition videos as well, completed with a video screen. Within the Apple’s iPod portfolio, the Apple iPod nano is one of the most popular devices among all iPod users.
The Apple iPod nano looks extremely sleek in its super slim case. The device is 3.5 inch tall, 1.6 inch wide and mere 0.26 inch thick. The devices are available in Apple iPod nano 2GB, 4GB and a massive 8GB memory space. It is therefore, convenient for customers to pick up the one iPod Nano best suited for his needs and expectations. The device is fitted with a powerful battery that lasts for up to 24 hours to give you uninterrupted playback for a long time.
need a website? want to be #1 on Google? visit our florida web design company homepage
Microsoft and At&t Jaw Dropping Devices
Both Microsoft and AT&T are very well known companies world wide, however recently they have both created a partnership which will enhance the mobile phone buying experience. Microsoft has come up with a very innovative device called the “Surface” which is basically a 30 inch tablet-like monitor which has several infrared cameras which detect the slightest change in the surface and translates it into software commands which return a visually appealing response.
In order to better understand what the Surface does and how it will be of benefit to mobile phone retailers as well as casinos, restaurants, etc. is by comparing it to tablet PCs, as you may know tablet PCs have been designed to be user friendly, they have a touch screen on which digital artists are able to manipulate their images using a pen; traditional users are also able to benefit from tablets by being able to interact with their applications or browse the web using a pen instead of a mouse.
Incidentally, Microsoft’s Surface brings these elements and improves them dramatically in their latest product which will be launched primarily in retail stores such as AT&T. The way this new interactive virtual display works is by easily connecting to any device such as a mobile phone and instantly recognizing it’s content and giving the user several options to manipulate such content, some may say this is the perfect link between hardware and the virtual world.
Pieces of information and data found on a mobile phone such as contacts, MP3 files, videos, pictures, etc can all be seen through the Surface and then organized just the way the user wants. In retail stores the Surface will be used in a way which will allow interested mobile phone buyers to place two phones they are interested in and the Surface will then provide a table of contents for both items which will make it easy to compare the features on both phones. Plans can also be compared through the table which lays them out in a visually appealing way that is easy to understand.
Table users will also be able to transfer digital photos or MP3 tunes from their devices to their mobile phones by simply placing the devices on the Surface and dragging the media files from the source into the mobile phone, which is just amazing. The only problem is that not every phone is compatible with the Surface, so obviously buyers will have to acquire the latest mobile phones in order for the surface to be able to deliver all the benefits it is intended to. Without a doubt this is a great idea Microsoft and AT&T have come up with, lets see how the public will adapt to it when it is launched in retail stores in April 17th, 2008.
need a website? want to be #1 on Google? visit our florida web design company homepage
Apple Ipods are Elegantly Designed Devices
Apple iPods are elegantly designed devices that are available in different colours. These devices are capable of providing round the clock entertainment as their battery can render 24 hours of standby time. The storage capacity of the Apple iPods also varies from model to model. The memory of iPods ranges from 2GB to 8GB. The device can store up to 2000 songs in it.
Listening to music is the real catch of the Apple iPod. Besides this, the iPod can also be used to download games and watch TV shows on its large display screen. The click wheel of the device is very useful for specific music recognition functions, controlling volume, or to search the menus for songs, artists, genres and albums. The device has a sleek metallic look. It is capable of delivering 24 hours of standby and 5 hours of video playback time. The Wi-Fi technology enables access to the internet. So, now it is possible to have fast downloads of games, music and videos.
Apple iPod can download 25,000 photos and there is also the option of slide shows. Watching videos on the large screen of the device is also very enjoyable. The device is available under various contract deals and is an interesting gadget to acquire. The Apple stores around the world are offering this new gadget with genuine warranty. Here you will find latest models of Apple iPods. We also allow the users to compare the prices of different products at various retailers. This will help them to get the best value for their money.
need a website? want to be #1 on Google? visit our florida web design company homepage
Archives
- April 2012
- March 2012
- January 2012
- December 2011
- November 2011
- October 2011
- September 2011
- August 2011
- July 2011
- June 2011
- May 2011
- April 2011
- March 2011
- February 2011
- January 2011
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- January 2009
Categories
- 861
- 8615
- Custom Web Design
- Email Marketing
- Google Optimization
- Google's Nexus One
- Graphic Design
- Jacksonville Furniture Stores
- Misc
- SEO
- Social Media Marketing
- Technology
- Twitter Marketing
- Uncategorized
- Web Design
- Web Development
- Web Marketing
- Website Design Companies
- Website Design Resources
- Website Marketing Companies
- Website Marketing Resources
Recent Posts
- Locating the Best SEO Company Your Website Needs for Top Ranking
- Free Keyword Research – How to Use Long-Tail Keywords to Build Your Internet Business Quickly
- Advantage of Best Website Designing!
- Camel Crochet Ultimate Bundle
- How To Litter Box Train Your Dog.
Views
- Concept Of Search Engine Optimaization for website marketing - 25,097 views
- Avnet Electronics Marketing First Distributor Certified by Renesas Technology America to Program Board ID Products (Business Wire via Yahoo! Finance) - 19,691 views
- A Bad Apple Logic Board Can be Very Inexpensive to Repair - 11,193 views
- Adobe Photoshop CS2 V 9.0 buy cheap - 8,252 views
- Strategic Internet Marketing Online Advertising Is Apparently the Solution for Small Businesses - 7,595 views
- Pop-ups Versus Banner Ads: Which Is Better For Increased Website Traffic? - 7,570 views
- SEO Tips for Designing a Top Ranking E-commerce Website by Rosemary Donald - 7,255 views
- Contextured Uncovers how Leading Automotive Firms are Turning to Online Marketing to Beat the Recession - 6,421 views
- Guide to SEO Keyword Research - 6,250 views
- Cheap Apple Logic Board Repair - 6,142 views
Resources
Recent Comments
- Andrew A. Sailer on Guide to SEO Keyword Research
- Matthew C. Kriner on Guide to SEO Keyword Research
- Burton Haynes on iTunes Store
- Andrew A. Sailer on iTunes Store
- Gregory Despain on Why Online Advertising Agency Opts for Video Advertising


