<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>BlackBerry Developer Blog &#187; Denver C.</title>
	<atom:link href="http://devblog.blackberry.com/author/denvercon1/feed/" rel="self" type="application/rss+xml" />
	<link>http://devblog.blackberry.com</link>
	<description></description>
	<lastBuildDate>Fri, 24 May 2013 15:08:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='devblog.blackberry.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://1.gravatar.com/blavatar/9ef0a66c09615fa946c4179662398878?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>BlackBerry Developer Blog &#187; Denver C.</title>
		<link>http://devblog.blackberry.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://devblog.blackberry.com/osd.xml" title="BlackBerry Developer Blog" />
	<atom:link rel='hub' href='http://devblog.blackberry.com/?pushpress=hub'/>
		<item>
		<title>Media Actions API in BlackBerry JDE v5.0.0 How-To</title>
		<link>http://devblog.blackberry.com/2009/08/media-actions-api-in-blackberry-jde-v5-0-0-how-to/</link>
		<comments>http://devblog.blackberry.com/2009/08/media-actions-api-in-blackberry-jde-v5-0-0-how-to/#comments</comments>
		<pubDate>Fri, 14 Aug 2009 15:38:00 +0000</pubDate>
		<dc:creator>Denver C.</dc:creator>
				<category><![CDATA[How-to]]></category>
		<category><![CDATA[Java Development]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jde 5.0]]></category>
		<category><![CDATA[Media]]></category>
		<category><![CDATA[MediaActionHandler]]></category>

		<guid isPermaLink="false">http://devblog.blackberry.com/?p=854</guid>
		<description><![CDATA[I would like to talk about a new API feature in the BlackBerry® Java® Development Environment v5.0 (Beta) I worked on called the Media Actions API. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=devblog.blackberry.com&#038;blog=17235680&#038;post=854&#038;subd=rimdevblog&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p style="text-align:center;"><img class="aligncenter size-full wp-image-855" title="BlackBerry® media" src="http://rimdevblog.files.wordpress.com/2009/08/blackberry-media.jpg?w=384&#038;h=315" alt="" width="384" height="315" /></p>
<p>I would like to talk about a new API feature in the <a title="BlackBerry® Java® Development Environment v5.0 (Beta)" href="http://na.blackberry.com/eng/developers/devbetasoftware/javasdk5.jsp" target="_new">BlackBerry® Java® Development Environment v5.0 (Beta)</a> I worked on called the Media Actions API.  In this article I will discuss how to use this API to respond to media key presses in the same way that the built-in media player does: respond to media key presses while in the background, and respond to key presses on connected wired headsets and paired Bluetooth® headsets.  I will also discuss some things to keep in mind when using this API, as well as some implementation details.  Finally, I will explain how to use this functionality from MIDlets, even without using non-standard APIs.  Included within the BlackBerry JDE v5.0.0 beta is a great sample media player application that demonstrates how to use the API and I would encourage you to look at this demo and play with it.  There is also a simple application included at the end of this article for reference.</p>
<p>The key to the Media Actions API is the new interface net.rim.device.api.media.MediaActionHandler, which defines a single method:</p>
<p>public boolean mediaAction(int action, int source, Object context)</p>
<p>The implementation of this method is expected to respond to the specified “action”, which will be equal to one of the MEDIA_ACTION_ constants defined in the interface.  These action constants represent common media player actions, such as play/pause, next/previous track, and volume up/down.  The “source” and “context” parameters contain additional information about where the action came from and may be used by the implementation to behave differently depending on their values.  Examples of values for the “action” parameter are MEDIA_ACTION_PLAYPAUSE_TOGGLE and MEDIA_ACTION_NEXT_TRACK.  Examples of values for the “source” parameter are SOURCE_BACKGROUND_KEY and SOURCE_WIRED_HEADSET.</p>
<p>The first use of the MediaActionHandler interface is to respond to media key presses while the application is in the foreground.  A new abstract class has been created that implements KeyListener and provides standard mappings from key presses to media actions: net.rim.device.api.media.MediaKeyListener.  These mappings depend on the hardware keys available on each BlackBerry smartphone and are the exact mappings used by the built-in BlackBerry Media Player application.  For example, if the BlackBerry smartphone does not have dedicated “next” and “previous” keys then pressing-and-holding the volume keys will generate “next track” and “previous track” media actions; however, on devices that do have dedicated “next” and “previous” keys these buttons will be used to generate the next/previous track actions and pressing-and-holding the volume keys will do nothing.  The MediaKeyListener class implements all methods defined by KeyListener but does not implement the method defined by MediaActionHandler, as it is left to a subclass.  An instance of MediaKeyListener can be registered by invoking addKeyListener(KeyListener) on the Application instance for the application.</p>
<p>The second use of this interface is to respond to media key presses while the application is in the background.  Normally, applications are only able to respond to key presses while in the foreground; to respond to key presses while in the background an application must register an instance of MediaActionHandler using the new method addMediaActionHandler(MediaActionHandler), defined in the Application class.  After registration, the MediaActionHandler will be notified of media actions resulting from media key presses even when it is in the background.  The mappings from key presses to media actions are identical to the standard mappings implemented by MediaKeyListener and cannot be modified.</p>
<p>The third use of the MediaActionHandler interface is to respond to key presses on a connected wired headset and/or paired Bluetooth® headset.  In fact, this functionality comes for free when registering a MediaActionHandler.  This is because the mediaAction() method is invoked when buttons are pressed on one of these headsets, just like it is invoked when media keys on the BlackBerry smartphone itself are pressed.  The only difference is that the “source” parameter will be equal to the SOURCE_ constants defined in MediaActionHandler and the “context” parameter will be non-null, as documented in the javadocs for the SOURCE_ constants.  Note, however, that media actions from all sources are delivered even if audio is being played through only one of the sources.  For example, if an application is playing audio through a wired headset and the user presses a button on a paired Bluetooth headset, then the corresponding media action will still be delivered to the application; it is up to the application to choose whether or not to respond to it.</p>
<p>Care was taken during implementation to ensure that when multiple applications register a MediaActionHandler only one of them is actually notified, and the choice of which one is notified is made in a fair way.  The rationale was that if multiple media player applications were running in the background and the user presses the play/pause button they would want to pause the current song; but if both applications were notified then it would pause one and begin playback in the other, an annoying user experience.  Therefore, only the most-recently-foregrounded application that has registered a MediaActionHandler will be notified.  This heuristic was chosen because it is assumed that the background media player application that the user wants to control is most likely to be the one that was most recently used explicitly.  If that application exits, then the one that was most-recently-foregrounded before it will be the one that gets notified, and so on.  Effectively, a “stack” of applications is maintained and only the application on the top of the stack gets notified of media actions, and an application is moved to the top of the stack when it comes to the foreground.</p>
<p>So far, this article has only discussed how to use the Media Actions API in CLDC applications, those that extend net.rim.device.api.system.Application; however, this feature is also available in MIDlet applications, those that extend javax.microedition.midlet.MIDlet.  A MIDlet is free to register a MediaActionHandler just like a CLDC application and will receive callbacks in exactly the same way.  But the Canvas class has been modified for native support of media keys.  Already, applications can override the keyPressed(), keyReleased(), and keyRepeated() methods of Canvas to respond to key presses while in the foreground and the keyCode for volume up and volume down are already documented to be -150 and -151, respectively.  In BlackBerry JDE v5.0.0 keyCodes for mute/speakerphone, next, and previous keys were added: -2731, -4100, and -4101, respectively.  But one problem with simply implementing keyXXX() to handle these new keyCodes is that another media player application that is in the background will also be notified of these key presses.  To fix this problem, the concept of “media player mode” for MIDlets was introduced.  If media player mode is enabled then two things change: background applications are not notified of media key presses that occur while the MIDlet is in the foreground and the MIDlet is notified of media key presses that occur while it is in the background.  The MIDlet application will be inserted into and moved around in the application “stack” just like CLDC applications to contend for receiving notifications of background media keys.  By default, media player mode is disabled and it can be enabled by using the new interface net.rim.device.api.lcdui.control.MediaBehaviourControl, whose instance can be obtained from the Display object (see javadocs for details).  Alternately, the JAD attribute RIM-MIDlet-MediaPlayerModeEnabled can be set to “1” for media player mode to instead be enabled by default, thus avoiding the use of any non-standard APIs.</p>
<p>I really hope that media player application developers will find this API easy to use and of value to their applications.  Also, I hope to see some creative uses of this API that I could never have foreseen, which always impresses me!  Please comment on this article with feedback, both positive and negative, about the API.  You can try it out in the BlackBerry 5.0.0 JDE beta that is available at the link below.</p>
<p><a title="BlackBerry® Java® Development Environment v5.0 (Beta)" href="http://na.blackberry.com/eng/developers/devbetasoftware/javasdk5.jsp" target="_new">BlackBerry® Java® Development Environment v5.0 (Beta)</a></p>
<p>Below is a very simple application that demonstrates how an application can respond to media actions.</p>
<div class="sample"><code>import net.rim.device.api.media.MediaKeyListener;<br />
import net.rim.device.api.ui.Field;<br />
import net.rim.device.api.ui.Screen;<br />
import net.rim.device.api.ui.UiApplication;<br />
import net.rim.device.api.ui.component.LabelField;<br />
import net.rim.device.api.ui.component.SeparatorField;<br />
import net.rim.device.api.ui.container.MainScreen;</code></p>
<p>public class MediaActionsAPIDemo extends UiApplication {</p>
<p>private static final String INSTRUCTION_TEXT =<br />
&#8220;Press a media key, even when in the background, &#8220;<br />
+ &#8220;and the corresponding action will be logged &#8220;<br />
+ &#8220;to the screen and standard output.&#8221;;</p>
<p>private final MainScreen _screen;</p>
<p>public MediaActionsAPIDemo() {<br />
this._screen = new MainScreen();<br />
this._screen.setTitle(&#8220;Media Actions API Demo&#8221;);<br />
this._screen.add(new LabelField(INSTRUCTION_TEXT));</p>
<p>this._screen.add(new SeparatorField());<br />
this.pushScreen(this._screen);</p>
<p>final MyMediaKeyListener myMediaKeyListener =<br />
new MyMediaKeyListener(this._screen);<br />
this.addKeyListener(myMediaKeyListener);<br />
this.addMediaActionHandler(myMediaKeyListener);<br />
}</p>
<p>public static void main(String[] args) {<br />
new MediaActionsAPIDemo().enterEventDispatcher();<br />
}</p>
<p>private static class MyMediaKeyListener extends<br />
MediaKeyListener {</p>
<p>private final Screen _logScreen;</p>
<p>public MyMediaKeyListener(Screen logScreen) {<br />
this._logScreen = logScreen;<br />
}</p>
<p>public boolean mediaAction(int action, int source,<br />
Object context) {<br />
final StringBuffer sb = new StringBuffer(200);<br />
sb.append(&#8220;mediaAction(action=&#8221;);<br />
sb.append(getActionName(action));<br />
sb.append(&#8220;, source=&#8221;);<br />
sb.append(getSourceName(source));<br />
sb.append(&#8220;, context=&#8221;);<br />
sb.append(context);<br />
sb.append(&#8216;)&#8217;);</p>
<p>final String message = sb.toString();<br />
System.out.println(message);<br />
final LabelField field =<br />
new LabelField(message, Field.FOCUSABLE);<br />
this._logScreen.add(field);</p>
<p>return true;<br />
}</p>
<p>public static String getActionName(int action) {<br />
switch (action) {<br />
case MEDIA_ACTION_NEXT_TRACK:<br />
return &#8220;NEXT_TRACK&#8221;;<br />
case MEDIA_ACTION_PLAYPAUSE_TOGGLE:<br />
return &#8220;PLAYPAUSE_TOGGLE&#8221;;<br />
case MEDIA_ACTION_PREV_TRACK:<br />
return &#8220;PREV_TRACK&#8221;;<br />
case MEDIA_ACTION_VOLUME_DOWN:<br />
return &#8220;VOLUME_DOWN&#8221;;<br />
case MEDIA_ACTION_VOLUME_UP:<br />
return &#8220;VOLUME_UP&#8221;;<br />
}<br />
return Integer.toString(action);<br />
}</p>
<p>public static String getSourceName(int source) {<br />
switch (source) {<br />
case SOURCE_BACKGROUND_KEY:<br />
return &#8220;BACKGROUND_KEY&#8221;;<br />
case SOURCE_BLUETOOTH_HEADSET:<br />
return &#8220;BLUETOOTH_HEADSET&#8221;;<br />
case SOURCE_FOREGROUND_KEY:<br />
return &#8220;FOREGROUND_KEY&#8221;;<br />
case SOURCE_WIRED_HEADSET:<br />
return &#8220;WIRED_HEADSET&#8221;;</p>
<p>}<br />
return Integer.toString(source);<br />
}<br />
}</p>
<p>}</p>
</div>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/rimdevblog.wordpress.com/854/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/rimdevblog.wordpress.com/854/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=devblog.blackberry.com&#038;blog=17235680&#038;post=854&#038;subd=rimdevblog&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://devblog.blackberry.com/2009/08/media-actions-api-in-blackberry-jde-v5-0-0-how-to/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/035dc37bb725cb59d3b846aeb8a55c6c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">denvercon1</media:title>
		</media:content>

		<media:content url="http://rimdevblog.files.wordpress.com/2009/08/blackberry-media.jpg" medium="image">
			<media:title type="html">BlackBerry® media</media:title>
		</media:content>
	</item>
		<item>
		<title>BlackBerry API Hidden Gems (Part Two)</title>
		<link>http://devblog.blackberry.com/2009/08/blackberry-api-hidden-gems-part-two/</link>
		<comments>http://devblog.blackberry.com/2009/08/blackberry-api-hidden-gems-part-two/#comments</comments>
		<pubDate>Thu, 13 Aug 2009 12:22:00 +0000</pubDate>
		<dc:creator>Denver C.</dc:creator>
				<category><![CDATA[Java Development]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[IntVector]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[timer]]></category>

		<guid isPermaLink="false">http://devblog.blackberry.com/?p=850</guid>
		<description><![CDATA[In yesterday's BlackBerry API Hidden Gems post, I showed you some of my favorite classes and methods oft overlooked within BlackBerry® APIs. I've got a few more in store for you today, so let's get started! [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=devblog.blackberry.com&#038;blog=17235680&#038;post=850&#038;subd=rimdevblog&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p style="text-align:center;"><img class="aligncenter size-full wp-image-837" title="hidden gems" src="http://rimdevblog.files.wordpress.com/2009/08/hidden-gems.jpg?w=480&#038;h=360" alt="" width="480" height="360" /></p>
<p>In yesterday&#8217;s <a href="http://devblog.blackberry.com/2009/08/blackberry-api-hidden-gems-part-one/">BlackBerry API Hidden Gems post</a>, I showed you some of my favorite classes and methods oft overlooked within BlackBerry® APIs. I&#8217;ve got a few more in store for you today, so let&#8217;s get started!</p>
<h2>IntVector</h2>
<p>In the net.rim.device.api.util package there are a bunch of collections for storing primitive Java types, such as ‘int’, ‘byte’, and ‘long’, which mirror the equivalent java.util classes.  Using these classes to store the primitive types is more efficient in both memory and time than storing wrapper objects in standard java.util collections.</p>
<p>My favourite example is IntVector.  IntVector has the same methods as java.util.Vector but stores primitive ‘int’ values instead of Object references.  Under the hood it uses an int[] array to store values instead of an Object[] array and therefore no conversions between ‘int’ and Integer are necessary.   This makes IntVector much better for storing ‘int’ values than java.util.Vector as it is both faster and uses less memory.  It is also fully synchronized, just like java.util.Vector.</p>
<p>Other adapted classes in net.rim.device.api.util include:</p>
<ul>
<li>ByteVector and LongVector: similar to IntVector but for ‘byte’ and ‘long’ types.</li>
<li>IntHashtable, LongHashtable: adaptations of Hashtable that use primitive ‘int’ and ‘long’ values as the keys, and Objects as the values.</li>
<li>ToIntHashtable, ToLongHashtable: similar to IntHashtable and LongHashtable but uses Objects for the keys and ‘int’ and ‘long’ for the values.</li>
</ul>
<p>Here is an example usage of IntVector to store a list of high scores, with the highest scores at the lowest indices.</p>
<div class="sample">
<p><code>public class HighScores {</code></p>
<p>private IntVector _scores;</p>
<p>public HighScores() {<br />
_scores = new IntVector();<br />
}</p>
<p>public void add(int score) {<br />
if (_scores.contains(score)) {<br />
return; // already there<br />
}</p>
<p>boolean isAdded = false;<br />
for (int i = 0; i &lt; _scores.size(); i++) {<br />
if (_scores.elementAt(i) &lt; score) {                 _scores.insertElementAt(score, i);                 isAdded = true;                 break;             }         }         if (!isAdded) {             _scores.addElement(score);         }         while (_scores.size() &gt; 10) {<br />
_scores.removeElementAt(_scores.size() &#8211; 1);<br />
}<br />
}</p>
<p>public int getHighScore() {<br />
if (_scores.isEmpty()) {<br />
return 0;<br />
} else {<br />
return _scores.elementAt(0);<br />
}<br />
}</p>
<p>public int[] getHighScores() {<br />
int[] array = new int[_scores.size()];<br />
_scores.copyInto(array);<br />
return array;<br />
}<br />
}</p>
</div>
<h2>Timer and TimerTask</h2>
<p>Like weak references, this next gem is also defined in CLDC but is mostly overlooked for its utility.  Suppose you want to perform background tasks in your application.  You can either use Application.invokeLater() or devise a grandiose background thread implementation that cleverly uses Java® synchronization primitives to efficiently perform background event dispatching.  The former consumes your application’s event thread, potentially causing UI lag, and the latter is just a lot of work.</p>
<p>I recommend whipping out Timer and TimerTask for background task processing.  Each Timer object has exactly one background thread which processes TimerTasks sequentially.  These tasks can be scheduled to occur immediately, after some delay, at a particular time, or repeatedly at a given interval.</p>
<p>The sample below shows how to use Timer and TimerTask to notify an object on a non-event thread about the user pressing the trackball.</p>
<div class="sample">
<p><code>public class MyScreen extends net.rim.device.api.ui.container.MainScreen {</code></p>
<p>private Timer _timer;</p>
<p>public MyScreen() {<br />
this.setTitle(&#8220;Timer Demo&#8221;);<br />
this._timer = new Timer();<br />
}</p>
<p>public void onTrackballClick() {<br />
System.out.println(&#8220;Quit pressing the trackball!&#8221;);<br />
}</p>
<p>protected boolean navigationClick(int status, int time) {<br />
this._timer.schedule(new ClickTask(), 0);<br />
return super.navigationClick(status, time);<br />
}</p>
<p>private class ClickTask extends TimerTask {<br />
public void run() {<br />
onTrackballClick();<br />
}<br />
}<br />
}</p>
</div>
<p>There are many more hidden gems in the BlackBerry® SDK but just not enough time here to share them all.  I will be doing a talk on this topic at the <a title="2009 BlackBerry Developer Conference" href="http://www.blackberrydeveloperconference.com/" target="_new">2009 BlackBerry Developer Conference</a> and plan to talk about some hidden gems not mentioned here as well as some lesser-known cool features of the JDE itself.  If you have found any hidden gems of your own please comment on this post to share your great discovery with the world!  I’d love to know which APIs you find useful.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/rimdevblog.wordpress.com/850/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/rimdevblog.wordpress.com/850/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=devblog.blackberry.com&#038;blog=17235680&#038;post=850&#038;subd=rimdevblog&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://devblog.blackberry.com/2009/08/blackberry-api-hidden-gems-part-two/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/035dc37bb725cb59d3b846aeb8a55c6c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">denvercon1</media:title>
		</media:content>

		<media:content url="http://rimdevblog.files.wordpress.com/2009/08/hidden-gems.jpg" medium="image">
			<media:title type="html">hidden gems</media:title>
		</media:content>
	</item>
		<item>
		<title>BlackBerry API Hidden Gems (Part One)</title>
		<link>http://devblog.blackberry.com/2009/08/blackberry-api-hidden-gems-part-one/</link>
		<comments>http://devblog.blackberry.com/2009/08/blackberry-api-hidden-gems-part-one/#comments</comments>
		<pubDate>Wed, 12 Aug 2009 12:27:00 +0000</pubDate>
		<dc:creator>Denver C.</dc:creator>
				<category><![CDATA[Java Development]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[weak-reference]]></category>

		<guid isPermaLink="false">http://devblog.blackberry.com/?p=836</guid>
		<description><![CDATA[Every time I think I know everything, I am always proven wrong.  For example, I used to think I knew everything about BlackBerry® APIs but as I continue developing software I am still finding new, cool classes and methods that make my life easier. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=devblog.blackberry.com&#038;blog=17235680&#038;post=836&#038;subd=rimdevblog&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p style="text-align:center;"><img class="aligncenter size-full wp-image-837" title="hidden gems" src="http://rimdevblog.files.wordpress.com/2009/08/hidden-gems.jpg?w=480&#038;h=360" alt="" width="480" height="360" /></p>
<p>Every time I think I know everything, I am always proven wrong.  For example, I used to think I knew everything about BlackBerry® APIs but as I continue developing software I am still finding new, cool classes and methods that make my life easier.  I call them “hidden gems” since they are often found by one stumbling across them, but when found are of great use.  In this post I will highlight some of my favourite gems, which I hope will make your life as a developer easier too.  So let’s dive in.</p>
<h2>Weak References</h2>
<p>For the longest time I had heard the term “weak references” but never really knew what they were.  Once I finally learned, I started to use them all the time to be more efficient and avoid memory leaks.  Indeed, weak references are not BlackBerry specific, but are defined right in the CLDC specification in the class java.lang.ref.WeakReference.</p>
<p>So what is a “weak reference” anyways?  The behaviour of a weak reference when contrasted with the normal “strong” reference pertains to making an object a candidate for garbage collection. A weak reference gives you the ability to access an object but also makes it available to the garbage collector.  So why would this be useful?  I find that there are often circumstances when you only care about an object if someone else does.  Holding a weak reference to an object is one way of determining if anyone else cares about it, based on the assumption that anyone who cares about it will hold a strong reference to it.  Once nobody cares about the object (other than me) it will be garbage collected.  This is the opposite of holding a strong reference to the object, as doing so would prevent the object from being garbage collected, wasting precious memory.</p>
<p>One excellent use case for weak references is holding a reference to an application object.  In general, you only need to reference an application object while the application it represents is alive; once the application exits you no longer need the reference. By holding a strong reference to the application object, the garbage collector will be prevented from freeing the object’s memory even after the application exits, along with the massive number of objects that it recursively references. Instead, holding a weak reference to the application object allows it to be garbage collected when the application exits.</p>
<p>Below is an example of how a weak reference to an application object can be used in a memory-efficient manner to determine if an application is still alive.</p>
<div class="sample"><code>import net.rim.device.api.system.Application;<br />
import java.lang.ref.WeakReference;</code></p>
<p>public class ApplicationLifeMonitor {</p>
<p>private WeakReference _appRef;</p>
<p>public ApplicationLifeMonitor() {<br />
Application app = Application.getApplication();<br />
_appRef = new WeakReference(app);<br />
}</p>
<p>public boolean isAlive() {<br />
Application app = (Application) _appRef.get();<br />
return (app != null &amp;&amp; app.isAlive());<br />
}<br />
}</p>
</div>
<h2>UIDGenerator</h2>
<p>The UIDGenerator class does exactly what its name implies: generates unique IDs.  Its class javadocs defines it as “a utility class to generate 32-bit unique IDs that can be used for synchronization or any other purpose.” Here’s an example to show how it could be used:</p>
<div class="sample">
<p><code>public class Person {</code></p>
<p>private int _id;<br />
private String _name;</p>
<p>public Person(String name) {<br />
this._id = UIDGenerator.getUID();<br />
this._name = name;<br />
}</p>
<p>public int getId() {<br />
return this._id;<br />
}</p>
<p>public String getName() {<br />
return this._name;<br />
}<br />
}</p>
</div>
<h2>IOUtilities.streamToBytes()</h2>
<p>Have you ever written code like this to dump the bytes from an InputStream into a byte[] array?</p>
<div class="sample"><code>public static byte[] getBytes(InputStream in)<br />
throws IOException {<br />
ByteArrayOutputStream out = new ByteArrayOutputStream();<br />
byte[] buffer = new byte[2048];<br />
int readCount = in.read(buffer);<br />
while (readCount &gt;= 0) {<br />
out.write(buffer, 0, readCount);<br />
readCount = in.read(buffer);<br />
}<br />
return out.toByteArray();<br />
}<br />
</code></div>
<p>Now you can do it in one line:</p>
<div class="sample"><code>public static byte[] getBytes(InputStream in)<br />
throws IOException {<br />
return net.rim.device.api.io.IOUtilities.streamToBytes(in);<br />
}<br />
</code></div>
<p>Impress your friends at your next party with this neat trick.</p>
<p>Stay tuned for <a href="http://rimdevblog.files.wordpress.com/2009/08/hidden-gems.jpg2009/08/blackberry-api-hidden-gems-part-two/">tomorrow&#8217;s post</a> when I&#8217;ll share even more BlackBerry API gems with you!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/rimdevblog.wordpress.com/836/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/rimdevblog.wordpress.com/836/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=devblog.blackberry.com&#038;blog=17235680&#038;post=836&#038;subd=rimdevblog&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://devblog.blackberry.com/2009/08/blackberry-api-hidden-gems-part-one/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/035dc37bb725cb59d3b846aeb8a55c6c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">denvercon1</media:title>
		</media:content>

		<media:content url="http://rimdevblog.files.wordpress.com/2009/08/hidden-gems.jpg" medium="image">
			<media:title type="html">hidden gems</media:title>
		</media:content>
	</item>
	</channel>
</rss>
