<?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/"
	>

<channel>
	<title>multithreading &#8211; Wiebe Elsinga</title>
	<atom:link href="http://wiebe-elsinga.com/blog/tag/multithreading/feed/" rel="self" type="application/rss+xml" />
	<link>http://wiebe-elsinga.com/blog</link>
	<description>Blog</description>
	<lastBuildDate>Mon, 18 Jul 2011 05:50:35 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.8.1</generator>
	<item>
		<title>Handlers and AsyncTasks, Android doing multithreading</title>
		<link>http://wiebe-elsinga.com/blog/handlers-and-asynctasks-android-doing-multithreading/</link>
					<comments>http://wiebe-elsinga.com/blog/handlers-and-asynctasks-android-doing-multithreading/#respond</comments>
		
		<dc:creator><![CDATA[W.Elsinga]]></dc:creator>
		<pubDate>Sun, 17 Jul 2011 22:50:35 +0000</pubDate>
				<category><![CDATA[Business]]></category>
		<category><![CDATA[Android]]></category>
		<category><![CDATA[AsyncTask]]></category>
		<category><![CDATA[Honeycomb]]></category>
		<category><![CDATA[multithreading]]></category>
		<category><![CDATA[NetworkOnMainThreadException]]></category>
		<guid isPermaLink="false">http://wiebe-elsinga.com/blog/?p=690</guid>

					<description><![CDATA[Multithreading is always tricky. On any platform and in any language, when not implemented properly you will get unexpected behavior sooner or later. In the process of making an Android application suitable for Honeycomb, a colleague of mine ran into the NetworkOnMainThreadException, which is new in Honeycomb. On earlier Android versions, doing heavy operations on the main thread was strongly discouraged, but still possible. Now, the OS is forcing the developer to implement a proper application structure. Which isn&#8217;t a bad thing at all. So, to solve the NetworkOnMainThreadException, network and other heavy operations needed to move to a background thread. Considering the structure of the application, the most logical choice was to use the Handler in combination with a Thread. Basic setup HandlerThread Here is an example: public class MBOutcomeHandlerThread extends Thread &#123; &#160; public MBOutcomeHandlerThread&#40;String name&#41; &#160; &#123; &#160; &#160; super&#40;name&#41;; &#160; &#125; &#160; private MBOutcomeHandler _outcomeHandler; &#160; @Override &#160; public void run&#40;&#41; &#160; &#123; &#160; &#160; try &#160; &#160; &#123; &#160; &#160; &#160; Looper.prepare&#40;&#41;; &#160; &#160; &#160; _outcomeHandler = new MBOutcomeHandler&#40;&#41;; &#160; &#160; &#160; Looper.loop&#40;&#41;; &#160; &#160; &#125; &#160; &#160; catch &#40;Throwable e&#41; &#160; &#160; &#123; &#160; &#160; &#160; Log.e&#40;&#34;Log&#34;, &#34;Thread stopped due to error&#34;, e&#41;; &#160; &#160; &#125; &#160; &#125; &#160; public MBOutcomeHandler getOutcomeHandler&#40;&#41; &#160; &#123; &#160; &#160; return _outcomeHandler; &#160; &#125; &#125; Looper.prepare creates a new Looper instance for this thread, which then creates a new MessageQueue that Handlers can use to post messages on. MBOutcomeHandler is a subclass of Handler, which implements the handleMessage method. The constructor of the Handler class associates with the Looper. Looper.loop starts the Looper and keeps the thread alive. The Looper can be stopped by invoking Looper.quit. This will end run method of the Thread, hence, the Thread is finished. It is also possible to use the HandlerThread class. This class does the Looper setup for you. It doesn&#8217;t really matter which one you choose, as long as you don&#8217;t forget to instantiate the Handler inside the run method. When using the HandlerThread you must instantiate the Handler in the onLooperPrepared method. public class MBOutcomeHandlerThread extends HandlerThread &#123; &#160; private MBOutcomeHandler _outcomeHandler; &#160; public MBOutcomeHandlerThread&#40;String name&#41; &#160; &#123; &#160; &#160; super&#40;name&#41;; &#160; &#125; &#160; @Override &#160; public void run&#40;&#41; &#160; &#123; &#160; &#160; super.run&#40;&#41;; &#160; &#160; _outcomeHandler = null; &#160; &#125; &#160; @Override &#160; protected void onLooperPrepared&#40;&#41; &#160; &#123; &#160; &#160; _outcomeHandler = new MBOutcomeHandler&#40;&#41;; &#160; &#125; &#160; public MBOutcomeHandler getOutcomeHandler&#40;&#41; &#160; &#123; &#160; &#160; return _outcomeHandler; &#160; &#125; &#125; Now that we have a HandlerThread running, we can use the Handler to send messages to the Looper. Please be aware, that the HandlerThread keeps looping until the quit method is invoked. It doesn&#8217;t really matter if you use the instance of the HandlerThread, the Handler or the Looper. After the quit method is invoked, the HandlerThread is finished and cannot be started again. For example, if the HandlerThread has been quit because the Activity was pushed to the background, you need to clean up the HandlerThread in an onPause or onStop. When the Activity comes to the foreground again, a new HandlerThread must be created. Of course, the starting and stopping of the HandlerThread depends on what kind of operations are performed in the Handler. Then again, I think it is good practice to do a little clean up, instead of Android doing all the work. AsyncTasks After the new Handler was created, the next problem occurred. After pushing the application to the background and let it come to the foreground again, the application crashed because of the following error: Handler{4062bc78} sending message to a Handler on a dead thread. Because I was implementing a Handler, I assumed the exception had something to do with the Handler I created. After a lot of searching and debugging, the cause of the exception were the AsyncTasks that are used inside the Handler. Then, after reading the documentation of AsyncTask, Android is very clear that AsyncTasks must be created and started on the UI thread. But, in the process of moving code to the handler, that was overlooked. After creating and starting the AsyncTasks, everything worked fine! Recap HandlerThreads and Handlers are a great way to handle heavy or long during operations on a separate thread. When using AsyncTasks in your Handler, make sure that they&#8217;re created on the UI thread.]]></description>
										<content:encoded><![CDATA[<p>Multithreading is always tricky. On any platform and in any language, when not implemented properly you will get unexpected behavior sooner or later.</p>
<p>In the process of making an Android application suitable for Honeycomb, a colleague of mine ran into the <em>NetworkOnMainThreadException</em>, which is new in Honeycomb. On earlier Android versions, doing heavy operations on the main thread was strongly discouraged, but still possible. Now, the OS is forcing the developer to implement a proper application structure. Which isn&#8217;t a bad thing at all.</p>
<p>So, to solve the <em>NetworkOnMainThreadException</em>, network and other heavy operations needed to move to a background thread. Considering the structure of the application, the most logical choice was to use the <em>Handler</em> in combination with a <em>Thread</em>.<br />
<span id="more-690"></span></p>
<h4>Basic setup <em>HandlerThread</em></h4>
<p>Here is an example:</p>
<div class="codecolorer-container java blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;height:100%;"><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MBOutcomeHandlerThread <span style="color: #000000; font-weight: bold;">extends</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Adocs.oracle.com+javase+docs+api+thread"><span style="color: #003399;">Thread</span></a><br />
<span style="color: #009900;">&#123;</span><br />
&nbsp; <span style="color: #000000; font-weight: bold;">public</span> MBOutcomeHandlerThread<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Adocs.oracle.com+javase+docs+api+string"><span style="color: #003399;">String</span></a> name<span style="color: #009900;">&#41;</span><br />
&nbsp; <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span>name<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><br />
<br />
&nbsp; <span style="color: #000000; font-weight: bold;">private</span> MBOutcomeHandler _outcomeHandler<span style="color: #339933;">;</span><br />
<br />
&nbsp; @Override<br />
&nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> run<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><br />
&nbsp; <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">try</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; Looper.<span style="color: #006633;">prepare</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<br />
&nbsp; &nbsp; &nbsp; _outcomeHandler <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MBOutcomeHandler<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<br />
&nbsp; &nbsp; &nbsp; Looper.<span style="color: #006633;">loop</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Adocs.oracle.com+javase+docs+api+throwable"><span style="color: #003399;">Throwable</span></a> e<span style="color: #009900;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; Log.<span style="color: #006633;">e</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Log&quot;</span>, <span style="color: #0000ff;">&quot;Thread stopped due to error&quot;</span>, e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><br />
<br />
&nbsp; <span style="color: #000000; font-weight: bold;">public</span> MBOutcomeHandler getOutcomeHandler<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><br />
&nbsp; <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">return</span> _outcomeHandler<span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span></div></div>
<p><strong><em>Looper.prepare</em></strong> creates a new Looper instance for this thread, which then creates a new <em>MessageQueue</em> that <em>Handlers</em> can use to post messages on.</p>
<p><em>MBOutcomeHandler</em> is a subclass of <em>Handler</em>, which implements the <strong><em>handleMessage</em></strong> method. The constructor of the <em>Handler</em> class associates with the Looper.</p>
<p><em>Looper.loop</em> starts the Looper and keeps the thread alive. The Looper can be stopped by invoking <strong><em>Looper.quit</em></strong>. This will end run method of the Thread, hence, the Thread is finished.</p>
<p>It is also possible to use the <em>HandlerThread</em> class. This class does the Looper setup for you. It doesn&#8217;t really matter which one you choose, as long as you don&#8217;t forget to instantiate the <em>Handler</em> inside the run method. When using the <em>HandlerThread</em> you must instantiate the <em>Handler</em> in the <strong><em>onLooperPrepared</em></strong> method.</p>
<div class="codecolorer-container java blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;height:100%;"><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MBOutcomeHandlerThread <span style="color: #000000; font-weight: bold;">extends</span> HandlerThread<br />
<span style="color: #009900;">&#123;</span><br />
&nbsp; <span style="color: #000000; font-weight: bold;">private</span> MBOutcomeHandler _outcomeHandler<span style="color: #339933;">;</span><br />
<br />
&nbsp; <span style="color: #000000; font-weight: bold;">public</span> MBOutcomeHandlerThread<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Adocs.oracle.com+javase+docs+api+string"><span style="color: #003399;">String</span></a> name<span style="color: #009900;">&#41;</span><br />
&nbsp; <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span>name<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><br />
<br />
&nbsp; @Override<br />
&nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> run<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><br />
&nbsp; <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006633;">run</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; _outcomeHandler <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><br />
<br />
&nbsp; @Override<br />
&nbsp; <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000066; font-weight: bold;">void</span> onLooperPrepared<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><br />
&nbsp; <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; _outcomeHandler <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MBOutcomeHandler<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><br />
<br />
&nbsp; <span style="color: #000000; font-weight: bold;">public</span> MBOutcomeHandler getOutcomeHandler<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><br />
&nbsp; <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">return</span> _outcomeHandler<span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span></div></div>
<p>Now that we have a <em>HandlerThread</em> running, we can use the <em>Handler</em> to send messages to the Looper.</p>
<p>Please be aware, that the <em>HandlerThread</em> keeps looping until the quit method is invoked. It doesn&#8217;t really matter if you use the instance of the <em>HandlerThread</em>, the <em>Handler</em> or the Looper. After the quit method is invoked, the <em>HandlerThread</em> is finished and cannot be started again. For example, if the <em>HandlerThread</em> has been quit because the Activity was pushed to the background, you need to clean up the <em>HandlerThread</em> in an <strong><em>onPause</em></strong> or <strong><em>onStop</em></strong>. When the Activity comes to the foreground again, a new <em>HandlerThread</em> must be created. Of course, the starting and stopping of the <em>HandlerThread</em> depends on what kind of operations are performed in the Handler. Then again, I think it is good practice to do a little clean up, instead of Android doing all the work.</p>
<h4>AsyncTasks</h4>
<p>After the new <em>Handler</em> was created, the next problem occurred. After pushing the application to the background and let it come to the foreground again, the application crashed because of the following error: <em>Handler{4062bc78}</em> sending message to a <em>Handler</em> on a dead thread. Because I was implementing a Handler, I assumed the exception had something to do with the Handler I created. After a lot of searching and debugging, the cause of the exception were the <em>AsyncTasks</em> that are used inside the Handler. Then, after reading the documentation of <em>AsyncTask</em>, Android is very clear that <em>AsyncTasks</em> must be created and started on the UI thread. But, in the process of moving code to the handler, that was overlooked. After creating and starting the <em>AsyncTasks</em>, everything worked fine!</p>
<h4>Recap</h4>
<p><em>HandlerThreads</em> and <em>Handlers</em> are a great way to handle heavy or long during operations on a separate thread. When using <em>AsyncTasks</em> in your Handler, make sure that they&#8217;re created on the UI thread. </p>
]]></content:encoded>
					
					<wfw:commentRss>http://wiebe-elsinga.com/blog/handlers-and-asynctasks-android-doing-multithreading/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
