<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><title>JavaBeat</title><link>http://www.javabeat.net</link><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/JavabeatArticles" /><description>Java Technology News</description><language>en-US</language><lastBuildDate>Mon, 13 May 2013 13:10:23 PDT</lastBuildDate><generator>http://wordpress.org/?v=3.5.1</generator><sy:updatePeriod xmlns:sy="http://purl.org/rss/1.0/modules/syndication/">hourly</sy:updatePeriod><sy:updateFrequency xmlns:sy="http://purl.org/rss/1.0/modules/syndication/">1</sy:updateFrequency><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/JavabeatArticles" /><feedburner:info uri="javabeatarticles" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId>JavabeatArticles</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item><title>What is StrictMode in Android? – Part 2</title><link>http://feedproxy.google.com/~r/JavabeatArticles/~3/MT1WT0OW-js/</link><category>Google Android</category><category>Android</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">krishnas</dc:creator><pubDate>Mon, 13 May 2013 13:10:23 PDT</pubDate><guid isPermaLink="false">http://www.javabeat.net/?p=7175</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In our previous post <a href="http://techbreaths.com/2013/02/strictmode-in-android/">StrictMode Part 1</a>  we had discussed how to set up StrictMode in development environment and how to run your application with <strong>StrictMode</strong> enabled on emulator. In this tutorial we would be discussing more about dealing with StrictMode. The main topics that we are going to discuss are,</p>
<ol>
<li>Turning off StrictMode When your application goes to production</li>
<li>StrictMode with older versions of Android(prior to Android 2.3)</li>
</ol>
<ul>
<li>Buy: <a href="http://www.flipkart.com/hello-android-9350232927/p/itmdf86bfgupeddu?pid=9789350232927&amp;affid=suthukrish" target="_blank">Hello, Android!!</a></li>
</ul>
<h2>Turning off StrictMode for Production purpose</h2>
<p>I hope by now you have enough basic knowledge about what is StrictMode, how to enable it, and how to use it in production. Now we will discuss how to disable it when your application is ready to go on live failing which your application will crash on your users because of an alert. Below are the two ways by which you can disable StrictMode.</p>
<ul>
<li> Comment out or Remove the StrictMode code when your application finishes its building, testing and debugging stage.</li>
<li>You can use production flags to skip the StrictMode setup code when it is not needed.</li>
</ul>
<p>If you start commenting out the StrictMode code, it would be difficult for you to continue development if anything else is left out in development. Hence the second approach to turnoff the StrictMode during production is better to use. This is done by simply declaring any flag and assigning it a boolean variable &#8220;true&#8221; in debugging mode and making it false once you are done with the development. You can make use of android:debuggable attribute that is present in AndroidManifest.xml for &lt;application&gt; Tag. Developer no longer need to add the android:debuggable attribute to the &lt;application&gt; tag in the manifest. The build tools add the attribute automatically. When exporting a signed release build, the tools do not add the attribute in the manifest. So it is enough for you to check whether android:debuggable attribute is true or false while setting up StrictMode.</p>
<p>Use the below code to check for debug mode,</p>
<pre class="brush: java; title: ; notranslate">

// collects information from &lt;application&gt; tag
ApplicationInfo appInformation =context.getApplicationInfo();

//gives Flags associated with the application
int appFlags = appInformation.flags;

//Checks whether the application would like to allow debugging of its code
if ((appFlags &amp; ApplicationInfo.FLAG_DEBUGGABLE) != 0)
{
// StrictMode setup goes here
}</pre>
<p>Above code checks for debug mode and performs the StrictMode set up accordingly.</p>
<h2>StrictMode with older versions of Android(prior Android 2.3)</h2>
<p>Lets assume we have an application targetting android 4.0(API 14) and minimum SDK version set to Android 2.2(API 8). I have made StrictMode enabled by using setThreadPolicy() and setVmPolicy() static methods. Now if you test your application on emulator of android 2.2(API 8), your application crashes by displaying ANR dialog. This is because StrictMode is not available in versions below Android 2.3. But your application works fine on Android 4.0 supporting emulators.<br />
Lets see how can we get rid of this particular problem.</p>
<p>Create a separate method to deal with the older versions of Android( prior to Android 2.3) as below</p>
<pre class="brush: java; title: ; notranslate">try {
//checks whether the strictMode class exists or what
Class class_obj = Class.forName(&quot;android.os.StrictMode&quot;);

//if the StrictMode class exists, the control comes here
Method enableDefaults = class_obj.getMethod(&quot;enableDefaults&quot;);

//dynamically invokes enableDefaults method which sets up StrictMode
enableDefaults.invoke(null);
}
catch(Exception e) {
// StrictMode not supported...
Log.v(&quot;STRICTMODE&quot;, &quot; Lower version of android, StrictMode not supported&quot;);
}</pre>
<p>As you can see in the above code, first you are checking whether android.os.StrictMode class is available or not. If it&#8217;s not, a ClassNotFoundException occurs which is caught by the catch block and we are writing a LogCat message by using Log class. You shouldn’t get any exceptions if StrictMode does exist, because enableDefaults() is one of its methods.The enableDefaults() method sets up StrictMode to detect everything and to write any violations to LogCat. If you run your application with this set up, on emulator supporting versions below Android 2.3, you get an Message logged in Logcat by your catch block and if you run on emulators supporting Android 2.3 and above, you will be alerted when you perform non-recommended things.</p>
<p>Another approach to deal with older versions of Android is using StrictMode wrapper class. This enables you to work with Higher and lower versions of Android while using StrictMode. If StrictMode is not available for your application, an<br />
Error will be thrown if you try to access it. If you wrap StrictMode in a class and then catch the error, you can ignore when StrictMode is not available and get it when it is.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Lets us change the sample example that we have developed in our earlier post <a href="http://StrictMode Part 1 in Android">StrictMode Part 1</a>. Add a StrictMode wrapper class to the project StrictModeTest by creating a class named StrictModeWrapper.java in the package my.app . the code of the StrictModeWrapper.java is as below.</p>
<pre class="brush: java; title: ; notranslate">

package my.app;

import android.content.Context;
import android.os.StrictMode;

public class StrictModeWrapper {

public static void enableStrictMode(Context context) {
StrictMode.setThreadPolicy(
new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.build());
StrictMode.setVmPolicy(
new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.penaltyLog()
.build());
}
}</pre>
<p>In the above code I have simply wrapped up the code of StrictMode set up that we have discussed in our earlier post, inside a enableStrictMode() static method.</p>
<p>Change the StrictModeTestActivity.java code to the below code.</p>
<pre class="brush: java; title: ; notranslate">

package my.app;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

public class StrictModeTestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
Context context=StrictModeTestActivity.this;
//check whether debug mode is available
int applicationflags = context.getApplicationInfo().flags;
if ((applicationflags &amp; ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
//check whether the Android version is &gt;= 2.3.. if yes set up StrictMode by calling enableStrictMode() of wrapper class.
if (Build.VERSION.SDK_INT&gt;=Build.VERSION_CODES.GINGERBREAD) {
StrictModeWrapper.enableStrictMode(this);
}
else{
//If the android version is less than 2.3 log a message to LogCat
Log.v(&quot;VERSION &lt; Android 2.3&quot;, &quot;StrictMode not supported&quot;);
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

//Code to perform FILE I/O which will be caught by StrictMode
try {
OutputStreamWriter output_writer= new OutputStreamWriter(openFileOutput(&quot;FILETEST&quot;, MODE_WORLD_WRITEABLE));
BufferedWriter writer = new BufferedWriter(output_writer);
writer.write(&quot;Hi This is my File to test StrictMode&quot;);
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}</pre>
<p>In the above code we are just checking whether the SDK version is Android 2.3 or higher. If yes we would be calling enableStrictMode() method of the wrapper class, which sets up StrictMode. If your version is lesser tha Android 2.3 you are logging a error message to the LogCat.</p>
<p>Run your application on emulator supporting Android 4.0, you would get the below LogCat message while your Program runs well.</p>
<pre class="brush: java; title: ; notranslate">02-15 16:25:04.665: D/StrictMode(929): StrictMode policy violation; ~duration=47 ms: android.os.StrictMode$StrictModeDiskWriteViolation: policy=49 violation=1
02-15 16:25:04.665: D/StrictMode(929):  at android.os.StrictMode$AndroidBlockGuardPolicy.onWriteToDisk(StrictMode.java:1048)
02-15 16:25:04.665: D/StrictMode(929):  at libcore.io.BlockGuardOs.write(BlockGuardOs.java:178)
02-15 16:25:04.665: D/StrictMode(929):  at libcore.io.IoBridge.write(IoBridge.java:447)
02-15 16:25:04.665: D/StrictMode(929):  at java.io.FileOutputStream.write(FileOutputStream.java:187)
02-15 16:25:04.665: D/StrictMode(929):  at java.io.OutputStreamWriter.flushBytes(OutputStreamWriter.java:167)
02-15 16:25:04.665: D/StrictMode(929):  at java.io.OutputStreamWriter.close(OutputStreamWriter.java:140)
02-15 16:25:04.665: D/StrictMode(929):  at java.io.BufferedWriter.close(BufferedWriter.java:98)
02-15 16:25:04.665: D/StrictMode(929):  at my.app.StrictModeTestActivity.onCreate(StrictModeTestActivity.java:35)</pre>
<p>Now run your application on emulator supporting Android 2.3 and see the LogCat entries. A log is being entered in LogCat where as the program runs well.</p>
<pre class="brush: java; title: ; notranslate">02-15 18:16:21.905: V/VERSION &lt; Android 2.3(386): StrictMode not supported</pre>
<p>This is how you can make your code run on all versions of Android with StrictMode enabled. Hope this tutorial helped you to work with StrictMode. If you have any queries, please post it in comments section.</p>
<ul>
<li>Buy: <a href="http://www.flipkart.com/hello-android-9350232927/p/itmdf86bfgupeddu?pid=9789350232927&amp;affid=suthukrish" target="_blank">Hello, Android!!</a></li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=MT1WT0OW-js:9WaE2TNFyZQ:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=MT1WT0OW-js:9WaE2TNFyZQ:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=MT1WT0OW-js:9WaE2TNFyZQ:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=MT1WT0OW-js:9WaE2TNFyZQ:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=MT1WT0OW-js:9WaE2TNFyZQ:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=MT1WT0OW-js:9WaE2TNFyZQ:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=MT1WT0OW-js:9WaE2TNFyZQ:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=MT1WT0OW-js:9WaE2TNFyZQ:l6gmwiTKsz0"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=l6gmwiTKsz0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=MT1WT0OW-js:9WaE2TNFyZQ:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=MT1WT0OW-js:9WaE2TNFyZQ:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/JavabeatArticles/~4/MT1WT0OW-js" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;Connect to us ( &lt;a href="https://twitter.com/javabeat"&gt;@twitter&lt;/a&gt; | &lt;a href="https://www.facebook.com/javabeat.net"&gt;@facebook )&lt;/p&gt;&lt;p&gt;In our previous post StrictMode Part 1  we had discussed how to set up StrictMode in development environment and how to run your application with StrictMode enabled on emulator. In this tutorial we would be discussing more about dealing with StrictMode. The main topics that we are going to discuss are, Turning off StrictMode When your [...]&lt;/p&gt;</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.javabeat.net/2013/05/strictmode-android-2/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">0</slash:comments><feedburner:origLink>http://www.javabeat.net/2013/05/strictmode-android-2/</feedburner:origLink></item><item><title>What is StrictMode in Android? – Part 1</title><link>http://feedproxy.google.com/~r/JavabeatArticles/~3/VCSRYQAoAvQ/</link><category>Google Android</category><category>Android</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">krishnas</dc:creator><pubDate>Sun, 12 May 2013 13:10:17 PDT</pubDate><guid isPermaLink="false">http://www.javabeat.net/?p=7174</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><strong>StrictMode</strong> is a special class for verifying that your Android application is not doing things like disk I/O, Network access from the UI thread. This is a debugging feature introduced in Android 2.3. This developer tool detect things done accidentally and bring them to your attention so that you can fix them so as to avoid ANR dialogs(Activity Not Responding dialogs). <strong>StrictMode</strong> is used to setup thread and virtual machine policies for your application and report violations of such policies. You will get an alert if a policy is violated. You can instruct Android to crash your application with the alert or you can just log the alert and let your application carry on.</p>
<ul>
<li>Buy: <a href="http://www.flipkart.com/hello-android-9350232927/p/itmdf86bfgupeddu?pid=9789350232927&amp;affid=suthukrish" target="_blank">Hello, Android!!</a></li>
</ul>
<h2>StrictMode Policies</h2>
<p>Currently there are two types of policies available with StrictMode.</p>
<ul>
<li>Thread Policy.</li>
<li>VM(Virtual Machine) policy.</li>
</ul>
<h2>ThreadPolicy of StrictMode</h2>
<p>Thread policies are concerned with the non-recommended things that are done on the main application thread(UI thread), notably flash I/O and Network I/O.</p>
<p>Violations you can look for using ThreadPolicy are,</p>
<ul>
<li>Disk reads</li>
<li>Disk writes</li>
<li>Network accesss</li>
<li>Slow calls</li>
</ul>
<p>The possible alerts that you can choose are,</p>
<ul>
<li>Write to LogCat</li>
<li>Display a dialog</li>
<li>Flash the screen</li>
<li>write to the DropBox log file</li>
<li>Crash the application</li>
</ul>
<h2>Setting up StrictMode&#8217;s ThreadPolicy</h2>
<p>The below code tells you how to set up StrictMode for thread policies,</p>
<pre class="brush: java; title: ; notranslate">StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskWrites()
.penaltyLog() //Logs a message to LogCat
.build());</pre>
<p>A good place to set policies is at the entry points to your application and activities. For instance, in a simple application, you may need to just put the code in the onCreate() method of the launch Activity class. setThreadPolicy is a static method so you don’t need to actually instantiate a StrictMode object. setThreadPolicy() method internally uses current thread for policy. The method bulid() returns a ThreadPolicy object. In the above code snippet, the policy is defined to alert on disk writes by logging the messages to LogCat. There are various detect and penalty methods available for ThreadPolicy which are listed below.</p>
<p>The various detect methods for Thread Policy are,</p>
<pre class="brush: java; title: ; notranslate">detectDiskWrites() //API level 9
detectDiskReads() //API level 9
detectNetwork() //API level 9
detectCustomSlowCalls()//Introduced in API level 11</pre>
<p>Instead of specific detect methods you can use detectAll() which detects all possible violations. detectCustomSlowCalls() is available from API level 11 using which you can detect slow code in your application.</p>
<p>The possible alerts(penalties) for thread policy are,</p>
<pre class="brush: java; title: ; notranslate">penaltyLog() //Logs a message to LogCat
penaltyDeath() //Crashes application, runs at the end of all enabled penalties
penaltyDialog() //Show a dialog
penaltyDeathOnNetwork() //Crashes the whole process on any network usage
penaltyDropBox() //Enable detected violations log a stacktrace and timing data to the DropBox on policy violation
penaltyFlashScreen() //Introduced in API level 11 which Flash the screen during a violation</pre>
<p>The above is the list of penalty methods available for ThreadPolicy. You can use two or more penalties while setting up the ThreadPolicy which will be executed based on priority. For example, you can make your system to Log your messages via penaltyLog() before crashing the process via penaltyDeath(). If no penalties are enabled before calling build, penaltyLog() is implicitly set.</p>
<h2>VmPolicy of StrictMode</h2>
<p>VM policy deals with bad coding practices resulting memory leaks like Detect leaks of Activity subclasses. Detects when SQLite object is finalized without having been closed or if any Closeable object is finalized before it has been closed. It is created via the same builder class as shown below.</p>
<pre class="brush: java; title: ; notranslate">StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectActivityLeaks()
.detectLeakedClosableObjects()
.penaltyLog()
.build());</pre>
<p>The possible policy violations for VmPolicy are,</p>
<pre class="brush: java; title: ; notranslate">detectActivityLeaks() //API level 11. Detect leaks of Activity subclasses.
detectLeakedClosableObjects() //API level 11. Detect when an Closeable or other object with a explict termination method is finalized without having been closed.
detectLeakedSqlLiteObjects() //API level 9. Detect when an SQLiteCursor or other SQLite object is finalized without having been closed.
setClassInstanceLimit(Class.forName(&quot;my.app.sample.sampleclass&quot;),10) //API level 11</pre>
<p>setClassInstanceLimit(className, Limit) is introduced in API level 11 which Sets an upper bound on how many instances of a class can be in memory at once. Helps to prevent object leaks.</p>
<p>The penalties that are applicable for VmPolicy Violations are,</p>
<pre class="brush: java; title: ; notranslate">
penaltyLog()
penaltyDeath()
penaltyDropBox()</pre>
<p>Note most of the Penalties that I have listed for ThreadPolicy are not application for VmPolicy. For example, you cannot be alerted by showing a dialog if a VmPolicy is violated.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>If you find any problematic violations, you can solve them using various approaches like <a title="Threads and Handlers in Android" href="http://techbreaths.com/2013/02/threads-and-handlers-in-android/">threads and handlers</a> , <a title="AsyncTask in android" href="http://techbreaths.com/2013/02/asynctask-in-android/">AsyncTask</a>  atc. Don&#8217;t try to solve all violations that your StrictMode detects. For example, Sometimes the disk I/O is necessary in your activities Lifecycle. In such cases you have to temporarily allow your Activity to access the DISK.  Android provides some helper methods to make it easier to allow disk reads and writes from the main thread temporarily. Such helper methods are,</p>
<ul>
<li>allowThreadDiskReads()</li>
<li>allowThreadDiskWrites()</li>
</ul>
<p>allowThreadDiskWrites() permits both disk reads &amp; writes. Whereas allowThreadDiskReads() permits only disk read. Use the below code to allow disk access.</p>
<pre class="brush: java; title: ; notranslate">StrictMode.ThreadPolicy myoldpolicy=StrictMode.allowThreadDiskWrites();
//The code to write the DISK goes here
StrictMode.setThreadPolicy(myoldpolicy);</pre>
<p>In the above code snippet,on line number 1 allowThreadDiskWrites() takes the current StrictMode.ThreadPolicy from getThreadPolic(), modifies it to permit both disk reads &amp; writes, and sets the new policy with setThreadPolicy(StrictMode.ThreadPolicy), returning the old policy. Now &#8220;myoldpolicy&#8221; has the old StrictMode thread policy which is used to set the old policy again on line numer 3 after performing the nececcary Disk I/O. Note that There is no method for temporarily allowing network access.</p>
<p>So far we have learnt how to set up StrictMode for your application. Let us now study how to run your application with StrictMode. For that let us create a sample application, which has StrictMode enabled in it.</p>
<h3>Step 1: Set up an Android working environment</h3>
<p>If you are not familiar with setting up working environment for android, please follow the post <a title="How to set up android development environment?" href="http://techbreaths.com/2012/12/setting-environment-android-app/">Environment</a>. For this example I would be using Android 4.0( API level 14).</p>
<h3>Step 2: Create an Android Project</h3>
<p>Create an android project named StrictModeTest with launcher activity StrictModeTestActivity. If you are not familiar with creating android projects, please follow one of our earlier posts <a title="How to write a simple Android application?" href="http://techbreaths.com/2012/12/creating-simple-android-app/">Create a simple project</a>.</p>
<h3>Step 3: Create the required layouts</h3>
<p>In this example, We would be using main.xml layout file. If you want to know more about layout files, please refer to the post <a title="How to create a Layout xml file in Android?" href="http://techbreaths.com/2012/12/how-create-layout-xml-file-android/">Layouts in android</a>. You need not to alter your main.xml file code for this example.</p>
<h3>Step 4: Create required Activities</h3>
<p>In this example, we would be using launcher activity StrictModeTestActivity.java. Open this and paste the below code,</p>
<pre class="brush: java; title: ; notranslate">

package my.app;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;

public class StrictModeTestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

//setThreadPolicy is a static method
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskWrites()
.penaltyLog() //Logs a message to LogCat
.penaltyDialog() //Shows a dialog
.build());

//VmPolicy
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectActivityLeaks()
.detectLeakedClosableObjects()
.penaltyLog()
.build());

super.onCreate(savedInstanceState);
setContentView(R.layout.main);

//Code to perform FILE I/O which will be caught by StrictMode
try {
OutputStreamWriter output_writer= new OutputStreamWriter(openFileOutput(&quot;FILETEST&quot;, MODE_WORLD_WRITEABLE));
BufferedWriter writer = new BufferedWriter(output_writer);
writer.write(&quot;Hi This is my File to test StrictMode&quot;);
writer.close();
} catch (Exception e) {
e.printStackTrace();
}

}
}

</pre>
<p>Now you are done with setting up StrictMode for DiskWrites. In the above example you are trying to read and write the file. Hence you would be alerted by LogCat messages and via dialogs.</p>
<h3>Step 4: Run your application</h3>
<p>Select your project-&gt; right click-&gt; Run As-&gt; Android Application</p>
<p>Now the Activity fires up with the Dialog which alerts saying, you are violating the StrictMode policies.</p>
<p><a href="http://techbreaths.com/wp-content/uploads/2013/02/StrictMode2.png"><img class="aligncenter size-full wp-image-1032" alt="StrictMode2" src="http://techbreaths.com/wp-content/uploads/2013/02/StrictMode2.png" width="337" height="497" /></a></p>
<p>StrictMode is warning us that we are attempting  FILE write on application&#8217;s main thread. The same is being logged in LogCat since we have specified penaltyLog(). The LogCat stackTrace is as below.</p>
<pre class="brush: java; title: ; notranslate">02-14 19:08:57.419: D/StrictMode(30397): StrictMode policy violation; ~duration=29 ms: android.os.StrictMode$StrictModeDiskWriteViolation: policy=49 violation=1
02-14 19:08:57.419: D/StrictMode(30397):  at android.os.StrictMode$AndroidBlockGuardPolicy.onWriteToDisk(StrictMode.java:1048)
02-14 19:08:57.419: D/StrictMode(30397):  at libcore.io.BlockGuardOs.write(BlockGuardOs.java:178)
02-14 19:08:57.419: D/StrictMode(30397):  at libcore.io.IoBridge.write(IoBridge.java:447)
02-14 19:08:57.419: D/StrictMode(30397):  at java.io.FileOutputStream.write(FileOutputStream.java:187)
02-14 19:08:57.419: D/StrictMode(30397):  at java.io.OutputStreamWriter.flushBytes(OutputStreamWriter.java:167)
02-14 19:08:57.419: D/StrictMode(30397):  at java.io.OutputStreamWriter.close(OutputStreamWriter.java:140)
02-14 19:08:57.419: D/StrictMode(30397):  at java.io.BufferedWriter.close(BufferedWriter.java:98)
02-14 19:08:57.419: D/StrictMode(30397):  at my.app.StrictModeTestActivity.onCreate(StrictModeTestActivity.java:34)</pre>
<p>You can observe the above LogCat messages, on Line number 1 it is saying the StrictMode policy is violated.</p>
<p>Note:  Do not use StrictMode in production code. It is designed for use when you are building,<br />
testing, and debugging your application.</p>
<ul>
<li>Buy: <a href="http://www.flipkart.com/hello-android-9350232927/p/itmdf86bfgupeddu?pid=9789350232927&amp;affid=suthukrish" target="_blank">Hello, Android!!</a></li>
</ul>
<p>StrictMode was introduced in <strong>Android 2.3</strong>(API level 9) but more features were added in Android 3.0, so it is your duty to target the correct Android version and make sure your code is executed on the appropriate platforms. <strong>StrictMode</strong> is for android 2.3 and higher versions of android. Hence if in our application, the target API is 2.3 or higher and the MinSDK is below 9, this may crash your applications while testing on lower version emulator or devices.  We would be discussing how to support StrictMode in lower versions of android in our upcoming post <a href="http://techbreaths.com/2013/02/strictmode-2-in-android/">StrictMode Part 2</a> . Stay Tuned. Hope this tutorial helped you to understand the usage of StrictMode. Please don&#8217;t forget to post your queries in comments section.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=VCSRYQAoAvQ:OWgehVJdFGg:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=VCSRYQAoAvQ:OWgehVJdFGg:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=VCSRYQAoAvQ:OWgehVJdFGg:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=VCSRYQAoAvQ:OWgehVJdFGg:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=VCSRYQAoAvQ:OWgehVJdFGg:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=VCSRYQAoAvQ:OWgehVJdFGg:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=VCSRYQAoAvQ:OWgehVJdFGg:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=VCSRYQAoAvQ:OWgehVJdFGg:l6gmwiTKsz0"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=l6gmwiTKsz0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=VCSRYQAoAvQ:OWgehVJdFGg:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=VCSRYQAoAvQ:OWgehVJdFGg:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/JavabeatArticles/~4/VCSRYQAoAvQ" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;Connect to us ( &lt;a href="https://twitter.com/javabeat"&gt;@twitter&lt;/a&gt; | &lt;a href="https://www.facebook.com/javabeat.net"&gt;@facebook )&lt;/p&gt;&lt;p&gt;StrictMode is a special class for verifying that your Android application is not doing things like disk I/O, Network access from the UI thread. This is a debugging feature introduced in Android 2.3. This developer tool detect things done accidentally and bring them to your attention so that you can fix them so as to avoid [...]&lt;/p&gt;</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.javabeat.net/2013/05/strictmode-android-1/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">0</slash:comments><feedburner:origLink>http://www.javabeat.net/2013/05/strictmode-android-1/</feedburner:origLink></item><item><title>AsyncTask in Android</title><link>http://feedproxy.google.com/~r/JavabeatArticles/~3/XHsV-melh0w/</link><category>Google Android</category><category>Android</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">krishnas</dc:creator><pubDate>Sat, 11 May 2013 13:06:20 PDT</pubDate><guid isPermaLink="false">http://www.javabeat.net/?p=7172</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><strong>AsyncTask is</strong> an Helper class that allows you to perform background operations and updating the UI when the task completes. After the execution of the Background task, the results are published on the UI thread. It is ideal for running short operations that spans for few seconds. It serves better when compared to Threads and handlers since it enables proper and easy use of the UI thread.</p>
<ul>
<li>Buy: <a href="http://www.flipkart.com/hello-android-9350232927/p/itmdf86bfgupeddu?pid=9789350232927&amp;affid=suthukrish" target="_blank">Hello, Android!!</a></li>
</ul>
<p>The <strong>AsyncTask</strong> class encapsulates the creation of Threads and Handlers. When an <strong>AsyncTask</strong> is created, it goes through 4 steps,</p>
<ul>
<li>onPreExecute()</li>
<li>doInBackground(Params&#8230;)</li>
<li>onProgressUpdates(Progress&#8230;)</li>
<li>onPostExecute(Result)</li>
</ul>
<p>The method doInBackgroung() executes automatically on a worker thread. The rest of the methods onPreExecute(), onPostExecute(), and onProgressUpdate() are all invoked on the UI thread. The value returned from the doInBackground() is sent to the onPostExecute() method. onProgressUpdate() method is executed by calling publishProgress() in doInBackground(). Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params&#8230;), onProgressUpdate(Progress&#8230;) manually. Overriding onPreExecute(), onPostExecute(Result), onProgressUpdate(Progress&#8230;) is optional.</p>
<p>AsyncTask is defined by three generic types Params, Progress, Result,</p>
<pre class="brush: java; title: ; notranslate">class AsyncDemo extends AsyncTask&lt;Params, Progress, Result&gt; { ... } </pre>
<ul>
<li>Params<br />
It is the type of the parameters passed in to the doInBackground.</li>
<li>Progress<br />
It is the type of the progress units published during the backgroung computation. These are passed in to the onProgressUpdate.</li>
<li>Result<br />
It is the return type of doInBackground and argument type passed in to onPostExecute.</li>
</ul>
<p>An AsyncTask must be subclassed to be used as below,</p>
<pre class="brush: java; title: ; notranslate">

private class AsyncDemo extends AsyncTask&lt;String, String, String&gt;{

@Override
protected void onPreExecute() {
// keeps the user informed about the long running tasks example by showing progressbar etc.
super.onPreExecute();
}

@Override
protected String doInBackground(String... params) {
// The code of long running tasks goes here
return null;
}

@Override
protected void onProgressUpdate(String... values) {
//when the long running tasks is in progress, the code to update the progress example updating the progress bar
super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(String result) {
//once the background work is done with execution, update the UI...
super.onPostExecute(result);
}
}</pre>
<p>The above snippet shows how you can create An AsyncTask for your operations. Once created, the Task is executed using the below line,</p>
<pre class="brush: java; title: ; notranslate">new AsyncDemo().execute();</pre>
<p>While calling execute() method, pass the parameters which your AsyncTask is using.</p>
<h3>Working of an AsyncTask</h3>
<p>When an AsyncTask is executed by calling execute() method, it goes through 4 steps as stated above,</p>
<ol>
<li> It first goes to onPreExecute() method, which is used to setup the Task. This can be used to keep the user informed about the Task that executes in background by showing a progressdialog.</li>
<li>Then the control goes to doInBackground() method where the expensive work takes place. This is invoked immediately after onPreExecute() finishes executing. The parameters of the AsyncTask are passed(if any) to this method. The results are returned and are passed to the onPostExecute() method which processess the result and updates the UI accordingly if necessary.</li>
<li>publishProgress(Progress&#8230;) can be called inside doInBackground() method which in turn calls the onProgressUpdate(Progress&#8230;) to publish one or more units of progress.</li>
<li>After the backgroud task finishes its computation, onPostExecute(Result) is invoked. The Result of the background computation is passed as parameter to this step from the doInBackground(Params&#8230;) step. onPostExecute(Result) updates the UI(Example: Cancelling the ProgressDialog etc);</li>
</ol>
<p>Let us now look at a simple example on how to execute long running tasks using AsyncTask</p>
<p>Working of the below AsyncTask example</p>
<p>In this example we would be displaying numbers in regular intervals of time forming a counterdown timer. The number of numerics to count is obtained from the user using an EditText. When the user clicks on a button called &#8220;Count&#8221;, the textview in the layout file starts showing numbers from 1 to any numeric specied by the user.(say 1 to 10 if your input is 10). When the numeric say 10 is displayed, the countdown stops and displays a message &#8220;Your countDown timer has stopped&#8221;.</p>
<p>Follow the below steps to create the example,</p>
<h3>Step 1: Set up an android working environment</h3>
<p>If you are not familiar with setting up the android environment, please refer to one of our earliar post, <a title="How to set up android development environment?" href="http://techbreaths.com/2012/12/setting-environment-android-app/">Environment</a>. I would be using Android2.2 for this example.</p>
<h3>Step 2 : Create an android project</h3>
<p>Create a project named &#8220;AsyncTaskDemo&#8221; with the activity &#8220;ActivityAsyncTask&#8221;. If you are not familiar with creation of android project, please refer the post <a title="How to write a simple Android application?" href="http://techbreaths.com/2012/12/creating-simple-android-app/">Create an Android project</a>.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h3>step 3: Create a layout</h3>
<p>When you create your project, the layout main.xml gets created automatically. Here in this example we are going to use this main.xml layout file. Open your main.xml and paste the below code.</p>
<pre class="brush: java; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;RelativeLayout android:id=&quot;@+id/RelativeLayout01&quot;
android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;fill_parent&quot;
xmlns:android=&quot;&lt;a href=&quot;http://schemas.android.com/apk/res/android&quot;&gt;http://schemas.android.com/apk/res/android&lt;/a&gt;&quot;&gt;
&lt;EditText android:id=&quot;@+id/EditText01&quot; android:layout_height=&quot;wrap_content&quot;
android:layout_width=&quot;90dip&quot;&gt;&lt;/EditText&gt;
&lt;Button android:id=&quot;@+id/Button01&quot; android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot; android:layout_toRightOf=&quot;@+id/EditText01&quot;
android:text=&quot;Count&quot;&gt;&lt;/Button&gt;
&lt;TextView android:id=&quot;@+id/TextView01&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot; android:layout_centerInParent=&quot;true&quot; android:textStyle=&quot;bold&quot; android:textSize=&quot;18sp&quot;&gt;&lt;/TextView&gt;
&lt;/RelativeLayout&gt;</pre>
<h3>Step 4: Create the required Activities</h3>
<p>Here in this example I would be using the launcher activity ActivityAsyncTask.java. Open this activity and paste the below code,</p>
<pre class="brush: java; title: ; notranslate">

package my.app;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ActivityAsyncTask extends Activity {
EditText input_time;
TextView count_textview;
Button start_count;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

start_count=(Button)findViewById(R.id.Button01);
count_textview=(TextView)findViewById(R.id.TextView01);
input_time=(EditText)findViewById(R.id.EditText01);

start_count.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//taking the input from the edittext
String input_number=input_time.getText().toString();
Integer input_time_int=Integer.parseInt(input_number);

//Starting CountDownStarterTask task by passing the parameter
new CountDownStarterTask().execute(input_time_int);
}
});
}

private class CountDownStarterTask extends AsyncTask&lt;Integer, Integer, Void&gt;{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
@Override
protected Void doInBackground(Integer... params) {
// TODO Auto-generated method stub
for(int i=1;i&lt;=params[0].intValue();i++){
try {

//calls onProgressUpdate to publish the progress
publishProgress(i);
Thread.sleep(1000);

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);

Integer time_to_set=values[0].intValue();
count_textview.setText(time_to_set.toString());
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
count_textview.setText(&quot;Your countDown timer has stopped&quot;);
}
}
}</pre>
<p>As you can observe in the above code, we have an Edittext which collects the user input. You have to enter a numeric input and click on &#8220;Count&#8221; button. Which starts counting number from 1 to max number that you have given as input.</p>
<h3>Step 5: Declaring the Activities in Android Manifest file</h3>
<p>Your launcher activity is declared automatically. If you want to know more about android Manifest xml file, please refer to the post <a title="How to write AndroidManifest.xml?" href="http://techbreaths.com/2012/12/androidmanifest-xml/">AndroidManifest.xml</a>.</p>
<p>Your manifest file has the below code,</p>
<pre class="brush: java; title: ; notranslate">

&lt;manifest xmlns:android=&quot;&lt;a href=&quot;http://schemas.android.com/apk/res/android&quot;&gt;http://schemas.android.com/apk/res/android&lt;/a&gt;&quot;
package=&quot;my.app&quot;
android:versionCode=&quot;1&quot;
android:versionName=&quot;1.0&quot;&gt;
&lt;application android:icon=&quot;@drawable/icon&quot; android:label=&quot;@string/app_name&quot;&gt;
&lt;activity android:name=&quot;.ActivityAsyncTask&quot;
android:label=&quot;@string/app_name&quot;&gt;
&lt;intent-filter&gt;
&lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
&lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
&lt;/intent-filter&gt;
&lt;/activity&gt;

&lt;/application&gt;
&lt;uses-sdk android:minSdkVersion=&quot;8&quot; /&gt;
&lt;/manifest&gt;</pre>
<h3>Step 6: Run your App</h3>
<p>Select your project-&gt; Right click-&gt; Run As-&gt; Android Application</p>
<p>Activity ActivityAsyncTask fires up as below.</p>
<p><a href="http://techbreaths.com/wp-content/uploads/2013/02/asynctask1.png"><img class="aligncenter size-full wp-image-1021" alt="asynctask1" src="http://techbreaths.com/wp-content/uploads/2013/02/asynctask1.png" width="333" height="494" /></a></p>
<p>Enter a number of your choice(say 10) in the EditText and click on the button &#8220;Count&#8221;. Now the countDown starts as below.</p>
<p><a href="http://techbreaths.com/wp-content/uploads/2013/02/asynctask3.png"><img class="aligncenter size-full wp-image-1023" alt="asynctask3" src="http://techbreaths.com/wp-content/uploads/2013/02/asynctask3.png" width="330" height="490" /></a></p>
<p>When the count reaches 10 it stops and the below message appears on screen.</p>
<p><a href="http://techbreaths.com/wp-content/uploads/2013/02/Async4.png"><img class="aligncenter size-full wp-image-1024" alt="Async4" src="http://techbreaths.com/wp-content/uploads/2013/02/Async4.png" width="332" height="493" /></a></p>
<p>This is how you can make your long running tasks to run using <strong>AsyncTask</strong> without blocking the main UI thread. <strong>AsyncTask</strong> starting with DONUT was offering multitasking by using pool of threads whereas starting with HONEYCOMB, it uses single threading model. If you truly want parallel execution, you can always use executeOnExecutor(java.util.concurrent.Executor, Object[]) instead of execute(). Hope this tutorial helped you. Please post your queries, doubts if any in the comments section.</p>
<ul>
<li>Buy: <a href="http://www.flipkart.com/hello-android-9350232927/p/itmdf86bfgupeddu?pid=9789350232927&amp;affid=suthukrish" target="_blank">Hello, Android!!</a></li>
<li><a href="http://developer.android.com/reference/android/os/AsyncTask.html" target="_blank">Google Reference </a></li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=XHsV-melh0w:yna_wVSWW1g:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=XHsV-melh0w:yna_wVSWW1g:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=XHsV-melh0w:yna_wVSWW1g:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=XHsV-melh0w:yna_wVSWW1g:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=XHsV-melh0w:yna_wVSWW1g:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=XHsV-melh0w:yna_wVSWW1g:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=XHsV-melh0w:yna_wVSWW1g:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=XHsV-melh0w:yna_wVSWW1g:l6gmwiTKsz0"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=l6gmwiTKsz0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=XHsV-melh0w:yna_wVSWW1g:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=XHsV-melh0w:yna_wVSWW1g:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/JavabeatArticles/~4/XHsV-melh0w" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;Connect to us ( &lt;a href="https://twitter.com/javabeat"&gt;@twitter&lt;/a&gt; | &lt;a href="https://www.facebook.com/javabeat.net"&gt;@facebook )&lt;/p&gt;&lt;p&gt;AsyncTask is an Helper class that allows you to perform background operations and updating the UI when the task completes. After the execution of the Background task, the results are published on the UI thread. It is ideal for running short operations that spans for few seconds. It serves better when compared to Threads and [...]&lt;/p&gt;</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.javabeat.net/2013/05/asynctask-android/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">0</slash:comments><feedburner:origLink>http://www.javabeat.net/2013/05/asynctask-android/</feedburner:origLink></item><item><title>Threads and Handlers in Android</title><link>http://feedproxy.google.com/~r/JavabeatArticles/~3/wslKOOQUbIk/</link><category>Google Android</category><category>Android</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">krishnas</dc:creator><pubDate>Fri, 10 May 2013 13:03:28 PDT</pubDate><guid isPermaLink="false">http://www.javabeat.net/?p=7169</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>When an android application is launched, a thread for that application is created by the system. This thread is called &#8220;main&#8221; or &#8220;UI thread&#8221;. Android uses single thread model ie. the system does not create a separate thread for each instance of a component. When you perform a long running task like database access, your UI thread can yield poor performance and these tasks will block the whole UI. Hence you can always create separate threads called worker threads to run your long running tasks.  All the UI updations should be done from the UI thread. Follow the below two rules while dealing with Android threads.</p>
<ol>
<li>Do not block the UI thread</li>
<li>Do not access the Android UI toolkit from outside the UI thread.</li>
</ol>
<p>Lets us now discuss how to make your application execute time consuming tasks without blocking the UI thread</p>
<p>Threading is used when your program executes time consuming  tasks(database access, calling web services etc.) with out blocking the UI thread. You can get away with blocking the UI thread using the following,</p>
<ul>
<li>Thread with handlers</li>
<li>AsynTask</li>
</ul>
<h3>Creating a thread</h3>
<p>The threads other than the Main UI thread are called as Worker threads. If you have operations to perform, that takes long time to complete, It is recommened to include them in worker threads. The worker threads are created using the below code snippet.</p>
<pre class="brush: java; title: ; notranslate">   new Thread(new Runnable() {
public void run() {
//time consuming tasks
}
}).start();</pre>
<p>You can write the code of your long running tasks inside the run() callback. lets assume, I have an ImageView in my layout file. I want to download an image from the internet and upload that to the ImageView. I can add the code for downloading the image inside run() callback. Once the image from the internet is downloaded, I should set that image to the ImageView. Now the question is, Where will you write the code to update that ImageView?  Writing the code to update the ImageView inside run() method would not yield guaranteed result since you violet the second rule that we have already discussed, which says &#8220;Do not access the Android UI toolkit from outside the UI thread&#8221;. This can be solved by using handlers.</p>
<h3>Handlers</h3>
<p>Handlers are used to make updations to the UI in response to messages sent by threads running within the application&#8217;s process. Each handler instance is associated with the thread from which its been created and that thread&#8217;s message queue. Handlers are implemented in the main thread of an application. Handlers are used to send and process the following that are associated with the thread&#8217;s messagequeue. When a thread sends a message to the Handler it will get saved into a message queue and gets executed by the UI thread as soon as possible.</p>
<ul>
<li>Messages</li>
<li>Runnable Objects</li>
</ul>
<p>Let us look at the code snippet that tells how you can communicate with the handler using messages and Runnable Objects.</p>
<h3>Communicating with the handler using Messages</h3>
<p>This is done using the callback method handleMessage(Message msg) which is called when the messages are sent by the thread using the following methods</p>
<ul>
<li>sendEmptyMessage(int)</li>
<li>sendMessage(Message)</li>
</ul>
<p>Message sending can be scheduled and delayed by using the below methods,</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<ul>
<li>sendEmptyMessageAtTime(int,long)</li>
<li>sendEmptyMessageDelayed(int,long)</li>
<li>sendMessageAtTime(Message,long)</li>
<li>sendMessageDelayed(Message,long)</li>
</ul>
<p>Handler object is created and the run callback is used as below</p>
<pre class="brush: java; title: ; notranslate">Handler handler = new Handler() {

//handles the thread's messages and updates the UI
@Override
public void handleMessage(Message msg) {
//code to update the UI goes here....
}
};</pre>
<p>The code that is used to update the user interface should be written inside the handleMessage() method which is called when the thread sends any messages to this handler. The worker thread which sends an empty message is created as below.</p>
<pre class="brush: java; title: ; notranslate">

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

//starting a new thread on click of a button
new Thread(new Runnable() {
public void run() {
try {
/*long running tasks code is written here... I have made the thread to sleep for 4 seconds*/
Thread.sleep(4000);

//Sending an empty message to the handler indicating that the task has finished its execution
handler.sendEmptyMessage(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}</pre>
<p>As you can notice in the above code I have simply made the thread to sleep for 4 seconds so as to create an environment where the main thread has to wait for 4 seconds to get response from the worker thread. In your examples you can do any time consuming tasks like database access etc. in the place of this line. In the above snippet I have created a thread on click of a button which sends an empty message to the handler. Then the handler processes that message and updates the UI. Here I have just used a textview whose text changes when a thread sends the message to the handler.</p>
<pre class="brush: java; title: ; notranslate">Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
txt.setText(&quot;text updated by worker thread&quot;);
}
};</pre>
<p>In the above snippet, our worker thread has just sent an empty message to the handler. What if our thread wants to send any data to the handler? This is done using the method Message.setData(Bundle bundle), where Bundle object contains the data to be transfered. The code snippet for data transfer between thread and handler is as below.</p>
<pre class="brush: java; title: ; notranslate">

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//starting a new thread on click of a button
new Thread(new Runnable() {
public void run() {
try {
/*long running tasks code is written here... I have made the thread to sleep for 4 seconds*/
Thread.sleep(4000);
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putString(&quot;Message&quot;, &quot;Data transfered&quot;);
msg.setData(bundle);
// send message to the handler
handler.sendMessage(msg);

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}</pre>
<p>The handler that processes the data sent by the worker thread is as below,</p>
<pre class="brush: java; title: ; notranslate">Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// get the bundle and extract data by key
Bundle bundle = msg.getData();
String message = bundle.getString(&quot;Message&quot;);
txt.setText(message);
}
};</pre>
<p>So far we have learnt how to communicate with the handler using messages. Lets us now look at how to communicate with the handler using Runnable Object.</p>
<h3>Communicating with the handler using Runnable Object</h3>
<p>You can use handlers by passing Runnable object to the handler.post() method. Use the below code snippet to use runnables,</p>
<pre class="brush: java; title: ; notranslate">

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Runnable r=null;
//starting a new thread on click of a button
new Thread(new Runnable() {
public void run() {
try {
/*long running tasks code is written here... I have made the thread to sleep for 4 seconds*/
Thread.sleep(4000);

handler.post(r);

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}</pre>
<p>When you create any worker threads for your application to perform any time consuming tasks, it is recommended to keep the user informed saying that they will have to wait for sometime to get their work done. This is done by showing a progress dialog or a progress bar to the user. Please refer to the post <a title="How to create ProgressDialog in android?" href="http://techbreaths.com/2013/01/how-to-create-progressdialog-in-android/">ProgressDialog </a>to know how to use threads and handlers in an application and how to keep the user informed about the background task. By using worker threads you can run time consuming tasks without blocking the User interface, however the long running tasks can be handled easily using AsyncTask. We would be discussing about AsyncTask in our next tutorial <a href="http://AsyncTask in android">AsyncTask</a>. Hope this tutorial helped you to understand the usage of Threads and handlers. Feel free to post your queries regarding this tutorial in comments section.</p>
<ul>
<li style="display: inline !important;"><a title="Android Books" href="http://www.techbreaths.com/android-books/" target="_top"> </a></li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=wslKOOQUbIk:I_9qdWKT25U:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=wslKOOQUbIk:I_9qdWKT25U:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=wslKOOQUbIk:I_9qdWKT25U:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=wslKOOQUbIk:I_9qdWKT25U:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=wslKOOQUbIk:I_9qdWKT25U:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=wslKOOQUbIk:I_9qdWKT25U:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=wslKOOQUbIk:I_9qdWKT25U:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=wslKOOQUbIk:I_9qdWKT25U:l6gmwiTKsz0"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=l6gmwiTKsz0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=wslKOOQUbIk:I_9qdWKT25U:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=wslKOOQUbIk:I_9qdWKT25U:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/JavabeatArticles/~4/wslKOOQUbIk" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;Connect to us ( &lt;a href="https://twitter.com/javabeat"&gt;@twitter&lt;/a&gt; | &lt;a href="https://www.facebook.com/javabeat.net"&gt;@facebook )&lt;/p&gt;&lt;p&gt;When an android application is launched, a thread for that application is created by the system. This thread is called &amp;#8220;main&amp;#8221; or &amp;#8220;UI thread&amp;#8221;. Android uses single thread model ie. the system does not create a separate thread for each instance of a component. When you perform a long running task like database access, your [...]&lt;/p&gt;</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.javabeat.net/2013/05/threads-handlers-android/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">0</slash:comments><feedburner:origLink>http://www.javabeat.net/2013/05/threads-handlers-android/</feedburner:origLink></item><item><title>How to create ProgressDialog in android?</title><link>http://feedproxy.google.com/~r/JavabeatArticles/~3/9o8qbM85Q7I/</link><category>Google Android</category><category>Android</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">krishnas</dc:creator><pubDate>Thu, 09 May 2013 12:59:42 PDT</pubDate><guid isPermaLink="false">http://www.javabeat.net/?p=7166</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>Android Progress Dialog is an extension of the AlertDialog class that can display a spinner wheel or a progress bar. These dialogs help us to inform the users about the time consuming tasks and keep them involved till they get their work done. Android progress dialog can be of two types.</p>
<ol>
<li>ProgressDialog with a horizontal progress bar.</li>
<li>ProgressDialog with a ciruclar, spinning progress bar.</li>
</ol>
<p>A ProgressDialog with a Spinner wheel looks like the below screen.</p>
<p><img class="aligncenter size-full wp-image-1004" alt="progress1" src="http://techbreaths.com/wp-content/uploads/2013/01/progress1.png" width="273" height="143" /><br />
A ProgressDialog with the horizontal Progress Bar is as below.</p>
<p><img class="aligncenter size-full wp-image-1005" alt="progress2" src="http://techbreaths.com/wp-content/uploads/2013/01/progress2.png" width="297" height="138" /></p>
<p>These ProgressDialogs can have buttons too(Example: to cancel a download progress). The dialog can be made cancelable on back key press.</p>
<p>This tutorial demostrates how you can create a simple ProgressDialog with the Spinning Wheel.</p>
<h3>Creating a ProgressDialog with circular spinning wheel</h3>
<p>The Spinning wheel ProgressDialog  is often used when your long running task takes undefined time or its time of completion is not known.</p>
<p>A progress dialog can be opened by calling ProgressDialog.show(). This can be easily done without managing the dialog inside onCreateDialog() callback as used in the post <a title="How to add lists, Checkboxes and Radio buttons to an AlertDialog – Android" href="http://techbreaths.com/2013/01/how-to-add-lists-checkboxes-and-radio-buttons-to-an-alertdialog/">AlertDialog </a>while creating an AlertDialog which has lists,Checkboxes and RadioButtons.</p>
<p>The syntax of ProgressDialog.show() is as below.</p>
<pre class="brush: java; title: ; notranslate">ProgressDialog.show(ActivityProgressDialog.this,
&amp;quot;Please wait&amp;quot;, &amp;quot;Your result is being calculated&amp;quot;, true);</pre>
<p>where the first parameter represents the context, second represents the title, third is the message and the last parameter tells whether the ProgressDialod is indeterminate or not. We have passed true since we are creating a spinning wheel ProgressDialog. The default style of the ProgressDialog is Spinning Wheel. Hence you can use the show() method without the last parameter.</p>
<p>Let us now discuss a simple example which explains the steps to create a Spinning wheel Progress Dialog.</p>
<p>In this example we are building a result calculation system. When the user clicks on the submit button, a ProgressDialog is shown, which asks him to wait till the result is being calculated. Then the result is shown to the user. Here the emphasis is more on creating a ProgressDialog and not on result calculation. Hence the &#8220;score&#8221; String is hardcoded with some value to display it to the user.</p>
<h3>Step 1: Set up the android working environment</h3>
<p>If you are not familiar with setting up an android environment, please have a look at the post, <a title="How to set up android development environment?" href="http://techbreaths.com/2012/12/setting-environment-android-app/">Environment</a>. This example is built using API level 8.</p>
<h3>Step 2: Create an Android Project</h3>
<p>Create an android project named ProgressDialogDemo with the launcher activity ActivityProgressDialog.java. If you are not familiar with the android project creation, please refer to the post <a title="How to write a simple Android application?" href="http://techbreaths.com/2012/12/creating-simple-android-app/">Simple android project</a>.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h3>Step 3: Create the required layouts</h3>
<p>In this example, We would be using main.xml layout file. If you want to know more about layout files, please refer to the post <a title="Layouts in Android" href="http://techbreaths.com/2012/12/layouts-android/">Layouts</a>. Open the main.xml file and paste the below code.</p>
<pre class="brush: java; title: ; notranslate">
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot;?&amp;gt;
&amp;lt;RelativeLayout android:id=&amp;quot;@+id/RelativeLayout01&amp;quot;
android:layout_width=&amp;quot;fill_parent&amp;quot; android:layout_height=&amp;quot;fill_parent&amp;quot;
xmlns:android=&amp;quot;&amp;lt;a href=&amp;quot;http://schemas.android.com/apk/res/android&amp;quot;&amp;gt;

http://schemas.android.com/apk/res/android&lt;/a&gt;&quot;&gt;

&amp;lt;TextView android:id=&amp;quot;@+id/TextView01&amp;quot; android:layout_width=&amp;quot;wrap_content&amp;quot;
android:layout_height=&amp;quot;wrap_content&amp;quot; android:text=&amp;quot;Press Submit button to get your results&amp;quot;
android:layout_centerHorizontal=&amp;quot;true&amp;quot; android:textStyle=&amp;quot;bold&amp;quot;
android:textSize=&amp;quot;15sp&amp;quot; android:layout_marginTop=&amp;quot;30dip&amp;quot;&amp;gt;&amp;lt;/TextView&amp;gt;

&amp;lt;Button android:id=&amp;quot;@+id/Button01&amp;quot; android:layout_below=&amp;quot;@id/TextView01&amp;quot;
android:layout_width=&amp;quot;wrap_content&amp;quot; android:layout_height=&amp;quot;wrap_content&amp;quot;
android:layout_centerHorizontal=&amp;quot;true&amp;quot; android:text=&amp;quot;Submit&amp;quot;
android:layout_marginTop=&amp;quot;15dip&amp;quot;&amp;gt;&amp;lt;/Button&amp;gt;

&amp;lt;TextView android:id=&amp;quot;@+id/TextView02&amp;quot; android:layout_below=&amp;quot;@id/Button01&amp;quot;
android:layout_width=&amp;quot;wrap_content&amp;quot; android:layout_height=&amp;quot;wrap_content&amp;quot;
android:layout_centerHorizontal=&amp;quot;true&amp;quot; android:visibility=&amp;quot;gone&amp;quot;
android:textSize=&amp;quot;16sp&amp;quot; android:textStyle=&amp;quot;bold&amp;quot;
android:text=&amp;quot;congratulations!! Your score is &amp;quot;&amp;gt;&amp;lt;/TextView&amp;gt;
&amp;lt;/RelativeLayout&amp;gt;</pre>
<p>The main.xml has a &#8220;Submit&#8221; button which triggers a ProgressDialog. It has 2 textviews.The first one is Textview01, which tells the user to click &#8220;Submit&#8221; button. Textview02 is made invisible in the beginning.</p>
<h3>Step 4: Create the required Activities</h3>
<p>Here in this example, we would be using launcher activity ActivityProgressDialog.java. Open ActivityProgressDialog.java and paste the below code.</p>
<pre class="brush: java; title: ; notranslate">

package my.app;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class ActivityProgressDialog extends Activity {
ProgressDialog progressdialog;
Button Spinner_progress, Progress_bar;
ProgressDialog progressbar;
Handler mHandler;
TextView instruction,marks_update;
String score;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Spinner_progress=(Button)findViewById(R.id.Button01);
instruction=(TextView)findViewById(R.id.TextView01);
marks_update=(TextView)findViewById(R.id.TextView02);
Spinner_progress.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
progressdialog=ProgressDialog.show(ActivityProgressDialog.this,
&amp;quot;Please wait&amp;quot;, &amp;quot;Your score is being calculated&amp;quot;);

//creating a separate thread
new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub

try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
getResults();
}
}).start();

mHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
super.handleMessage(msg);
switch (msg.what)
{
case 10:
progressdialog.dismiss();
marks_update.setVisibility(View.VISIBLE);
marks_update.append(score);
instruction.setVisibility(View.GONE);
Spinner_progress.setVisibility(View.GONE);

break;
}
}
};

}
});
}
private void getResults() {
// TODO Auto-generated method stub
try {
/*Write the code of your long
*running tasks here*/

//assigned 80% to score string, to display the results
score=&amp;quot;80%&amp;quot;;

mHandler.sendEmptyMessage(10);

} catch (Exception e) {
// TODO: handle exception
mHandler.sendEmptyMessage(1);
}
}

}</pre>
<p>Let us now try to understand the flow of the above code. In the onCreate() function we create the ProgressDialog on click of the button &#8220;submit&#8221; using the method ProgressDialog.show(). As you can notice, we have created a separate thread to calculate the result. when the thread.start() is executed, it creates a new thread and executes the run() function, which inturn calls the method getResults(). Before calling getResults() I have made the thread to sleep for some time. This is done to make the ProgressDialog visible for more time.</p>
<p>The getResults() method calculates your score(does long running tasks in other case) and sends an Empty message to the handler. Sometimes its difficult to update the UI when you are running separate threads hence here we use handlers to update the UI. When the handler receives the message, it dismisses the ProgressDialog and does the UI updations.</p>
<h3>Step 5: Declare the activities in AndroidManifest.xml</h3>
<p>Your launcher activity is declared automatically. If you want to know more about AndroidManifest.xml file, please refer to our earlier post, <a title="How to write AndroidManifest.xml?" href="http://techbreaths.com/2012/12/androidmanifest-xml/">Manifest</a>.</p>
<p>Your Manifest file has the below code.</p>
<pre class="brush: java; title: ; notranslate">

&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot;?&amp;gt;
&amp;lt;manifest xmlns:android=&amp;quot;&amp;lt;a href=&amp;quot;http://schemas.android.com/apk/res/android&amp;quot;&amp;gt;

http://schemas.android.com/apk/res/android&lt;/a&gt;&quot;

package=&amp;quot;my.app&amp;quot;
android:versionCode=&amp;quot;1&amp;quot;
android:versionName=&amp;quot;1.0&amp;quot;&amp;gt;
&amp;lt;application android:icon=&amp;quot;@drawable/icon&amp;quot; android:label=&amp;quot;@string/app_name&amp;quot;&amp;gt;
&amp;lt;activity android:name=&amp;quot;.ActivityProgressDialog&amp;quot;
android:label=&amp;quot;@string/app_name&amp;quot;&amp;gt;
&amp;lt;intent-filter&amp;gt;
&amp;lt;action android:name=&amp;quot;android.intent.action.MAIN&amp;quot; /&amp;gt;
&amp;lt;category android:name=&amp;quot;android.intent.category.LAUNCHER&amp;quot; /&amp;gt;
&amp;lt;/intent-filter&amp;gt;
&amp;lt;/activity&amp;gt;

&amp;lt;/application&amp;gt;
&amp;lt;uses-sdk android:minSdkVersion=&amp;quot;8&amp;quot; /&amp;gt;

&amp;lt;/manifest&amp;gt;</pre>
<h3>Step 6: Run your project</h3>
<p>Select your project-&gt;right click-&gt;Run As-&gt;Android Application.</p>
<p>Your project runs and the activity fires up as below.</p>
<p><img class="aligncenter size-full wp-image-1010" alt="progressoutpt" src="http://techbreaths.com/wp-content/uploads/2013/01/progressoutpt.png" width="333" height="492" /></p>
<p>Press the submit button to see your progress Dialog.</p>
<p><img class="aligncenter size-full wp-image-1011" alt="progressdialog_1" src="http://techbreaths.com/wp-content/uploads/2013/01/progressdialog_1.png" width="329" height="492" /></p>
<p>Then the score displays as below.</p>
<p><img class="aligncenter size-full wp-image-1009" alt="progressdialog_out" src="http://techbreaths.com/wp-content/uploads/2013/01/progressdialog_out.png" width="333" height="487" />So far we have seen how to develop an android Spinning Wheel ProgressDialog to make the users involved when a long running tasks need to be done in the background. We would be studying about Horizontal Progress Bar( the other type of ProgressDialog) in our upcomming posts. I Hope this tutorial served your purpose. Feel free to post your comments if you have any queries.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=9o8qbM85Q7I:LdQgjZaFLUA:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=9o8qbM85Q7I:LdQgjZaFLUA:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=9o8qbM85Q7I:LdQgjZaFLUA:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=9o8qbM85Q7I:LdQgjZaFLUA:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=9o8qbM85Q7I:LdQgjZaFLUA:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=9o8qbM85Q7I:LdQgjZaFLUA:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=9o8qbM85Q7I:LdQgjZaFLUA:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=9o8qbM85Q7I:LdQgjZaFLUA:l6gmwiTKsz0"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=l6gmwiTKsz0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=9o8qbM85Q7I:LdQgjZaFLUA:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=9o8qbM85Q7I:LdQgjZaFLUA:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/JavabeatArticles/~4/9o8qbM85Q7I" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;Connect to us ( &lt;a href="https://twitter.com/javabeat"&gt;@twitter&lt;/a&gt; | &lt;a href="https://www.facebook.com/javabeat.net"&gt;@facebook )&lt;/p&gt;&lt;p&gt;Android Progress Dialog is an extension of the AlertDialog class that can display a spinner wheel or a progress bar. These dialogs help us to inform the users about the time consuming tasks and keep them involved till they get their work done. Android progress dialog can be of two types. ProgressDialog with a horizontal [...]&lt;/p&gt;</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.javabeat.net/2013/05/progressdialog-android/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">0</slash:comments><feedburner:origLink>http://www.javabeat.net/2013/05/progressdialog-android/</feedburner:origLink></item><item><title>Annotation Support for Scheduling and Asynchronous Execution</title><link>http://feedproxy.google.com/~r/JavabeatArticles/~3/cG5HREwxjlE/</link><category>Spring Framework</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Manisha Patil</dc:creator><pubDate>Wed, 08 May 2013 09:04:02 PDT</pubDate><guid isPermaLink="false">http://www.javabeat.net/?p=7284</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In the previous post <a href="http://www.javabeat.net/2013/05/task-execution-scheduling-spring/">Task Execution and Scheduling in Spring</a>, I explained basic interfaces for task execution and scheduling. In this post I shall demonstrate an example for the same using annotations <strong>@Scheduled</strong> and <strong>@Async</strong>. Let us have working Eclipse IDE in place and follow the steps to create a scheduled Spring application:</p>
<ol>
<li><b>Create a project</b>: Create a project with a name <i>SpringScheduler</i> and create a package <i>com.javabeat</i> under the src directory in the created project.</li>
<li><b>Add Libraries</b>: Add required Spring libraries using Add External JARs option as explained in the article <a title=" How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/" target="_blank">Customizing callback methods</a>. Along with these libraries also add <i>aopalliance-1.0.jar</i> to the build path.</li>
<li><b>Create source files</b>: Create Java classes SchedulerSample,TaskSample and MainApp under the <i>com.javabeat</i> package.</li>
<li><b>Create configuration file</b>: Create XML based configuration file Beans.xml under <i>src</i> directory.</li>
</ol>
<p>follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a></p>
<ul>
<li><a href="http://www.javabeat.net/spring-framework-books/">Spring Framework Books</a></li>
<li><a href="http://www.javabeat.net/2013/03/spring-tutorials/">Spring Tutorials ( Collection for Spring reference tutorials)</a></li>
<li><a href="http://www.javabeat.net/2009/02/spring-framework-interview-questions/">Spring Framework Interview Questions</a></li>
<li><a href="http://www.javabeat.net/2011/05/introduction-to-spring-ldap/">Introduction to Spring LDAP</a></li>
<li><a title="How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/">How to write Custom Spring Callback Methods?</a></li>
</ul>
<p>The content of <b>SchedulerSample.java</b> file are:</p>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class SchedulerSample {

	  @Autowired
	  private TaskSample task;

	  @Scheduled(fixedDelay = 3000)
	  public void processScheduledJob() {
	    task.execute();
	  }

	  public TaskSample getTask() {
	    return task;
	  }

	  public void setTask(TaskSample task) {
	    this.task = task;
	  }
}
</pre>
<p>Here you can note that we have scheduled the task for a time of 3000 milliseconds.</p>
<p>The content of <b>TaskSample.java</b> file are:</p>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class TaskSample {
	@Async
	public void execute() {
		System.out
		.println(&quot;Executing asynchronous task for every fixedDelay of 3000millisecond.&quot;);
	}
}
</pre>
<p>The execute() method will be called every 3000 milliseconds.</p>
<p>The content of <b>Beans.xml</b> file are:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
 xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
 xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
 xmlns:task=&quot;http://www.springframework.org/schema/task&quot;
 xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd


http://www.springframework.org/schema/task


http://www.springframework.org/schema/task/spring-task-3.0.xsd


http://www.springframework.org/schema/context


http://www.springframework.org/schema/context/spring-context-3.0.xsd&quot;&gt;

&lt;context:component-scan base-package=&quot;com.javabeat&quot; /&gt;

&lt;task:annotation-driven executor=&quot;executor&quot; scheduler=&quot;scheduler&quot; /&gt;

&lt;task:executor id=&quot;executor&quot; pool-size=&quot;5&quot; /&gt;

&lt;task:scheduler id=&quot;scheduler&quot; pool-size=&quot;5&quot; /&gt;

&lt;/beans&gt;
</pre>
<p>Here we need to note few things:</p>
<ul>
<li>To enable the annotation driven scheduling we have added the <i>annotation-driven</i> element from the task namespace.</li>
<li>Schema http://www.springframework.org/schema/task, http://www.springframework.org/schema/task/spring-task-3.0.xsd, are added to the above file.</li>
<li><i>task:executor </i> &#8211; creates an instance of ThreadPoolTaskExecutor.</li>
<li><i>task:scheduler </i> &#8211; creates an instance of ThreadPoolTaskScheduler.</li>
</ul>
<p>To execute the application the <b>MainApp.java</b> is as follows:</p>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
	public static void main(String[] args) {
	    new ClassPathXmlApplicationContext(&quot;Beans.xml&quot;);
	  }
}
</pre>
<p><b>Execute the code</b></p>
<p>The final step is run the application. Once all the above code is ready execute and the below output appears on the console:</p>
<pre class="brush: java; title: ; notranslate">
Executing asynchronous task for every fixedDelay of 3000millisecond.
Executing asynchronous task for every fixedDelay of 3000millisecond.
</pre>
<p>As you can see the message is printed at a delay of 3000millisecond. You need to stop the application to stop the printing of message.</p>
<h2>Summary</h2>
<p>In this section I demonstrated an example of scheduling the Spring application using the annotation.If you are interested in receiving the future articles, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>. follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=cG5HREwxjlE:xb8f2ifAFBs:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=cG5HREwxjlE:xb8f2ifAFBs:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=cG5HREwxjlE:xb8f2ifAFBs:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=cG5HREwxjlE:xb8f2ifAFBs:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=cG5HREwxjlE:xb8f2ifAFBs:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=cG5HREwxjlE:xb8f2ifAFBs:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=cG5HREwxjlE:xb8f2ifAFBs:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=cG5HREwxjlE:xb8f2ifAFBs:l6gmwiTKsz0"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=l6gmwiTKsz0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=cG5HREwxjlE:xb8f2ifAFBs:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=cG5HREwxjlE:xb8f2ifAFBs:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/JavabeatArticles/~4/cG5HREwxjlE" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;Connect to us ( &lt;a href="https://twitter.com/javabeat"&gt;@twitter&lt;/a&gt; | &lt;a href="https://www.facebook.com/javabeat.net"&gt;@facebook )&lt;/p&gt;&lt;p&gt;In the previous post Task Execution and Scheduling in Spring, I explained basic interfaces for task execution and scheduling. In this post I shall demonstrate an example for the same using annotations @Scheduled and @Async. Let us have working Eclipse IDE in place and follow the steps to create a scheduled Spring application: Create a project: [...]&lt;/p&gt;</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.javabeat.net/2013/05/annotation-scheduling-asynchronous-spring-examples/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">0</slash:comments><feedburner:origLink>http://www.javabeat.net/2013/05/annotation-scheduling-asynchronous-spring-examples/</feedburner:origLink></item><item><title>Task Execution and Scheduling in Spring</title><link>http://feedproxy.google.com/~r/JavabeatArticles/~3/VvxJQW88Q24/</link><category>Spring Framework</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">Manisha Patil</dc:creator><pubDate>Wed, 08 May 2013 02:50:07 PDT</pubDate><guid isPermaLink="false">http://www.javabeat.net/?p=7242</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>Spring 2.0 introduced abstractions for asynchronous execution and scheduling of tasks. The key interfaces for scheduling and task execution are as listed as <strong>TaskExecutor, </strong><strong>TaskScheduler, </strong><strong>Trigger, </strong><strong>TriggerContext and </strong><strong>ScheduledFuture</strong>. Let take a look at each of these interfaces. This article explores spring&#8217;s scheduler related APIs in detail. You can read the official explanation for this API&#8217;s <a href="http://static.springsource.org/spring/docs/3.0.x/reference/scheduling.html" target="_blank">here</a>.</p>
<p>follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a></p>
<ul>
<li><a href="http://www.javabeat.net/spring-framework-books/">Spring Framework Books</a></li>
<li><a href="http://www.javabeat.net/2013/03/spring-tutorials/">Spring Tutorials ( Collection for Spring reference tutorials)</a></li>
<li><a href="http://www.javabeat.net/2009/02/spring-framework-interview-questions/">Spring Framework Interview Questions</a></li>
<li><a href="http://www.javabeat.net/2011/05/introduction-to-spring-ldap/">Introduction to Spring LDAP</a></li>
<li><a title="How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/">How to write Custom Spring Callback Methods?</a></li>
</ul>
<h2>TaskExecutor</h2>
<p>TaskExecutor was introduced as an abstraction for dealing with executors. <i>Executors</i> are the Java 5 name for the concept of thread pools. The primary aim of TaskExecutor is to abstract away the need for Java 5 when using thread pools. The interface has only a single method as shown below:</p>
<pre class="brush: java; title: ; notranslate">
public interface TaskExecutor extends java.util.concurrent.Executor {
void execute(Runnable task);
}
</pre>
<p><b>TaskExecutor Implementation Classes</b></p>
<ul>
<li>SimpleAsyncTaskExecutor: Does not reuse threads. It starts a new thread and is asynchronus.</li>
<li>SyncTaskExecutor: No thread reuse and is synchonous. Instead, each invocation takes place in the calling thread.</li>
<li>ConcurrentTaskExecutor: Exposes the Java 5 <i>java.util.concurrent.Executor</i>.</li>
<li>SimpleThreadPoolTaskExecutor: It is a subclass of Quartz&#8217;s SimpleThreadPool which listens to Spring&#8217;s lifecycle callbacks.</li>
<li>ThreadPoolTaskExecutor: It exposes bean properties for configuring a ThreadPoolExecutor configuration and and wraps it in a TaskExecutor.</li>
<li>TimerTaskExecutor: This implementation uses a single TimerTask as its backing implementation. It&#8217;s different from the SyncTaskExecutor in that the method invocations are executed in a separate thread, although they are synchronous in that thread.</li>
<li>WorkManagerTaskExecutor: This implementation uses the CommonJ WorkManager as its backing implementation</li>
</ul>
<h2>TaskScheduler</h2>
<p>This interface has a variety of methods for scheduling tasks to run at some point in the future, as seen below:</p>
<pre class="brush: java; title: ; notranslate">
public interface TaskScheduler {
ScheduledFuture schedule(Runnable task, Trigger trigger);

    ScheduledFuture schedule(Runnable task, Date startTime);

    ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period);

    ScheduledFuture scheduleAtFixedRate(Runnable task, long period);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay);
}
</pre>
<p>FixedRate &#8211; period will be measured from the start time<br />
FixedDelay &#8211; period will be measured from the completion time</p>
<p><b>TaskScheduler Implementation Classes</b></p>
<ul>
<li>TimerManagerTaskScheduler: Delegates to a CommonJ TimerManager instance, typically configured with a JNDI-lookup.</li>
<li>ThreadPoolTaskScheduler: Used whenever external thread management is not a requirement. Internally, it delegates to a ScheduledExecutorService instance.</li>
</ul>
<h2>Trigger</h2>
<p>Using Trigger the execution times may be determined based on past execution outcomes or even arbitrary conditions. The Trigger interface is as follows:</p>
<pre class="brush: java; title: ; notranslate">
public interface Trigger {
Date nextExecutionTime(TriggerContext triggerContext);
}
</pre>
<p>TriggerContext is an interface and encapsulates all of the relevant data.</p>
<p><b>Trigger Implementation Classes</b></p>
<ul>
<li>CronTrigger: It enables the scheduling of tasks based on cron expressions.</li>
<li>PeriodicTrigger: It accepts a fixed period, an optional initial delay value, and a boolean to indicate whether the period should be interpreted as a fixed-rate or a fixed-delay.</li>
</ul>
<h2>Bootstrapping the scheduler</h2>
<p>Since Spring 3.0, XML namespace for configuring TaskExecutor and TaskScheduler instances is available. It also provides a convenient way to configure tasks to be scheduled with a trigger. Add the following schema to the spring configuration file(xml file):</p>
<pre class="brush: java; title: ; notranslate">

http://www.springframework.org/schema/task


http://www.springframework.org/schema/task/spring-task-3.0.xsd

</pre>
<p><b>Task Namespace</b><br />
Add the following configuration :</p>
<pre class="brush: java; title: ; notranslate">
&lt;task:executor id=&quot;executor&quot; pool-size=&quot;8-25&quot; queue-capacity=&quot;100&quot; /&gt;
&lt;task:scheduler id=&quot;scheduler&quot; pool-size=&quot;10&quot; /&gt;
</pre>
<ul>
<li><b>task:executor </b> &#8211; Create instance of ThreadPoolTaskExecutor</li>
<li><b>task:scheduler </b> &#8211; Create instance of ThreadPoolTaskScheduler</li>
<li><b>pool-size</b> &#8211; If the value is not provided, then the default thread pool will only have a single thread.</li>
<li><b>queue-capacity</b> &#8211; Number of tasks held back. Default value is <i>Unbound</i></li>
<li><b>rejection-policy</b> &#8211; This another attribute not mentione the above example. Used for to throw exception when a task is rejected. Its default value is <i> AbortPolicy</i>. Other possbile values are &#8211; <i> DiscardPolicy </i>, <i>DiscardOldestPolicy </i>, and <i> CallerRunsPolicy</i>.</li>
</ul>
<h2>Scheduling the Tasks</h2>
<p>Tasks can be scheduled in the following three ways:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<ol>
<li>Annotation Driven</li>
<li>XML Driven</li>
<li>Programmatically</li>
</ol>
<p><b>1. Annotation Driven </b></p>
<p>The @Scheduled annotation can be added to a method along with trigger metadata for task scheduling. The @Async annotation can be provided on a method so that invocation of that method will occur asynchronously.</p>
<p>Add following to your spring configuration file:</p>
<pre class="brush: java; title: ; notranslate">
&lt;context:component-scan annotation-config=&quot;true&quot; base-package=&quot;com.javabeat&quot;/&gt;
&lt;task:annotation-driven executor=&quot;executor&quot; scheduler=&quot;scheduler&quot; /&gt;
</pre>
<p>The following example will only execute on weekdays.:</p>
<pre class="brush: java; title: ; notranslate">
@Scheduled(cron=&quot;*/5 * * * * MON-FRI&quot;)
public void doSomeTask(){
 // some task that should execute on weekdays only
}
</pre>
<blockquote><p>Scheduled methods must have void returns and must not expect any arguments.</p></blockquote>
<p>Syntax for @Async annotation is:</p>
<pre class="brush: java; title: ; notranslate">
@Async
void doSomething() {
    // this will be executed asynchronously
}
</pre>
<p><b>2. XML Driven</b></p>
<p>Add the following configuration to the spring configuration file :</p>
<pre class="brush: java; title: ; notranslate">
&lt;task:scheduled-tasks scheduler=&quot;sampleScheduler&quot;&gt;
   &lt;task:scheduled ref=&quot;someObject&quot;
      method=&quot;someMethod&quot; fixed-delay=&quot;5000&quot;/&gt;
&lt;/task:scheduled-tasks&gt;
</pre>
<p><b>3. Programmatically </b></p>
<p>Go for programmatic way when your application desire more control on scheduling. For example :</p>
<pre class="brush: java; title: ; notranslate">

ThreadPoolTaskScheduler scheduler = (ThreadPoolTaskScheduler) appContext.getBean(&quot;scheduler&quot;);
CronTrigger trigger = new CronTrigger(&quot;*/5 * * * * MON-FRI&quot;);

ScheduledFuture&lt;Object&gt; scedulefuture= scheduler.schedule(taskObject, trigger );

</pre>
<p>In the above example instead of <i>schedule()</i> method, you can use <i>scheduleAtFixedRate(.. , ..)</i> or <i>scheduleWithFixedDelay(.. , ..)</i>.</p>
<h2>Summary</h2>
<p>In this post we saw the basics of task execution and scheduling in Spring. We studied the interfaces <b>TaskExecutor</b>, <b>TaskScheduler</b>, and <b>Trigger</b> and their implementation classes. We also saw methods of scheduling the tasks, annotation driven, XML driven and programmatically. In the next article I shall demonstrate this with an example. If you are interested in receiving the future articles, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>. follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a>.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=VvxJQW88Q24:zLFk-5F5qac:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=VvxJQW88Q24:zLFk-5F5qac:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=VvxJQW88Q24:zLFk-5F5qac:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=VvxJQW88Q24:zLFk-5F5qac:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=VvxJQW88Q24:zLFk-5F5qac:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=VvxJQW88Q24:zLFk-5F5qac:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=VvxJQW88Q24:zLFk-5F5qac:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=VvxJQW88Q24:zLFk-5F5qac:l6gmwiTKsz0"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=l6gmwiTKsz0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=VvxJQW88Q24:zLFk-5F5qac:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=VvxJQW88Q24:zLFk-5F5qac:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/JavabeatArticles/~4/VvxJQW88Q24" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;Connect to us ( &lt;a href="https://twitter.com/javabeat"&gt;@twitter&lt;/a&gt; | &lt;a href="https://www.facebook.com/javabeat.net"&gt;@facebook )&lt;/p&gt;&lt;p&gt;Spring 2.0 introduced abstractions for asynchronous execution and scheduling of tasks. The key interfaces for scheduling and task execution are as listed as TaskExecutor, TaskScheduler, Trigger, TriggerContext and ScheduledFuture. Let take a look at each of these interfaces. This article explores spring&amp;#8217;s scheduler related APIs in detail. You can read the official explanation for this API&amp;#8217;s here. follow us on @twitter and @facebook Spring [...]&lt;/p&gt;</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.javabeat.net/2013/05/task-execution-scheduling-spring/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">0</slash:comments><feedburner:origLink>http://www.javabeat.net/2013/05/task-execution-scheduling-spring/</feedburner:origLink></item><item><title>How to add lists, Checkboxes and Radio buttons to an AlertDialog – Android</title><link>http://feedproxy.google.com/~r/JavabeatArticles/~3/q4tYsYnIBng/</link><category>Google Android</category><category>Android</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">krishnas</dc:creator><pubDate>Mon, 06 May 2013 12:55:11 PDT</pubDate><guid isPermaLink="false">http://www.javabeat.net/?p=7164</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>A Dialog is a small window that appears in front of the current Activity.  An <strong>AlertDialog</strong> is a Dialog which can have zero, one, two or three buttons. We have discussed about creating a simple <strong>AlertDialog</strong> in one of our earlier posts <a title="How to create AlertDialog box in Android?" href="http://www.javabeat.net/2013/05/alertdialog-box-android/">AlertDialog</a>.  The previous tutorial on AlertDialog demonstrated how to create an <strong>AlertDialog</strong> which has  title, simple message and buttons.  This tutorial demonstrates how to add lists, CheckBoxes and Radio Buttons to an <strong>AlertDialog</strong>.</p>
<p>Prerequisites:</p>
<p>You must have enough knowledge on how to create an AlertDialog. If you are not familiar with creating an AlertDialog, please refer to the post <a title="How to create AlertDialog box in Android?" href="http://www.javabeat.net/2013/05/alertdialog-box-android/">Create an AlertDialog </a>.Unlike the previous post, here in this tutorial we would be using  few methods of the Activity</p>
<ul>
<li>onCreateDialog()</li>
<li>onPrepareDialog()</li>
<li>showDialog()</li>
</ul>
<p>When you want to show a dialog, call showDialog(int) method and pass in an integer variable that uniquely identifies your dialog.<br />
When the dialog is requested for the first time, Android calls onCreateDialog(int) from your Activity. You should instantiate your dialog inside onCreateDialog method. This callback returns the Dialog object.</p>
<p>If you want to do change any properties of your dialog each time it is opened, you can make use of an optional callback onPrepareDialog(int,dialog), which is called every time your dialog is opened whereas onCreateDialog(int) is only called for the very first time your dialog is opened. If you donot define onPrepareDialog method, your dialog&#8217;s selection state remains unchanged(such as items checked in the checkbox or radio button remains checked even when the dialog is opened for the second time).</p>
<p>Your job is to call the method showDialog with the unique integer that identifies your dialog. <strong>Android</strong> calls the rest of the methods onCreateDialog and onPrepareDialog.</p>
<p>It is recommended to use switch statement inside onCreateDialog and onPrepareDialog callbacks that checks the id parameter that is passed as parameters to these methods and creates the dialog accordingly.</p>
<pre class="brush: java; title: ; notranslate">
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
switch (id) {
case LIST_ALERTDIALOG:

break;
case CHECKBOX_ALERTDIALOG:

break;
case RADIOBUTTON_ALERTDIALOG:

break;

}
return null;
}</pre>
<h2>Creating an AlertDialog with a list of items</h2>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/1_Alertpost2.png"><img class="aligncenter size-full wp-image-7260" alt="1_Alertpost2" src="http://www.javabeat.net/wp-content/uploads/2013/05/1_Alertpost2.png" width="198" height="170" /></a></p>
<p>Above is the picture of an AlertDialog with a list of items. To create an AlertDialog with a list of selectable items, use the method setItems().</p>
<pre class="brush: java; title: ; notranslate">public AlertDialog.Builder setItems (CharSequence[] items,
DialogInterface.OnClickListener listener);</pre>
<p>The setItems() method takes 2 parameters, first one is the list of items to be displayed in the dialog as its content and the next is the listener which notifies about the selected item.</p>
<p>When you call showDialog(LIST_ALERTDIALOG) method, where LIST_ALERTDIALOG is the variable representing your list AlertDilaog, Android calls the onCreateDialog(LIST_ALERTDIALOG) where in it goes to the first case statement which matches your List AlertDialog. The below code snippet is used to define and create your dialog inside the first case .</p>
<pre class="brush: java; title: ; notranslate">
case LIST_ALERTDIALOG:

AlertDialog.Builder builder=new AlertDialog.Builder(AlertDialogDemo.this)
.setTitle(&quot;Choose a Color&quot;)
.setItems(colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
&quot;The selected color is &quot;+colors_list[which], Toast.LENGTH_LONG).show();
}
});
AlertDialog alertdialog=builder.create();
return alertdialog;</pre>
<p>In the above code colors_list is the array of items to display.</p>
<pre class="brush: java; title: ; notranslate">final CharSequence[] colors_list={&quot;Green&quot;,&quot;Black&quot;,&quot;White&quot;};</pre>
<p>Here in the case statement, we are displaying a Toast message on click of a list item. The toast displays the selected item. If you want more information about how to create a toast message, please go through the post <a title="How to create a Toast message in Android?" href="http://www.javabeat.net/2013/05/toast-message-android/">Toast </a>. Finally the case statement returns the Dialog object.</p>
<p>Note: Few lines in the above case statement are not explained here, since it has been covered in one of our previous posts.  Please refer to the post <a title="How to create AlertDialog box in Android?" href="http://www.javabeat.net/2013/05/alertdialog-box-android/">How to create an AlertDialog</a> to know how to create a simple Alertdialog.</p>
<h2>Creating an AlertDialog with Checkboxes</h2>
<p>Now we would be discussing about the second case statement &#8220;case CHECKBOX_ALERTDIALOG:&#8221; An AlertDialog with checkBoxes is as shown below.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/2_check.png"><img class="aligncenter size-full wp-image-7261" alt="2_check" src="http://www.javabeat.net/wp-content/uploads/2013/05/2_check.png" width="151" height="154" /></a></p>
<p>As you can see in the above screen of alertDialog, I have added a button &#8220;OK&#8221; to get the checked item details. However adding &#8220;OK&#8221; button is optional.</p>
<p>To create an AlertDialog with a list of multiple-choice items, you have to make use of the method setMultiChoiceItems(). The code is as same as the previous code snippet, but setItems() method is replaced with the setMultiChoiceItems() method. This method takes 3 parameters. The syntax of the method setMultiChoiceItems() is as below.</p>
<pre class="brush: java; title: ; notranslate">public AlertDialog.Builder setMultiChoiceItems (CharSequence[] items,
boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener);
</pre>
<p>First parameter is the text of the items to be displayed in the list, second parameter specifies which items are checked. It should be null in which case no items are checked. If non null it must be exactly the same length as the array of items. you will be notified of the selected item via the supplied listener as the third parameter. Clicking on an item in the list will not dismiss the dialog hence I have added a button &#8220;OK&#8221; which takes the items that you have checked and dismisses the dialog on click of it.</p>
<h2>Creating an AlertDialog with RadioButtons</h2>
<p>The alertDialog with a list of single-choice items is as shown below.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/3_radio.png"><img class="aligncenter size-full wp-image-7262" alt="3_radio" src="http://www.javabeat.net/wp-content/uploads/2013/05/3_radio.png" width="153" height="130" /></a></p>
<p>We have to use setSingleChoiceItems() method to create such AlertDialogs. This method takes three parameters. The syntax is as below.</p>
<pre class="brush: java; title: ; notranslate">public AlertDialog.Builder setSingleChoiceItems (CharSequence[] items,
int checkedItem, DialogInterface.OnClickListener listener);</pre>
<p>First parameter is the list of items to be displayed. Second is the &#8220;checkedItem&#8221;  specifies which item is checked. If -1 no items are checked. The third parameter is a &#8220;listener&#8221;  notified when an item on the list is clicked. The dialog will not be dismissed when an item is clicked.</p>
<p>Add the below code to the third case statement of the onCreateDialog method to create an <strong>AlertDialog</strong> with radiobuttons.</p>
<pre class="brush: java; title: ; notranslate">

case RADIOBUTTON_ALERTDIALOG:

AlertDialog.Builder builder2=new AlertDialog.Builder(AlertDialogDemo.this)
.setTitle(&quot;Choose a Color&quot;)
.setSingleChoiceItems(colors_radio, -1, new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
&quot;The selected color is &quot;+colors_radio[which], Toast.LENGTH_LONG).show();

//dismissing the dialog when the user makes a selection.
dialog.dismiss();
}
});
AlertDialog alertdialog2=builder2.create();
return alertdialog2;</pre>
<p>As you see in the above code, We have used dialog.dismiss inside onclick() of the list since clicking on the list item do not dismisses the dialog. colors_radio is the list of items to be displayed.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">final CharSequence[] colors_radio={&quot;Green&quot;,&quot;Black&quot;,&quot;White&quot;};</pre>
<p>If you create any one of the above selectable lists(checkbox or radiobuttons) in the onCreateDialog() callback method, the state of the selected item is managed by Android as long as the Activity is active.</p>
<p>So far we have seen details on AlertDialog with lists, CheckBoxes and RadioButtons. Let us now learn how to create a project which has all these types of dialogs.</p>
<p><strong>Required layouts</strong></p>
<ul>
<li>main.xml which has three buttons namely &#8220;List&#8221;(shows a List AlertDialog), &#8220;CheckBox&#8221; and &#8220;RadioButton&#8221;.</li>
</ul>
<p><strong>Required Activity</strong></p>
<ul>
<li>AlertDialogDemo</li>
</ul>
<h2>Step 1: Set up the android developement evvironment</h2>
<p>This topic has already been discussed in one of our previous posts <a title="How to set up android development environment?" href="http://www.javabeat.net/2013/04/android-development-environment/">Environment</a>. Please refer the post for more queries. I would be using Android 2.2 for this example.</p>
<h2>Step 2: Create the Project</h2>
<p>Create a project named &#8220;AlertDialog&#8221; with the launcher activity AlertDialogDemo.java. For more information on how to create a new project in android, please refer to the post <a title="How to write a simple Android application?" href="http://www.javabeat.net/2013/04/simple-android-application/">Create an android project</a>.</p>
<h2>Step 3: Create the required layouts</h2>
<p>As i said earlier, I would be using main.xml layout file. To know more about layout xml files, please go through the post <a title="Layouts in Android" href="http://www.javabeat.net/2013/04/layouts-in-android/">Layouts</a>. Open the main.xml file and paste the below code.</p>
<pre class="brush: java; title: ; notranslate">

main.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;RelativeLayout android:id=&quot;@+id/RelativeLayout01&quot;
android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;fill_parent&quot;
xmlns:android=&quot;&lt;a href=&quot;http://schemas.android.com/apk/res/android&quot;&gt;

http://schemas.android.com/apk/res/android&lt;/a&gt;&quot;&gt;

&lt;Button android:id=&quot;@+id/Button01&quot; android:layout_height=&quot;wrap_content&quot;
android:text=&quot;List&quot; android:layout_width=&quot;90dip&quot;
android:layout_marginLeft=&quot;20dip&quot; android:layout_centerVertical=&quot;true&quot;&gt;&lt;/Button&gt;
&lt;Button android:id=&quot;@+id/Button02&quot; android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot; android:layout_toRightOf=&quot;@+id/Button01&quot;
android:text=&quot;CheckBox&quot; android:layout_centerVertical=&quot;true&quot;&gt;&lt;/Button&gt;
&lt;Button android:id=&quot;@+id/Button03&quot; android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot; android:layout_toRightOf=&quot;@+id/Button02&quot;
android:text=&quot;RadioButton&quot; android:layout_centerVertical=&quot;true&quot;&gt;&lt;/Button&gt;
&lt;/RelativeLayout&gt;</pre>
<p>As you can notice, I have used three buttons to trigger your three AlertDilaogs.</p>
<h2>Step 4: Create the required Activities</h2>
<p>Here in this example, I would be using the launcher activity &#8220;AlertDialogdemo&#8221;. Open the activity and paste the below code.</p>
<pre class="brush: java; title: ; notranslate">

package my.app;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class AlertDialogDemo extends Activity implements OnClickListener {
/** Called when the activity is first created. */

final int LIST_ALERTDIALOG=0,CHECKBOX_ALERTDIALOG=1,RADIOBUTTON_ALERTDIALOG=2;
final boolean checked_state[]={false,false,false}; //The array that holds the checked state of the checkbox items
final CharSequence[] colors_check={&quot;Green&quot;,&quot;Black&quot;,&quot;White&quot;}; //items in the alertdialog that displays checkboxes
final CharSequence[] colors_list={&quot;Green&quot;,&quot;Black&quot;,&quot;White&quot;}; //items in the alertdialog that displays list
final CharSequence[] colors_radio={&quot;Green&quot;,&quot;Black&quot;,&quot;White&quot;}; //items in the alertdialog that displays radiobuttons
Button list,check,radio;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

list=(Button)findViewById(R.id.Button01);
check=(Button)findViewById(R.id.Button02);
radio=(Button)findViewById(R.id.Button03);

list.setOnClickListener(this);
check.setOnClickListener(this);
radio.setOnClickListener(this);
}

/*triggered by showDialog method. onCreateDialog creates a dialog*/
@Override
public Dialog onCreateDialog(int id) {
switch (id) {
case LIST_ALERTDIALOG:

AlertDialog.Builder builder=new AlertDialog.Builder(AlertDialogDemo.this)
.setTitle(&quot;Choose a Color&quot;)
.setItems(colors_list, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), &quot;The selected color is &quot;+colors_list[which], Toast.LENGTH_LONG).show();
}
});
AlertDialog alertdialog=builder.create();
return alertdialog;

case CHECKBOX_ALERTDIALOG:

AlertDialog.Builder builder1=new AlertDialog.Builder(AlertDialogDemo.this)
.setTitle(&quot;Choose a Color&quot;)
.setMultiChoiceItems(colors_check, null, new DialogInterface.OnMultiChoiceClickListener() {

@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// TODO Auto-generated method stub

//storing the checked state of the items in an array
checked_state[which]=isChecked;
}
})
.setPositiveButton(&quot;OK&quot;, new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String display_checked_colors = &quot;&quot;;
for(int i=0;i&lt;3;i++){
if(checked_state[i]==true){
display_checked_colors=display_checked_colors+&quot; &quot;+colors_check[i];
}
}
Toast.makeText(getApplicationContext(), &quot;The selected color(s) is
&quot;+display_checked_colors, Toast.LENGTH_LONG).show();

//clears the String used to store the displayed text
display_checked_colors=null;

//clears the array used to store checked state
for(int i=0;i&lt;checked_state.length;i++){
if(checked_state[i]==true){
checked_state[i]=false;
}
}

//used to dismiss the dialog upon user selection.
dialog.dismiss();
}
});
AlertDialog alertdialog1=builder1.create();
return alertdialog1;

case RADIOBUTTON_ALERTDIALOG:

AlertDialog.Builder builder2=new AlertDialog.Builder(AlertDialogDemo.this)
.setTitle(&quot;Choose a Color&quot;)
.setSingleChoiceItems(colors_radio, -1, new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
&quot;The selected color is &quot;+colors_radio[which], Toast.LENGTH_LONG).show();

//dismissing the dialog when the user makes a selection.
dialog.dismiss();
}
});
AlertDialog alertdialog2=builder2.create();
return alertdialog2;
}
return null;

}

@Override
protected void onPrepareDialog(int id, Dialog dialog) {
// TODO Auto-generated method stub

switch (id) {
case CHECKBOX_ALERTDIALOG:
AlertDialog prepare_checkbox_dialog=(AlertDialog)dialog;
ListView list_checkbox=prepare_checkbox_dialog.getListView();
for(int i=0;i&lt;list_checkbox.getCount();i++){
list_checkbox.setItemChecked(i, false);
}
break;
case RADIOBUTTON_ALERTDIALOG:
AlertDialog prepare_radio_dialog=(AlertDialog)dialog;
ListView list_radio=prepare_radio_dialog.getListView();
for(int i=0;i&lt;list_radio.getCount();i++){
list_radio.setItemChecked(i, false);
}
break;

}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub

switch (v.getId()) {
case R.id.Button01:
//triggering the List alertdialog
showDialog(LIST_ALERTDIALOG);
break;
case R.id.Button02:
//triggering the checkbox alertdialog
showDialog(CHECKBOX_ALERTDIALOG);
break;
case R.id.Button03:
//triggering the radio alertdialog
showDialog(RADIOBUTTON_ALERTDIALOG);
break;

default:
break;
}

}
}</pre>
<p>I have used onPrepareDialog() method to change the selection state of the selected list items. Since Android manages the state of the selectable list, doing this is recommended.</p>
<h2>Step 5: Declare the activities in AndroidManifest.xml</h2>
<p>Your launcher activity is registered automatically. If you want to know more on Manifest file, please follow the post on <a title="How to write AndroidManifest.xml?" href="http://www.javabeat.net/2013/04/how-to-write-androidmanifest-xml/">Manifest</a>. Your AndroidManifest.xml has the below code.</p>
<pre class="brush: java; title: ; notranslate">

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;manifest xmlns:android=&quot;&lt;a href=&quot;http://schemas.android.com/apk/res/android&quot;&gt;

http://schemas.android.com/apk/res/android&lt;/a&gt;&quot;

package=&quot;my.app&quot;
android:versionCode=&quot;1&quot;
android:versionName=&quot;1.0&quot;&gt;
&lt;application android:icon=&quot;@drawable/icon&quot; android:label=&quot;@string/app_name&quot;&gt;
&lt;activity android:name=&quot;.AlertDialogDemo&quot;
android:label=&quot;@string/app_name&quot;&gt;
&lt;intent-filter&gt;
&lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
&lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
&lt;/intent-filter&gt;
&lt;/activity&gt;

&lt;/application&gt;
&lt;uses-sdk android:minSdkVersion=&quot;8&quot; /&gt;
&lt;/manifest&gt;</pre>
<h2>Step 6: Run your Project</h2>
<p>Select your project-&gt;Right click-&gt;Run As-&gt;Android Application. Your first activity pops up as below.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/4_alertout1.png"><img class="aligncenter size-full wp-image-7263" alt="4_alertout1" src="http://www.javabeat.net/wp-content/uploads/2013/05/4_alertout1.png" width="333" height="493" /></a></p>
<p>your activity is displaying three buttons. Click on the button &#8220;List&#8221; which displays your first AlertDialog with List of items &#8220;Green&#8221;, &#8220;Black&#8221; and &#8220;White&#8221; as below.</p>
<p>Select any one of the item from the list displayed inside your AlertDialog. I would be selecting &#8220;Black&#8221; from the list. You will get a Toast message showing the selected item as below.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/5_alertout3.png"><img class="aligncenter size-full wp-image-7264" alt="5_alertout3" src="http://www.javabeat.net/wp-content/uploads/2013/05/5_alertout3.png" width="330" height="492" /></a></p>
<p>Now click on the button &#8220;CheckBox&#8221;, It displays an AlertDialog with list having checkBoxes.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/6_alertout4.png"><img class="aligncenter size-full wp-image-7265" alt="6_alertout4" src="http://www.javabeat.net/wp-content/uploads/2013/05/6_alertout4.png" width="328" height="508" /></a></p>
<p>Select any number of items and click on &#8220;OK&#8221;. The checked items are displayed in the toast as below.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/6_alertout4.png"><img class="aligncenter size-full wp-image-7265" alt="6_alertout4" src="http://www.javabeat.net/wp-content/uploads/2013/05/6_alertout4.png" width="328" height="508" /></a></p>
<p>Click the button &#8220;RadioButton&#8221; which displays the Dialog with list having radioButtons.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/8_alertout6.png"><img class="aligncenter size-full wp-image-7267" alt="8_alertout6" src="http://www.javabeat.net/wp-content/uploads/2013/05/8_alertout6.png" width="297" height="459" /></a></p>
<p>select any item. The AlertDialog is closed and a toast is displayed showing the checked item name.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/9_alertout7.png"><img class="aligncenter size-full wp-image-7268" alt="9_alertout7" src="http://www.javabeat.net/wp-content/uploads/2013/05/9_alertout7.png" width="332" height="493" /></a></p>
<p>This is how you can create AlertDialog with different content areas. If you have any queries, please post it in comments section.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=q4tYsYnIBng:Ip2nOFj7EuM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=q4tYsYnIBng:Ip2nOFj7EuM:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=q4tYsYnIBng:Ip2nOFj7EuM:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=q4tYsYnIBng:Ip2nOFj7EuM:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=q4tYsYnIBng:Ip2nOFj7EuM:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=q4tYsYnIBng:Ip2nOFj7EuM:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=q4tYsYnIBng:Ip2nOFj7EuM:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=q4tYsYnIBng:Ip2nOFj7EuM:l6gmwiTKsz0"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=l6gmwiTKsz0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=q4tYsYnIBng:Ip2nOFj7EuM:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=q4tYsYnIBng:Ip2nOFj7EuM:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/JavabeatArticles/~4/q4tYsYnIBng" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;Connect to us ( &lt;a href="https://twitter.com/javabeat"&gt;@twitter&lt;/a&gt; | &lt;a href="https://www.facebook.com/javabeat.net"&gt;@facebook )&lt;/p&gt;&lt;p&gt;A Dialog is a small window that appears in front of the current Activity.  An AlertDialog is a Dialog which can have zero, one, two or three buttons. We have discussed about creating a simple AlertDialog in one of our earlier posts AlertDialog.  The previous tutorial on AlertDialog demonstrated how to create an AlertDialog which [...]&lt;/p&gt;</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.javabeat.net/2013/05/lists-checkboxes-radio-buttons-alertdialog-android/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">0</slash:comments><feedburner:origLink>http://www.javabeat.net/2013/05/lists-checkboxes-radio-buttons-alertdialog-android/</feedburner:origLink></item><item><title>How to create a DatePickerDialog in android?</title><link>http://feedproxy.google.com/~r/JavabeatArticles/~3/5QW3yKHaNFc/</link><category>Google Android</category><category>Android</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">krishnas</dc:creator><pubDate>Sun, 05 May 2013 13:02:09 PDT</pubDate><guid isPermaLink="false">http://www.javabeat.net/?p=7162</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>Android DatePicker dialog allows the user to select a date in year, month and day in a standardized format. To create this, you can use Android.app.DatePickerDialog Class. Android provides a DatePickerDialog class which creates a floating dialog. In this tutorial we would be discussing how to create DatePickerDialog in android and how to deal with it.  DatePickerDialog class is inherited from the AlertDialog class. It has some additional features along with the features of an AlertDialog class. The DatePickerDialog when invoked allows the user to pick a date from the DatePicker widget.</p>
<p>The datePickerDialog will disable the Active Activity until the user selects the date and click &#8220;set&#8221; button of the dialog.<br />
OnDateSetListener is the interface that has to be implemented with onDateSet callback to indicate the user is done filling in the date.</p>
<p>Let us now look at a simple example on how to create a DatePickerDialog in android. In this example we would be creating a DatePicker Dilaog on click of a button.</p>
<p><strong>Required layouts</strong></p>
<ul>
<li>main.xml</li>
</ul>
<p><strong>Required activities</strong></p>
<ul>
<li>DatePickerDialog.java</li>
</ul>
<p>Follow the below steps to create a DatePickerDialog</p>
<h2>Step 1: Set up the android development environment</h2>
<p>If you are not familiar with setting up an android environment, please refer to one of our previous posts <a title="How to set up android development environment?" href="http://www.javabeat.net/2013/04/android-development-environment/">Android Environment</a>. Note: This example is build using android 2.2</p>
<h2>Step 2: Create an android Project</h2>
<p>Create an android project named datepicker with the launcher activity DatepickerDialog.java. Please refer the post <a title="How to write a simple Android application?" href="http://www.javabeat.net/2013/04/simple-android-application/">Create a sample app</a> to know more on how to create a new android project. Now your project has an activity &#8220;DatePickerDialog.java&#8221; and a layout xml file &#8220;main.xml&#8221;. The complete project structure is as below.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/1_date1.png"><img class="aligncenter size-full wp-image-7233" alt="1_date1" src="http://www.javabeat.net/wp-content/uploads/2013/05/1_date1.png" width="225" height="291" /></a></p>
<h2>Step 3: Create a layout xml file</h2>
<p>In this example we would be using main.xml layout file, which gets created when you create an android project. The main.xml layout file has the below Views,</p>
<ul>
<li>TextView- Which has the text &#8220;DatePicker Demo&#8221;.</li>
<li>EditText- Which displays the current date when you run your project and then it displays the date that you set using datePickerDialog.</li>
<li>Button named &#8220;Change&#8221;- on click of this button, a DatePickerDialog appears which allows the user to change the date displayed in the edittext.</li>
</ul>
<p>Open the main.xml file and paste the below code.</p>
<pre class="brush: java; title: ; notranslate">&lt;RelativeLayout android:id=&quot;@+id/RelativeLayout01&quot;
android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;fill_parent&quot;
xmlns:android=&quot;&lt;a href=&quot;http://schemas.android.com/apk/res/android&quot;&gt;

http://schemas.android.com/apk/res/android&lt;/a&gt;&quot;&gt;

&lt;TextView android:id=&quot;@+id/TextView01&quot; android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot; android:text=&quot;DatePicker Demo&quot;
android:layout_marginTop=&quot;30dip&quot; android:layout_centerHorizontal=&quot;true&quot;
android:textStyle=&quot;bold&quot; android:textSize=&quot;20sp&quot;&gt;&lt;/TextView&gt;
&lt;EditText android:text=&quot;@+id/EditText01&quot; android:id=&quot;@+id/EditText01&quot;
android:layout_below=&quot;@id/TextView01&quot; android:layout_height=&quot;50dip&quot;
android:layout_width=&quot;150dip&quot; android:layout_marginTop=&quot;15dip&quot;&gt;&lt;/EditText&gt;
&lt;Button android:id=&quot;@+id/Button01&quot; android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot; android:layout_below=&quot;@+id/TextView01&quot;
android:layout_toRightOf=&quot;@+id/EditText01&quot; android:text=&quot;Change&quot;
android:layout_marginTop=&quot;15dip&quot;&gt;&lt;/Button&gt;
&lt;/RelativeLayout&gt;</pre>
<h2>Step 4: Create the required activities</h2>
<p>In this Example, the launcher activity &#8220;DatePickerDialog.java&#8221; is used. Open the activity and paste the below code.</p>
<pre class="brush: java; title: ; notranslate">package com.infy;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;

public class DatepickerDialog extends Activity{
/** Called when the activity is first created. */
EditText etDate;
Button change_date;
final int Date_Dialog_ID=0;
int cDay,cMonth,cYear; // this is the instances of the current date
Calendar cDate;
int sDay,sMonth,sYear; // this is the instances of the entered date
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etDate=(EditText)findViewById(R.id.EditText01);
change_date=(Button)findViewById(R.id.Button01);
change_date.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//triggers the DatePickerDialog
showDialog(Date_Dialog_ID);
}
});
//getting current date
cDate=Calendar.getInstance();
cDay=cDate.get(Calendar.DAY_OF_MONTH);
cMonth=cDate.get(Calendar.MONTH);
cYear=cDate.get(Calendar.YEAR);
//assigning the edittext with the current date in the beginning
sDay=cDay;
sMonth=cMonth;
sYear=cYear;
updateDateDisplay(sYear,sMonth,sDay);
}
@Override
protected Dialog onCreateDialog(int id) {

switch (id) {
case Date_Dialog_ID:
return new DatePickerDialog(this, onDateSet, cYear, cMonth,
cDay);
}
return null;
}

private void updateDateDisplay(int year,int month,int date) {
// TODO Auto-generated method stub
etDate.setText(date+&quot;-&quot;+(month+1)+&quot;-&quot;+year);
}
private OnDateSetListener onDateSet=new OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
System.out.println(&quot;2&quot;);
sYear=year;
sMonth=monthOfYear;
sDay=dayOfMonth;
updateDateDisplay(sYear,sMonth,sDay);
}
};
}</pre>
<p>As you can see in the above code, The DatePickerDialog is created as below</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<ol>
<li>a DatePickerDialog is defined using a member variable &#8220;Date_Dialog_ID&#8221;. This should be unique.</li>
<li>updateDateDisplay is called to set the Edittext with the date that we pass as parametes to this method.</li>
<li>The DatePickerDialog is created using the method &#8220;onCreateDialog(int id)&#8221;. you must provide a case for your dialog if you are using more than one Dailog. When showDialog(Date_Dialog_ID) method is called, it triggers onCreateDialog method which returns an appropriate Dialog instance.</li>
<li>In onCreateDialog method, we create an instance of DatePickerDialog.</li>
<li>OnDateSetListener interface has to be implemented with onDateSet callback, which is called when you select a date from the Dialog.</li>
</ol>
<h2>Step 5: Declare the activity in AndroidManifest.xml file</h2>
<p>Our launcher activity &#8220;DatePickerdialog.java&#8221; is declared automatically when we create our project. If you want to know more about Manifest file, please refer to the post <a title="How to write AndroidManifest.xml?" href="http://www.javabeat.net/2013/04/how-to-write-androidmanifest-xml/">Manifest</a>.</p>
<p>Our Androidmanifest.xml file has the below code.</p>
<pre class="brush: java; title: ; notranslate">

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;manifest xmlns:android=&quot;&lt;a href=&quot;http://schemas.android.com/apk/res/android&quot;&gt;http://schemas.android.com/apk/res/android&lt;/a&gt;&quot;
package=&quot;com.infy&quot;
android:versionCode=&quot;1&quot;
android:versionName=&quot;1.0&quot;&gt;
&lt;application android:icon=&quot;@drawable/icon&quot; android:label=&quot;@string/app_name&quot;&gt;
&lt;activity android:name=&quot;.DatepickerDialog&quot;
android:label=&quot;@string/app_name&quot;&gt;
&lt;intent-filter&gt;
&lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
&lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
&lt;/intent-filter&gt;
&lt;/activity&gt;

&lt;/application&gt;
&lt;uses-sdk android:minSdkVersion=&quot;8&quot; /&gt;
&lt;/manifest&gt;</pre>
<h2>Step 6: Run your application</h2>
<p>Select the project-&gt;right click-&gt;Run As-&gt;Android Application</p>
<p>Now your activity &#8220;DatePickeDialog.java&#8221; opens up as below.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/2_date2.png"><img class="aligncenter size-full wp-image-7234" alt="2_date2" src="http://www.javabeat.net/wp-content/uploads/2013/05/2_date2.png" width="475" height="492" /></a><br />
As you can see in the above screen, The Edittext has the current date in the beginning. Click on the button &#8220;Change&#8221; to fire a DatePickerDialog, which takes you to the below screen.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/3_date3.png"><img class="aligncenter size-full wp-image-7235" alt="3_date3" src="http://www.javabeat.net/wp-content/uploads/2013/05/3_date3.png" width="332" height="495" /></a></p>
<p>You can now see the displayed DatePickerDialog. Change the current date to new date of your choice. For example I would change the Date to 22 jan 2013. Click on Set button to set the new date to Edittext. Cancel button simply closes your Dialog without changing the Edittext contents. On click of &#8220;Set&#8221; button, the EditText contents changes as below.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/4_date4.png"><img class="aligncenter size-full wp-image-7236" alt="4_date4" src="http://www.javabeat.net/wp-content/uploads/2013/05/4_date4.png" width="436" height="493" /></a></p>
<p>Try clicking the &#8220;Change&#8221; button once again(second time), It displays the DatePickerDialog which shows the DatePicker Widget with the date chosen previous time (ie. 22 jan 2013) as below.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/5_date5.png"><img class="aligncenter size-full wp-image-7237" alt="5_date5" src="http://www.javabeat.net/wp-content/uploads/2013/05/5_date5.png" width="275" height="252" /></a></p>
<p>If you want to reuse the Dialog that you have created, you want to reset it to the current date each time the dialog is shown. To do this, use onPrepareDialog method of the Activity. Add the below onPrepareDialog method to your activity, to make your DatePicker display the current date each time it is shown.</p>
<pre class="brush: java; title: ; notranslate">@Override
protected void onPrepareDialog(int id, Dialog dialog) {
// TODO Auto-generated method stub
switch (id) {
case Date_Dialog_ID:
((DatePickerDialog)dialog).updateDate(cYear,cMonth,cDay);
break;

}
}</pre>
<p>This is how you can allow user to choose date using android DatePickerDialog. You can always add a DatePicker component to your layout that displays a DatePicker widget to the user. We would be discussing about DatePicker Widget in our upcomming Posts. If you have any doubts, please post it in the comment section.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=5QW3yKHaNFc:Kw0b5t9PpwM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=5QW3yKHaNFc:Kw0b5t9PpwM:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=5QW3yKHaNFc:Kw0b5t9PpwM:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=5QW3yKHaNFc:Kw0b5t9PpwM:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=5QW3yKHaNFc:Kw0b5t9PpwM:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=5QW3yKHaNFc:Kw0b5t9PpwM:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=5QW3yKHaNFc:Kw0b5t9PpwM:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=5QW3yKHaNFc:Kw0b5t9PpwM:l6gmwiTKsz0"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=l6gmwiTKsz0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=5QW3yKHaNFc:Kw0b5t9PpwM:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=5QW3yKHaNFc:Kw0b5t9PpwM:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/JavabeatArticles/~4/5QW3yKHaNFc" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;Connect to us ( &lt;a href="https://twitter.com/javabeat"&gt;@twitter&lt;/a&gt; | &lt;a href="https://www.facebook.com/javabeat.net"&gt;@facebook )&lt;/p&gt;&lt;p&gt;Android DatePicker dialog allows the user to select a date in year, month and day in a standardized format. To create this, you can use Android.app.DatePickerDialog Class. Android provides a DatePickerDialog class which creates a floating dialog. In this tutorial we would be discussing how to create DatePickerDialog in android and how to deal with [...]&lt;/p&gt;</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.javabeat.net/2013/05/datepickerdialog-android/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">0</slash:comments><feedburner:origLink>http://www.javabeat.net/2013/05/datepickerdialog-android/</feedburner:origLink></item><item><title>How to create Notifications in Android?</title><link>http://feedproxy.google.com/~r/JavabeatArticles/~3/n6nlrJgcqeA/</link><category>Google Android</category><category>Android</category><dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">krishnas</dc:creator><pubDate>Sat, 04 May 2013 12:56:42 PDT</pubDate><guid isPermaLink="false">http://www.javabeat.net/?p=7157</guid><content:encoded xmlns:content="http://purl.org/rss/1.0/modules/content/"><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>A <strong>Notification</strong> is a message displayed to the user outside of your application&#8217;s normal UI. It informs the user about the event that occured which requires attention. Examples for notification are alarm clocks, SMS indicators, birthday reminders etc. A service running in the background cannot intrude an Activity in the foreground to inform about any event since the Activity has highest priority, So Android provides a notification system which notifies the user in the form of a status bar icon which can steer to another activity, a toast message or any kind of hardware alert.</p>
<p><strong>Notifications</strong> can display once or any number of times. A notification in the status bar appears as an icon and some short text. When the status bar is pulled down, the user can see more notification details.<br />
Available notifications are,</p>
<ul>
<li>Flash Lights</li>
<li>Play sound</li>
<li>Status bar icons</li>
<li>Mobile phone vibrations</li>
</ul>
<h2>Steps to create a Notification in Android</h2>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/1_android-notifications.jpg"><img class="aligncenter size-full wp-image-7201" alt="1_android-notifications" src="http://www.javabeat.net/wp-content/uploads/2013/05/1_android-notifications.jpg" width="195" height="259" /></a></p>
<h2>Step 1: Creating a status bar notification</h2>
<p>In the below code we create a notification object.</p>
<pre class="brush: java; title: ; notranslate">Notification notification=new Notification(R.drawable.icon,&quot;Saanvi Birthday!&quot;,
System.currentTimeMillis());</pre>
<p>Here we have passed three parameters ,</p>
<ol>
<li>int icon-we set the icon to one of the system icons.</li>
<li>The ticker text displayed briefly in the status bar.</li>
<li>The time-to show the user when the notification occurred.</li>
</ol>
<h2>Step 2: Customizing expanded View</h2>
<pre class="brush: java; title: ; notranslate">notification.setLatestEventInfo(this, &quot;Reminder: Saanvi Birthday&quot;,
&quot;Today is your friend Saanvi's Birthday, please wish her&quot;, null);</pre>
<p>The above code is used to customize the notification&#8217;s expand view. The expanded view contains a notification title and a text(Notification message) that tells the user about the notification.</p>
<h2>Step 3: Passing a pendingIntent</h2>
<p><strong>PendingIntent</strong>: PendingIntent wraps the regular intent inside an object.This is the intent that can be fired at a later point of time. In our case the pendingIntent Intent(StartActivity) is fired when the user clicks on the Notification.</p>
<pre class="brush: java; title: ; notranslate">Intent intent=new Intent(getApplicationContext(), SecondActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
notification.setLatestEventInfo(this, &quot;Reminder: Saanvi Birthday&quot;,
&quot;Today is your friend Saanvi's Birthday, please wish her&quot;, pendingIntent);</pre>
<p>In the above code the activity &#8220;SecondActivity&#8221; is fired when the user clicks on the expanded view of the notification.</p>
<h2>Step 4: Triggering the Notification via NotificationManager</h2>
<p>NotificationManager is a system service. To create notification we use the NotificationManager class which can be retrieved from the Activity via the <strong>getSystemService()</strong> method. The <strong>NotificationManager</strong> has following methods,</p>
<ol>
<li>notify(int,Notification)
<ul>
<li>This is used to trigger a particular notification which is identified by the first parameter &#8220;Notification ID&#8221;,</li>
</ul>
</li>
<li>cancel(int)
<ul>
<li>This is used to cancel a particular notification by passing notification Id.</li>
</ul>
</li>
<li>cancelAll()
<ul>
<li>Used to cancel all notifications.</li>
</ul>
</li>
</ol>
<p>The notification is triggered as below</p>
<pre class="brush: java; title: ; notranslate">private static final int NOTIFICATION_ID=1;
final NotificationManager mgr=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
mgr.notify(NOTIFICATION_ID,notification);</pre>
<p>So far we have seen the steps to create a notification. Let us now look at a <span style="text-decoration: underline; color: #000080;"><strong>simple example of creating a notification in Android 2.2</strong></span></p>
<p>Required layouts:</p>
<ul>
<li>main.xml</li>
<li>second.xml</li>
</ul>
<p>Required Activities:</p>
<ul>
<li>Activity_Notification.java</li>
<li>SecondActivity.java(Which is fired when the user clicks on the notification&#8217;s expanded view)</li>
</ul>
<p><span style="text-decoration: underline;"><strong>Working of this example:</strong></span></p>
<p>The layout main.xml contains two buttons named &#8220;start&#8221; and &#8220;clear&#8221;. Start button to create a notification and clear buton to clear the notification. To see the created notification you have to swipe your finger down from the top of the screen. Inorder to respond to the notification, you have to touch it. Then the second activity &#8220;Second_Activity&#8221; is fired up. Follow the below steps to create the example.</p>
<p><strong>Step 1: Set up the android working environment</strong></p>
<p>To know about how to set up a working environment, please refer to the post <a title="How to set up android development environment?" href="http://www.javabeat.net/2013/04/android-development-environment/">Set up environment</a>.</p>
<p><strong>Step 2: Create an android project</strong></p>
<p>Create an android project named &#8220;NotificationDemo&#8221; with the activity &#8220;Activity_Notification.java&#8221;. To know how to create an android project, please refer to the post <a title="How to write a simple Android application?" href="http://www.javabeat.net/2013/04/simple-android-application/">create an android project</a>.</p>
<p><strong>Step 3: Create the required layouts</strong></p>
<p>As I said earlier I will be using two layouts main.xml and second.xml. If you have any doubts on how to create a layout xml file, please refer to one of our earlier posts <a title="How to create a Layout xml file in Android?" href="http://www.javabeat.net/2013/04/layouts-in-android/">Create a layout.</a></p>
<p>Open the main.xml which gets created automatically when you create your project, and paste the below code.</p>
<pre class="brush: java; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;RelativeLayout android:id=&quot;@+id/RelativeLayout01&quot;
android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;fill_parent&quot;
xmlns:android=&quot;&lt;a href=&quot;http://schemas.android.com/apk/res/android&quot;&gt;http://schemas.android.com/apk/res/android&lt;/a&gt;&quot;&gt;
&lt;TextView android:id=&quot;@+id/TextView01&quot; android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot; android:text=&quot;Notification Demo&quot;
android:layout_centerHorizontal=&quot;true&quot; android:layout_marginTop=&quot;30dip&quot;
android:textStyle=&quot;bold&quot;&gt;&lt;/TextView&gt;
&lt;Button android:layout_below=&quot;@id/TextView01&quot;
android:layout_width=&quot;wrap_content&quot; android:text=&quot;Start&quot; android:id=&quot;@+id/start&quot;
android:layout_centerHorizontal=&quot;true&quot; android:layout_height=&quot;50dip&quot;
android:layout_marginTop=&quot;20dip&quot;&gt;&lt;/Button&gt;
&lt;Button android:layout_width=&quot;wrap_content&quot; android:text=&quot;Clear&quot;
android:layout_below=&quot;@+id/start&quot; android:id=&quot;@+id/clear&quot;
android:layout_centerHorizontal=&quot;true&quot; android:layout_height=&quot;50dip&quot;
android:layout_marginTop=&quot;20dip&quot;&gt;&lt;/Button&gt;
&lt;/RelativeLayout&gt;</pre>
<p><span style="text-decoration: underline; color: #000080;"><strong>You can always pass the pendingIntent null if you are not willing to start a second activity on click of the notification.</strong></span> If you want to do something then you need to create second.xml layout file. I would be creating second.xml for your reference to show how a pendingIntent works.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>Open second.xml and paste the below code. Here I would just include a textview which just says you have clicked on notification.</p>
<pre class="brush: java; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;&lt;a href=&quot;http://schemas.android.com/apk/res/android&quot;&gt;

http://schemas.android.com/apk/res/android&lt;/a&gt;&quot;

android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot;&gt;
&lt;TextView android:id=&quot;@+id/TextView01&quot; android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot; android:text=&quot;You just clicked on a notification&quot;&gt;&lt;/TextView&gt;
&lt;/LinearLayout&gt;</pre>
<p><strong>Step 4: Create the required activities</strong></p>
<p>Here in this example I would be using the activity &#8220;Activity_Notification.java&#8221; and &#8220;SecondActivity.java&#8221;.</p>
<p>Open Activity_Notification.java and paste the below code.</p>
<pre class="brush: java; title: ; notranslate">package my.app;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Activity_Notification extends Activity {
Button start,clear;
Notification notification;
private static final int NOTIFICATION_ID=1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start=(Button)findViewById(R.id.start);
clear=(Button)findViewById(R.id.clear);

final NotificationManager mgr=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notification=new Notification(R.drawable.icon,&quot;Saanvi Birthday!&quot;, System.currentTimeMillis());
//Intent to start new activity on click of expanded view
Intent intent=new Intent(getApplicationContext(), SecondActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
notification.setLatestEventInfo(this, &quot;Reminder: Saanvi Birthday&quot;,
&quot;Today is your friend Saanvi's Birthday, please wish her&quot;, pendingIntent);

start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//to notify the user
mgr.notify(NOTIFICATION_ID,notification);
}
});
clear.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//to clear the notification
mgr.cancel(NOTIFICATION_ID);
}
});
}
}</pre>
<p>Create a new activity &#8220;SecondActivity.java&#8221;. If you are not familiar with creating a new activity, please go through the post <a title="How to create a new activity in Android?" href="http://www.javabeat.net/2013/04/create-new-activity-android/">Create a Activity.</a></p>
<pre class="brush: java; title: ; notranslate">package my.app;
import android.app.Activity;
import android.os.Bundle;
public class SecondActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
}
}</pre>
<p>If you want to do nothing on click of notification&#8217;s view, just pass the intent object as null to the PendingIntent method as below.</p>
<pre class="brush: java; title: ; notranslate">PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(), 0, null, 0);</pre>
<p>Please make a note that passing a pendingIntent object to setLatestEventInfo() method is a must failing which you will get a force close. If you don&#8217;t want to do anything on click of notification, just pass the intent object null.</p>
<p><strong>Step 5: Declare the Activities in manifest file</strong></p>
<p>Your first activity &#8220;Activity_Notification&#8221; would be automatically declared when you create your application. Declare the second activity &#8220;SecondActivity&#8221;. If you want to know more about AndroidManifest.xml, please refer to the post <a title="How to write AndroidManifest.xml?" href="http://www.javabeat.net/2013/04/how-to-write-androidmanifest-xml/">manifest</a>.</p>
<p>Now your manifest file contains the below code.</p>
<pre class="brush: java; title: ; notranslate">

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;manifest xmlns:android=&quot;&lt;a href=&quot;http://schemas.android.com/apk/res/android&quot;&gt;

http://schemas.android.com/apk/res/android&lt;/a&gt;&quot;

package=&quot;my.app&quot;
android:versionCode=&quot;1&quot;
android:versionName=&quot;1.0&quot;&gt;
&lt;application android:icon=&quot;@drawable/icon&quot; android:label=&quot;@string/app_name&quot;&gt;
&lt;activity android:name=&quot;.Activity_Notification&quot;
android:label=&quot;@string/app_name&quot;&gt;
&lt;intent-filter&gt;
&lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
&lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
&lt;/intent-filter&gt;
&lt;/activity&gt;

&lt;activity android:name=&quot;SecondActivity&quot;&gt;&lt;/activity&gt;
&lt;/application&gt;
&lt;uses-sdk android:minSdkVersion=&quot;8&quot; /&gt;
&lt;/manifest&gt;</pre>
<p><strong>Step 6: Run your application</strong></p>
<p>Select your project -&gt;right click-&gt;Run As-&gt;Android application</p>
<p>Now your first activity gets fired up as below.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/2_notify1.png"><img class="aligncenter size-full wp-image-7202" alt="2_notify1" src="http://www.javabeat.net/wp-content/uploads/2013/05/2_notify1.png" width="445" height="495" /></a></p>
<p>Click the highlighted &#8220;Start&#8221; button to raise the notification. Your notification fires up as below.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/3_notify_2.png"><img class="aligncenter size-full wp-image-7203" alt="3_notify_2" src="http://www.javabeat.net/wp-content/uploads/2013/05/3_notify_2.png" width="502" height="494" /></a></p>
<p>Swipe your finger down from the top of the screen. You can now see your notification&#8217;s expanded view as below.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/4_notify3.png"><img class="aligncenter size-full wp-image-7204" alt="4_notify3" src="http://www.javabeat.net/wp-content/uploads/2013/05/4_notify3.png" width="516" height="524" /></a></p>
<p><span style="text-decoration: underline; color: #000080;"><strong>Android provides you a default &#8221;Clear&#8221; button to clear the notification or you can clear it programmatically using cancel() method of Notification Manager.</strong></span> Click on the notification to start a new activity SecondActivity.java&#8221;.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/5_notify4.png"><img class="aligncenter size-full wp-image-7205" alt="5_notify4" src="http://www.javabeat.net/wp-content/uploads/2013/05/5_notify4.png" width="331" height="492" /></a></p>
<p>If you don&#8217;t want to start the new activity just click the &#8220;Clear&#8221; button in the first image, which clears the Notification as below.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2013/05/6_notify5.png"><img class="aligncenter size-full wp-image-7206" alt="6_notify5" src="http://www.javabeat.net/wp-content/uploads/2013/05/6_notify5.png" width="332" height="494" /></a><br />
This is how you can raise and clear the notifications in android. If you have any issues regarding this article, please post it in comment section. I hope this article would have provided more detailed explanation on how to create a notification using the <strong>NotificationManager API </strong>and create a sample application. If you have any questions, please post it in the comments section.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=n6nlrJgcqeA:N3MYY2q-wgM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=n6nlrJgcqeA:N3MYY2q-wgM:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=n6nlrJgcqeA:N3MYY2q-wgM:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=n6nlrJgcqeA:N3MYY2q-wgM:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=7Q72WNTAKBA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=n6nlrJgcqeA:N3MYY2q-wgM:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=n6nlrJgcqeA:N3MYY2q-wgM:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=n6nlrJgcqeA:N3MYY2q-wgM:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=n6nlrJgcqeA:N3MYY2q-wgM:l6gmwiTKsz0"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?d=l6gmwiTKsz0" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/JavabeatArticles?a=n6nlrJgcqeA:N3MYY2q-wgM:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/JavabeatArticles?i=n6nlrJgcqeA:N3MYY2q-wgM:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/JavabeatArticles/~4/n6nlrJgcqeA" height="1" width="1"/>]]></content:encoded><description>&lt;p&gt;Connect to us ( &lt;a href="https://twitter.com/javabeat"&gt;@twitter&lt;/a&gt; | &lt;a href="https://www.facebook.com/javabeat.net"&gt;@facebook )&lt;/p&gt;&lt;p&gt;A Notification is a message displayed to the user outside of your application&amp;#8217;s normal UI. It informs the user about the event that occured which requires attention. Examples for notification are alarm clocks, SMS indicators, birthday reminders etc. A service running in the background cannot intrude an Activity in the foreground to inform about any [...]&lt;/p&gt;</description><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://www.javabeat.net/2013/05/notifications-android/feed/</wfw:commentRss><slash:comments xmlns:slash="http://purl.org/rss/1.0/modules/slash/">0</slash:comments><feedburner:origLink>http://www.javabeat.net/2013/05/notifications-android/</feedburner:origLink></item></channel></rss>
