Well its been a while since I updated my blog. Basically I finished a contract back in June last year and decided to take some time off. I've been doing anything other that work really :) Actually I have been doing some of my own programming projects to keep my hand in, basically a bit of Swing and a fair bit of Android. I plan to start looking around for new Contracts again shortly.
I plan to have my first Android App out in the next month or so and around that time I will start posting on some of the more technical issues about the Android Eco System and some of the problems I came across and how I resolved them.
In the meantime here is a quick, brief 10,000ft overview/observations on Android from a Swing developers point of view.
Firstly if your coming to Android from Swing you are approaching it with a big advantage to J2EE developers. Now I realise Android doesn't actually have the AWT/Swing API's but that doesn't matter as the general front end/event driven mechanism in it is so close to Swing that you will find it easy. Now Android does rely a lot more on XML defs than Swing ever did and that took me a while to get my head around and realise how powerful a feature it actually it is if used correctly.
I started off by buying a couple of books:
Learning Android
Programming Android
I'd recommend both of these as they cover the basics very well, from then on you can use the online Android SDK docs. Other books I've seen are not great to be honest, you will be better off googling.
Android GUI is like Swing, it's on a single thread, if you do some heavy lifting on that thread it will cause some issue's just like with Swing. There are mechanisms and classes available that like SwingWorker help you out (more of this in later blogs).
A typical Android screen is created by an Activity class that you have extended. This class typically inflates an XML definition on the screen layout. The XML defines the textfields, comboboxes (called Spinners) and so on. Eclipse is typically used to create the XML (I use the Graphical Layout Tool in Eclipse which is still very buggy but ok). You can also hard code the layouts but I wouldn't bother as it's easier to use the XML. The Activities are state driven, they are created, paused, resumed and so on. The states are there because they run on a small device where calls can come in, other programs started an so on. The screens for your app can be hidden, displayed again, killed off and restarted .... You need to handle this and in some cases persist the data.
The Activity states are a bit of a head scratcher to start with but once you try a few examples out its straightforward enough.
Handling Events from components (Views in Android) is so similar to Swing it makes me wonder if somebody copied the event mechanism ;)
Any Activity you create needs to be defined in your applications Manifest file, this file is used by the Android device to figure out you apps main class, the icon, the privileges it needs and so on. If you don't specify an Activity on the manifest then the app will stack trace when you attempt to display it.
Jumping from screen to screen is done by the use of Intents. Intents are used by Android to signal that you want something to happen. You can create an Intent passing in the class that you want to process the Intent (so say an Activity which displays another screen) or you can ask for some operation, so for instance display this web page, Android in this case would open a browser and display the page. If you had several browsers installed it might ask you which one to use. Android keeps an internal stack so that when the back key is pressed then it will switch back from the browser back to your apps Activity (remember the states I mentioned, your Activity has just had its resume state called ;).
Android has some nice features to let you define backgrounds and the look of buttons. This seems to be similar to JavaFX. Basically you can define gradients, patch 9 images (a way of taking a small image and extending it to fit a background nicely), shapes .......
Android comes complete with SQLite3 which is a nice lightweight database. I've found it very quick and nice to use. I'll return to this in another blog as I'm not sure the preferred way to use the database in the most books is actually a good idea.
Finally there is a emulator to test your apps on. Its ok, lets you test things on different versions of android and different device specs (screens, memory, input methods (rollers, soft/hard keyboard)) but its slow and really I'd say if you want to really write and app you need atleast one Android device. I have a nice Nexus S Mmmmmm lovely.
Anyway thats a very brief overview and when I finish my App I will have some time to spend adding some nice new blogs.
Enjoy
Please give a recommend below if you liked the article.
My Java development and Android findings, thoughts and rants. I expect to mainly post about JDesktop and Android related issues but will no doubt go off topic many many times.
I'm writing this as someone who actually uses Java at the coal face and not as someone who sits in an ivory tower quoting happy day scenarios. So don't expect perfect code, full use of patterns. I'll be posting about stuff that is actually useful for me and with any luck others!
Core Java Books
Thursday, 5 January 2012
Tuesday, 5 April 2011
Java GUI Application Shutdown Gotcha
In recent times I've had issues with one or two Java GUI application not shutting down when I close them. They seem to stay around as a process, consuming computer resources. Today I got to the bottom of the problem and it's a bit of a nasty gotcha which I wasn't aware of before so I thought I would share it.
In theory when you close a Java application all the threads should be stopped and the process should die. Im my case when I monitored the application the threads I expected to finish such as Swing worker pools were still alive, Strange. The reason turned out to be that the AWT Shutdown thread wasn't terminating all the helper threads, and the reason for this was that there were still AWT Events in the EventQueues. The reason for this is a real sneaky little gatcha, I will explain.
My application used a Thread which had a regular sleep but when woke up would so some calculation and then make a call to update the gui:
Thread updateThread = new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
do {
try {
Thread.sleep(300); // 300ms
gui.updateValue(SOME_VALUE);
} catch (InterruptException ex) {
return;
}
frame.setValue(SOMEDATA);
} while (i++ < 100);
}
}, "updateThread");
updateThread.setDaemon(true);
updateThread.start();
Now you will notice that the thread returns if it is interrupted and also it is started as a Daemon thread. I had thought that as part of the application shutdown the thread would be terminated but NO it wasn't. This was caused by gui.updateValue(SOME_VALUE) making use of InvokeLater:
public void updateValue(final int value) {
// make sure we access graphics in the EDT thread
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
...
...
...
SOME CODE
} catch (Exception t) {
// not a lot to do
}
}
});
}
The InvokeLater is basically putting an event on the EventQueue and because of this the AWT Shutdown thread want shutdown the application. The AWT Shutdown thread checks the EventQueues every seconds but as you will see my Thread does an update subsecond (300ms) so there is always an event on the Queue! So in short the AWT Shutdown thread never terminates the threads I want it to terminate and so the application needs to be killed.
The work around is simple in the while loop of my thread I also check that the JComonent that is to be updated via it is still visible and shown, if it is not the loop is exited, the thread dies and so there are no more events put on the Event thread and whooohooo the application closes as expected :)
Thread updateThread = new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
do {
try {
Thread.sleep(300); // 300ms
gui.updateValue(SOME_VALUE);
} catch (InterruptException ex) {
return;
}
frame.setValue(SOMEDATA);
}while (i < 100 && progressGlassPane.isVisible() && progressGlassPane.isShowing());
}
}, "updateThread");
updateThread.setDaemon(true);
updateThread.start();
So in short don't call InvokeLater from a helper thread at sub-second frequency unless you also terminate the thread if the component it is updating is no longer visible!
As a side note after I spotted the issue I found this very useful article on the same subject which highlighted the same issue I was having.
In theory when you close a Java application all the threads should be stopped and the process should die. Im my case when I monitored the application the threads I expected to finish such as Swing worker pools were still alive, Strange. The reason turned out to be that the AWT Shutdown thread wasn't terminating all the helper threads, and the reason for this was that there were still AWT Events in the EventQueues. The reason for this is a real sneaky little gatcha, I will explain.
My application used a Thread which had a regular sleep but when woke up would so some calculation and then make a call to update the gui:
Thread updateThread = new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
do {
try {
Thread.sleep(300); // 300ms
gui.updateValue(SOME_VALUE);
} catch (InterruptException ex) {
return;
}
frame.setValue(SOMEDATA);
} while (i++ < 100);
}
}, "updateThread");
updateThread.setDaemon(true);
updateThread.start();
Now you will notice that the thread returns if it is interrupted and also it is started as a Daemon thread. I had thought that as part of the application shutdown the thread would be terminated but NO it wasn't. This was caused by gui.updateValue(SOME_VALUE) making use of InvokeLater:
public void updateValue(final int value) {
// make sure we access graphics in the EDT thread
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
...
...
...
SOME CODE
} catch (Exception t) {
// not a lot to do
}
}
});
}
The InvokeLater is basically putting an event on the EventQueue and because of this the AWT Shutdown thread want shutdown the application. The AWT Shutdown thread checks the EventQueues every seconds but as you will see my Thread does an update subsecond (300ms) so there is always an event on the Queue! So in short the AWT Shutdown thread never terminates the threads I want it to terminate and so the application needs to be killed.
The work around is simple in the while loop of my thread I also check that the JComonent that is to be updated via it is still visible and shown, if it is not the loop is exited, the thread dies and so there are no more events put on the Event thread and whooohooo the application closes as expected :)
Thread updateThread = new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
do {
try {
Thread.sleep(300); // 300ms
gui.updateValue(SOME_VALUE);
} catch (InterruptException ex) {
return;
}
frame.setValue(SOMEDATA);
}while (i < 100 && progressGlassPane.isVisible() && progressGlassPane.isShowing());
}
}, "updateThread");
updateThread.setDaemon(true);
updateThread.start();
So in short don't call InvokeLater from a helper thread at sub-second frequency unless you also terminate the thread if the component it is updating is no longer visible!
As a side note after I spotted the issue I found this very useful article on the same subject which highlighted the same issue I was having.
Monday, 28 March 2011
Providing Mock API's at Runtime
This article is about how I provide a mock api's to my applications at runtime so I can test them without external services being involved.
Many of the application I work on make use of api's to servers, communications engines and so on. I find it useful to be able to test my application with mock API's so I have more control of the tests on it and can test it standalone. Also the mechanism provided allows me to run my application when a service has yet to be delivered but is defined. I could make use of dependency injection if I was to drag JEE api's into my build but I prefer the simple approach. It might not be perfect but it works.
Lets say I have an external interface that my application makes use of:
public interface Service {
void addListener(final ServiceListener listener);
void removeListener(final ServiceListener listener);
}
Now in my application I would typically construct a concrete class either directly or via a factory method which implements the interface contract. Whilst testing I would like to actually provide another version of the implementing class which can be used to test my application with the interface:
public class MockService implements Service {
private static List<ServiceListener> listeners = new ArrayList<ServiceListener>();
public void addListener(ServiceListener listener) {
listeners.add(listener);
}
public void removeListener(ServiceListener listener) {
listeners.remove(listener);
}
public void newRequestReceived(final ExternalRequest request) {
RequestEvent event = new RequestEvent(request);
for(ServiceListener listener : listeners) {
listener.notifyRequestEvent(event);
}
}
}
I provide the mock class making use of a command line property:
java -Dservice.api.classname=com.webbyit.MockService -jar myapp.jar
Now in the code of my app I make use of the property (maybe within a factory method) and construct the class provided rather than the default class:
private static Service getService() {
synchronized (ServiceLock) {
if (Service == null) {
String serviceClassName = System.getProperty("service.api.classname");
if (serviceClassName == null) {
Service = new RealService();
} else {
try {
Service = (Service) Class.forName(serviceClassName).newInstance();
} catch (InstantiationException e) {
throwCallServiceInitialisationException(serviceClassName, e);
} catch (IllegalAccessException e) {
throwCallServiceInitialisationException(serviceClassName, e);
} catch (ClassNotFoundException e) {
throwCallServiceInitialisationException(serviceClassName, e);
}
}
}
}
return Service;
}
}
So what I have done is test for an alternative class being specified by a property (via the command line). If set the code attempts to construct the alternative class and use that instead of the default class usually used by the application.
Many of the application I work on make use of api's to servers, communications engines and so on. I find it useful to be able to test my application with mock API's so I have more control of the tests on it and can test it standalone. Also the mechanism provided allows me to run my application when a service has yet to be delivered but is defined. I could make use of dependency injection if I was to drag JEE api's into my build but I prefer the simple approach. It might not be perfect but it works.
Lets say I have an external interface that my application makes use of:
public interface Service {
void addListener(final ServiceListener listener);
void removeListener(final ServiceListener listener);
}
Now in my application I would typically construct a concrete class either directly or via a factory method which implements the interface contract. Whilst testing I would like to actually provide another version of the implementing class which can be used to test my application with the interface:
public class MockService implements Service {
private static List<ServiceListener> listeners = new ArrayList<ServiceListener>();
public void addListener(ServiceListener listener) {
listeners.add(listener);
}
public void removeListener(ServiceListener listener) {
listeners.remove(listener);
}
public void newRequestReceived(final ExternalRequest request) {
RequestEvent event = new RequestEvent(request);
for(ServiceListener listener : listeners) {
listener.notifyRequestEvent(event);
}
}
}
I provide the mock class making use of a command line property:
java -Dservice.api.classname=com.webbyit.MockService -jar myapp.jar
Now in the code of my app I make use of the property (maybe within a factory method) and construct the class provided rather than the default class:
private static Service getService() {
synchronized (ServiceLock) {
if (Service == null) {
String serviceClassName = System.getProperty("service.api.classname");
if (serviceClassName == null) {
Service = new RealService();
} else {
try {
Service = (Service) Class.forName(serviceClassName).newInstance();
} catch (InstantiationException e) {
throwCallServiceInitialisationException(serviceClassName, e);
} catch (IllegalAccessException e) {
throwCallServiceInitialisationException(serviceClassName, e);
} catch (ClassNotFoundException e) {
throwCallServiceInitialisationException(serviceClassName, e);
}
}
}
}
return Service;
}
}
So what I have done is test for an alternative class being specified by a property (via the command line). If set the code attempts to construct the alternative class and use that instead of the default class usually used by the application.
Subscribe to:
Posts (Atom)