<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Advancing Backwards &#187; Java</title>
	<atom:link href="http://advback.com/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://advback.com</link>
	<description>Boldly going in the wrong direction since 2008</description>
	<lastBuildDate>Fri, 16 Mar 2012 02:31:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Access Android system services outside of an activity</title>
		<link>http://advback.com/android/access-android-system-services-outside-of-an-activity/</link>
		<comments>http://advback.com/android/access-android-system-services-outside-of-an-activity/#comments</comments>
		<pubDate>Fri, 16 Mar 2012 02:31:13 +0000</pubDate>
		<dc:creator>Jeremy Cerise</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Mobile Programming]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[context]]></category>
		<category><![CDATA[LocationListener]]></category>

		<guid isPermaLink="false">http://advback.com/?p=213</guid>
		<description><![CDATA[So, its been quite some time since I&#8217;ve posted anything here, so its time to break the silence. And, what better way to do so than by posting a small snippet of Android code that tripped me up? Todays topic: Accessing and setting Android system services outside of an activity. This is a small thing [...]]]></description>
			<content:encoded><![CDATA[<p>So, its been quite some time since I&#8217;ve posted anything here, so its time to break the silence. And, what better way to do so than by posting a small snippet of Android code that tripped me up? Todays topic: Accessing and setting Android system services outside of an activity. This is a small thing that many may already know, but in my tradition of documenting small things that trip me up, Im going to write about it anyways.</p>
<p><span id="more-213"></span></p>
<p>So, the problem was thus: I have my main activity that checks for the existence of a location provider before it transfers the user to a different activity. After it is satisfied that the GPS is in fact enabled, it continuously grabs a location from it until the accuracy is less than or equal to ten feet. Once both of these conditions are met, it passes control to the next activity. Overall, its a very simple task, but I wanted to keep my main activity from having to implement the LocationListener interface to accomplish it. Not only do I feel its a good separation of concerns to put the LocationListener onto its own class, but it also keeps the code for the main activity much more simple. Which is always good.</p>
<p>So, I created a new class that I called LocationProvider. It implemented the LocationListener interface, and in the constructor set up a new LocationManager, told it to start updating itself, and the created a new Location from the updates. I also added a few methods to the class to cycle the location updates until the given accuracy was achieved. Simple enough. But, a problem arose. I could not call the method getSystemService() without an activity context, meaning my entire class scheme would not work.</p>
<p>But, a simple problem in this case, luckily required a very simple solution: pass the context from the main activity into the LocatoinProvider object in the constructor, and then call context.getSystemService(). Beautiful, works like a charm. My class now knows just enough to initialize the GPS, refine the accuracy, and then spit the latitude and longitude back to the main activity.</p>
<p>For the curious, and to further illustrate my point, heres the relevant code from my project:</p>
<pre name="code" class="java">
// Make sure the GPS fix is sufficiently accurate
// Set up a progress spinner to display while an
// accurate fix is achieved.
spinnerDialog = ProgressDialog.show(Pinpoint.this, "",
		"Waiting for accurate (> 10 meters)" +
                "GPS coordinates...Please wait. ", true);

//Create a new instance of LocationProvider,
//which implements LocationListener
//Pass in the current activity context, so
//LocationProvider can access system services
locProvider = new LocationProvider(Pinpoint.this);

// Thread handles refreshing the GPS until desired
// accuracy is achieved
new Thread(new Runnable() {
          public void run() {
          locProvider.getCurrentLocation();
          spinnerDialog.dismiss();
          return;
     }
}).start();

//Once the GPS has sufficient accuracy,
//Create an intent to launch the new location activity
Intent createLocationIntent = new Intent(
     Pinpoint.this, CreateLocation.class);
startActivity(createLocationIntent);
</pre>
<p>So, there you have it, a dead simple approach to separate concerns in your Android project.</p>


<div class="shr-bookmarks shr-bookmarks-expand shr-bookmarks-center shr-bookmarks-bg-enjoy">
<ul class="socials">
		<li class="shr-digg">
			<a href="http://digg.com/submit?phase=2&amp;url=http://advback.com/android/access-android-system-services-outside-of-an-activity/&amp;title=Access+Android+system+services+outside+of+an+activity" rel="nofollow" class="external" title="Digg this!" onclick="pageTracker._trackPageview('/outgoing/digg.com/submit?phase=2_amp_url=http_//advback.com/android/access-android-system-services-outside-of-an-activity/_amp_title=Access+Android+system+services+outside+of+an+activity&amp;referer=');">Digg this!</a>
		</li>
		<li class="shr-facebook">
			<a href="http://www.facebook.com/share.php?v=4&amp;src=bm&amp;u=http://advback.com/android/access-android-system-services-outside-of-an-activity/&amp;t=Access+Android+system+services+outside+of+an+activity" rel="nofollow" class="external" title="Share this on Facebook" onclick="pageTracker._trackPageview('/outgoing/www.facebook.com/share.php?v=4_amp_src=bm_amp_u=http_//advback.com/android/access-android-system-services-outside-of-an-activity/_amp_t=Access+Android+system+services+outside+of+an+activity&amp;referer=');">Share this on Facebook</a>
		</li>
		<li class="shr-googlebuzz">
			<a href="http://www.google.com/buzz/post?url=http://advback.com/android/access-android-system-services-outside-of-an-activity/&amp;imageurl=" rel="nofollow" class="external" title="Post on Google Buzz" onclick="pageTracker._trackPageview('/outgoing/www.google.com/buzz/post?url=http_//advback.com/android/access-android-system-services-outside-of-an-activity/_amp_imageurl=&amp;referer=');">Post on Google Buzz</a>
		</li>
		<li class="shr-reddit">
			<a href="http://reddit.com/submit?url=http://advback.com/android/access-android-system-services-outside-of-an-activity/&amp;title=Access+Android+system+services+outside+of+an+activity" rel="nofollow" class="external" title="Share this on Reddit" onclick="pageTracker._trackPageview('/outgoing/reddit.com/submit?url=http_//advback.com/android/access-android-system-services-outside-of-an-activity/_amp_title=Access+Android+system+services+outside+of+an+activity&amp;referer=');">Share this on Reddit</a>
		</li>
		<li class="shr-twitter">
			<a href="http://twitter.com/home?status=Access+Android+system+services+outside+of+an+activity+-+http://tinyurl.com/887j4u6&amp;source=shareaholic" rel="nofollow" class="external" title="Tweet This!" onclick="pageTracker._trackPageview('/outgoing/twitter.com/home?status=Access+Android+system+services+outside+of+an+activity+-+http_//tinyurl.com/887j4u6_amp_source=shareaholic&amp;referer=');">Tweet This!</a>
		</li>
</ul>
<div style="clear:both;"></div>
</div>

]]></content:encoded>
			<wfw:commentRss>http://advback.com/android/access-android-system-services-outside-of-an-activity/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ProgressDialog and You: The Basics &#8211; Android</title>
		<link>http://advback.com/android/progressdialog-and-you-the-basics-android/</link>
		<comments>http://advback.com/android/progressdialog-and-you-the-basics-android/#comments</comments>
		<pubDate>Sat, 30 Oct 2010 07:04:51 +0000</pubDate>
		<dc:creator>Jeremy Cerise</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Mobile Programming]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[ProgressDialog]]></category>
		<category><![CDATA[threading]]></category>
		<category><![CDATA[threads]]></category>

		<guid isPermaLink="false">http://advback.com/?p=195</guid>
		<description><![CDATA[So, after a rather long absence from Android, I decided to dive back in and start tweaking an app I started a while back. This particular app uses the GPS to store a location in a database. The problem was, the app would sometimes try and store the location before the GPS was even ready, [...]]]></description>
			<content:encoded><![CDATA[<p>So, after a rather long absence from Android, I decided to dive back in and start tweaking an app I started a while back. This particular app uses the GPS to store a location in a database. The problem was, the app would sometimes try and store the location before the GPS was even ready, resulting in coordinates of 0, 0. At the same time, I also wanted the GPS reading to be as accurate as possible before it was stored in the database. Accuracy of +/- 80 feet is not so useful in the long run.</p>
<p>After some thought on how best to accomplish this without pissing off the user (nobody likes an application that seems to hang, even if there is something ticking in the background), I settled on displaying a <a href="http://developer.android.com/reference/android/app/ProgressDialog.html" onclick="pageTracker._trackPageview('/outgoing/developer.android.com/reference/android/app/ProgressDialog.html?referer=');">ProgressDialog</a> to let the user that something is indeed happening, and they can continue once its done. </p>
<p><span id="more-195"></span></p>
<p>So, after reading up on this particular dialog, I found that there are two flavors: indeterminate and non-indeterminate. The non-indeterminate variety shows a progress bar, and can be handy when you have something measurable to load. The indeterminate variety simply shows a spinner with a message, and is therefore good for non-measurable load times. For my situation, the indeterminate variety is fine.</p>
<p>So, choice in hand, I set out to write some code. My first draft looked like this:</p>
<pre name="code" class="java">
ProgressDialog spinnerDialog = ProgressDialog.show(
	Placeholder.this, "",
	"Waiting for accurate (> 10 meters) GPS coordinates...Please wait. ", true);
refineGPSAccuracy();
spinnerDialog.dismiss();
</pre>
<p>The ProgressDialog takes four arguments: a context, a title (which Ive left blank), the message to be displayed, and whether or not the spinner is indeterminate. After creating one of these, I call my method, and once thats done, dismiss the spinner. Pretty simple, right? Well, yes, but the problem is that the code as we have it won&#8217;t work. If you tried to run this, your method would fire off, the app would hang until the method returned, and your spinner would be nowhere to be seen.</p>
<p>Why is this? Well, the quick answer is, calling the method is blocking the UI thread, meaning that your nice dialog will not show up until the method has returned, at which point we dismiss the dialog. So, how do we get around this? Create a thread for the method to run in. This way, it won&#8217;t block the main UI thread, and our spinner will be displayed in all its glory.</p>
<p>Version 2 of my code looked like this: </p>
<pre name="code" class="java">
ProgressDialog spinnerDialog = ProgressDialog.show(
	Placeholder.this, "",
	"Waiting for accurate (> 10 meters) GPS coordinates...Please wait. ", true);
new Thread(new Runnable() {
	public void run() {
		refineGPSAccuracy();
		spinnerDialog.dismiss();
		return;
	}
}).start();
</pre>
<p>So, essentially, all we&#8217;re doing is setting the actual logic aside into its own thread, and once that method returns, dismissing the spinner (as the work is done, and the user should be able to interact with the app again), and killing the thread. Simple as that. </p>


<div class="shr-bookmarks shr-bookmarks-expand shr-bookmarks-center shr-bookmarks-bg-enjoy">
<ul class="socials">
		<li class="shr-digg">
			<a href="http://digg.com/submit?phase=2&amp;url=http://advback.com/android/progressdialog-and-you-the-basics-android/&amp;title=ProgressDialog+and+You%3A+The+Basics+-+Android" rel="nofollow" class="external" title="Digg this!" onclick="pageTracker._trackPageview('/outgoing/digg.com/submit?phase=2_amp_url=http_//advback.com/android/progressdialog-and-you-the-basics-android/_amp_title=ProgressDialog+and+You_3A+The+Basics+-+Android&amp;referer=');">Digg this!</a>
		</li>
		<li class="shr-facebook">
			<a href="http://www.facebook.com/share.php?v=4&amp;src=bm&amp;u=http://advback.com/android/progressdialog-and-you-the-basics-android/&amp;t=ProgressDialog+and+You%3A+The+Basics+-+Android" rel="nofollow" class="external" title="Share this on Facebook" onclick="pageTracker._trackPageview('/outgoing/www.facebook.com/share.php?v=4_amp_src=bm_amp_u=http_//advback.com/android/progressdialog-and-you-the-basics-android/_amp_t=ProgressDialog+and+You_3A+The+Basics+-+Android&amp;referer=');">Share this on Facebook</a>
		</li>
		<li class="shr-googlebuzz">
			<a href="http://www.google.com/buzz/post?url=http://advback.com/android/progressdialog-and-you-the-basics-android/&amp;imageurl=" rel="nofollow" class="external" title="Post on Google Buzz" onclick="pageTracker._trackPageview('/outgoing/www.google.com/buzz/post?url=http_//advback.com/android/progressdialog-and-you-the-basics-android/_amp_imageurl=&amp;referer=');">Post on Google Buzz</a>
		</li>
		<li class="shr-reddit">
			<a href="http://reddit.com/submit?url=http://advback.com/android/progressdialog-and-you-the-basics-android/&amp;title=ProgressDialog+and+You%3A+The+Basics+-+Android" rel="nofollow" class="external" title="Share this on Reddit" onclick="pageTracker._trackPageview('/outgoing/reddit.com/submit?url=http_//advback.com/android/progressdialog-and-you-the-basics-android/_amp_title=ProgressDialog+and+You_3A+The+Basics+-+Android&amp;referer=');">Share this on Reddit</a>
		</li>
		<li class="shr-twitter">
			<a href="http://twitter.com/home?status=ProgressDialog+and+You%3A+The+Basics+-+Android+-+http://tinyurl.com/2e8rgbn&amp;source=shareaholic" rel="nofollow" class="external" title="Tweet This!" onclick="pageTracker._trackPageview('/outgoing/twitter.com/home?status=ProgressDialog+and+You_3A+The+Basics+-+Android+-+http_//tinyurl.com/2e8rgbn_amp_source=shareaholic&amp;referer=');">Tweet This!</a>
		</li>
</ul>
<div style="clear:both;"></div>
</div>

]]></content:encoded>
			<wfw:commentRss>http://advback.com/android/progressdialog-and-you-the-basics-android/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Working with App widgets &#8211; Android</title>
		<link>http://advback.com/android/working-with-app-widgets-android/</link>
		<comments>http://advback.com/android/working-with-app-widgets-android/#comments</comments>
		<pubDate>Thu, 29 Apr 2010 06:57:41 +0000</pubDate>
		<dc:creator>Jeremy Cerise</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Mobile Programming]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[App Widget]]></category>
		<category><![CDATA[Homescreen widget]]></category>
		<category><![CDATA[RemoteViews]]></category>
		<category><![CDATA[Widget]]></category>

		<guid isPermaLink="false">http://advback.com/?p=128</guid>
		<description><![CDATA[One thing I&#8217;ve been grappling with recently is how to get home screen applications widgets to work for my application. There is a decent tutorial in the Android developer documents about the subject (located here), but it doesn&#8217;t really go into too much detail on how to make your widgets interactive. Sure, it shows you [...]]]></description>
			<content:encoded><![CDATA[<p>One thing I&#8217;ve been grappling with recently is how to get home screen applications widgets to work for my application. There is a decent tutorial in the Android developer documents about the subject (located <a title="Android App Widgets" href="http://developer.android.com/guide/topics/appwidgets/index.html" onclick="pageTracker._trackPageview('/outgoing/developer.android.com/guide/topics/appwidgets/index.html?referer=');">here</a>), but it doesn&#8217;t really go into too much detail on how to make your widgets interactive. Sure, it shows you how to set up an OnClickListener on an element of your widget to load an activity from elsewhere, but what if you want the widget to do something more, like redraw itself with a new image when its clicked? This seems pretty simple, but to be honest, it took me a lot of fiddling to get it to happen.</p>
<p><span id="more-128"></span></p>
<p>The first obvious thing we need is an idea of what our widget is going to do. In my case, my app widget toggles on the camera LEDs (on the Moto Droid/Milestone).  Not too complicated. So, what do we want to happen when we push the widget? Well, the LED&#8217;s need to either come on or turn off, and also the little flashlight icon should switch between lit and unlit respectively.</p>
<p>So, with this in mind, now we need to actually set up our application to use a widget. For brevitys sake, Ill let the good folks over at google cover this topic, as they already have a good write-up/tutorial on how its all done (written much better than I could too). The link to the Widget tutorial is <a title="Android App Widgets" href="http://developer.android.com/guide/topics/appwidgets/index.html" onclick="pageTracker._trackPageview('/outgoing/developer.android.com/guide/topics/appwidgets/index.html?referer=');">here</a>.</p>
<p>Once you have your application set up to support a widget, the next step we need to do is to hook our widget up to our existing code to allow the user to interact with our main application from their home screen. Lets first focus on calling our method to toggle the lights on and off. We need to somehow get our widget to register when the user clicks on it. Since app widgets are slightly different than other widgets within Android, we cannot just attach an onClickListener to our widget and go. We need to instead use a RemoteViews object. The Android documentation defines a RemoteViews as a &#8220;class that describes a view hierarchy that can be displayed in  another process&#8221;.</p>
<pre name="code" class="java">
private RemoteViews views = new RemoteViews("com.test.widgetTest", R.layout.widget);
</pre>
<p>Our RemoteViews object takes two arguments, the package name, and the layout to use in the object. This object will allow us to connect an onClickListener to our widget. Before we do that however, we need to specify a new intent for our onClickListener to start. We will also need to create a PendingIntent to store our new intent.</p>
<pre name="code" class="java">
Intent intent = new Intent(context, Widget.class);
intent.setAction(ACTION_WIDGET_RECEIVER);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
					0, intent, 0);
</pre>
<p>For our intent, we need to supply a context and a target activity. In this case, the target activity is the widget class, the same class we are currently working in. Why we are doing this will be explained in a moment. We also need to set an action for the intent, and in this case we have chosen ACTION_WIDGET_RECEIVER, which we will use in the onReceive() method when a user clicks on the widget. Finally, we set up our pending intent with the intent we just created, but we set it to broadcast, rather than start a new activity.</p>
</p>
<p>The next step we need to take is to set up our onClickReceiver using our RemoteViews object.</p>
<pre name="code" class="java">
views.setOnClickPendingIntent(R.id.toggle_button_widget, pendingIntent);
</pre>
<p>We use the setOnClickPendingIntent() method to set our widget to use our pending intent whenever the user clicks on it. For the purposes of this tutorial, I have used an ImageView in my widget layout called toggle_button_widget.</p>
<p>So, now that we have our onClick all set up, lets make it do something when a user clicks on it. As I mentioned earlier, our intent broadcasts to our widget class. What this means is that whenever the widget is clicked on, it sends a broadcast to itself, which automatically triggers the widgets onReceive() method. It is in the onReceive() method where we will do the appropriate action (in this case toggle the lights on or off).</p>
<p>Earlier, we set the action of our intent to ACTION_WIDGET_RECEIVER. One of the first things we want to do is check to see which action was broadcast in our intent. This can be accomplished using a simple if statement (or possibly a switch if you have multiple cases):</p>
<pre name="code" class="java">
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
}
</pre>
<p>By using this sort of check at the start of our method, we can handle multiple types of broadcasts if need be, but for our example we&#8217;ll only be using one. Once we are sure that the action that was sent is the action we want, we can then set up our logic to flip the lights on or off. This might look something like this:</p>
<pre name="code" class="java">
@Override
public void onReceive(Context context, Intent intent) {
     if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
          try {
               led = new FlashlightLED();
               led.toggleLight();
          }
     }
     super.onReceive(context, intent);
}
</pre>
<p>Thats all we need to do to get our widget to toggle a value in our main application! Pretty simple, whenever the widget is clicked, it calls its own onReceive() and then runs the appropriate logic. But while thats all well and good, when our light is on, the image on the widget is the same as if it were off, which can be confusing. The next thing we want to do is to change the image on the widget according to the state of our light.</p>
<p>I&#8217;m going to put a disclaimer in at this point: The following method, while it will work fine, is probably not the best way to go about this, but it is, at the time of this writing, the only way I have found to accomplish this. Please chime in in the comments if you know of a better way.</p>
<p>What we basically need to do is to change the image that is stored in our ImageView, toggle_button_widget, and then update the widget to reflect our new changes. Since we have our widget layout stored in a RemoteViews object, the first step, physically changing the image, is fairly easy:</p>
<pre name="code" class="java">
views.setImageViewResource(R.id.toggle_button_widget, R.drawable.flashlight_lit);
</pre>
<p>All we are doing here is finding the ImageView in our RemoteViews object and updating its value. Next, we need to update the widget to reflect our changes.  To do this, we create a ComponentName object, which takes the context, and the class, in our case our widget class. We can then use this ComponentName object, along with our RemoteViews object to update the widget:</p>
<pre name="code" class="java">
ComponentName cn = new ComponentName(context, Widget.class);
AppWidgetManager.getInstance(context).updateAppWidget(cn, views);
</pre>
<p>It should be noted here that if the user has more than one instance of the widget active on their screen, this will update all of them simultaneously. This makes sense for my widget, as if the light is on, all the instances of the widget should reflect this fact. </p>
<p>So, now that we can update the image each time the light is toggled, our onReceive() method could look something like this:</p>
<pre name="code" class="java">
@Override
public void onReceive(Context context, Intent intent) {
     if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
          try {
               led = new FlashlightLED();
               led.toggleLight();
               if (led.isEnabled()){
                    views.setImageViewResource(R.id.toggle_button_widget, R.drawable.flashlight_lit);
                    ComponentName cn = new ComponentName(context, Widget.class);
                    AppWidgetManager.getInstance(context).updateAppWidget(cn, views);
               }else{
                    views.setImageViewResource(R.id.toggle_button_widget, R.drawable.flashlight_off);
                    ComponentName cn = new ComponentName(context, Widget.class);
                    AppWidgetManager.getInstance(context).updateAppWidget(cn, views);
               }
          }
     }
     super.onReceive(context, intent);
}
</pre>
<p>And the full code for our widget might look something like this:</p>
<pre name="code" class="java">
public class Widget extends AppWidgetProvider {
     private static final String ACTION_WIDGET_RECEIVER = "ActionRecieverWidget";
     private RemoteViews views = new RemoteViews("com.test.widgetTest",
			R.layout.widget);

     public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		final int N = appWidgetIds.length;

		// Perform this loop procedure for each App Widget that belongs to this
		// provider
		for (int i = 0; i < N; i++) {
            int appWidgetId = appWidgetIds[i];
            Intent intent = new Intent(context, Widget.class);
            intent.setAction(ACTION_WIDGET_RECEIVER);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

            views.setOnClickPendingIntent(R.id.toggle_button_widget, pendingIntent);

            // Tell the AppWidgetManager to perform an update on the current App
           // Widget
			appWidgetManager.updateAppWidget(appWidgetId, views);
     }

     @Override
     public void onReceive(Context context, Intent intent) {
          if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
               try {
                    led = new FlashlightLED();
                    led.toggleLight();
                    if (led.isEnabled()){
                         views.setImageViewResource(R.id.toggle_button_widget, R.drawable.flashlight_lit);
                         ComponentName cn = new ComponentName(context, Widget.class);
                         AppWidgetManager.getInstance(context).updateAppWidget(cn, views);
                    }else{
                         views.setImageViewResource(R.id.toggle_button_widget, R.drawable.flashlight_off);
                         ComponentName cn = new ComponentName(context, Widget.class);
                         AppWidgetManager.getInstance(context).updateAppWidget(cn, views);
                    }
               }
          }
          super.onReceive(context, intent);
     }
}
</pre>
<p>And there you have it! A simple, lightly interactive homescreen app widget for Android.</p>


<div class="shr-bookmarks shr-bookmarks-expand shr-bookmarks-center shr-bookmarks-bg-enjoy">
<ul class="socials">
		<li class="shr-digg">
			<a href="http://digg.com/submit?phase=2&amp;url=http://advback.com/android/working-with-app-widgets-android/&amp;title=Working+with+App+widgets+-+Android" rel="nofollow" class="external" title="Digg this!" onclick="pageTracker._trackPageview('/outgoing/digg.com/submit?phase=2_amp_url=http_//advback.com/android/working-with-app-widgets-android/_amp_title=Working+with+App+widgets+-+Android&amp;referer=');">Digg this!</a>
		</li>
		<li class="shr-facebook">
			<a href="http://www.facebook.com/share.php?v=4&amp;src=bm&amp;u=http://advback.com/android/working-with-app-widgets-android/&amp;t=Working+with+App+widgets+-+Android" rel="nofollow" class="external" title="Share this on Facebook" onclick="pageTracker._trackPageview('/outgoing/www.facebook.com/share.php?v=4_amp_src=bm_amp_u=http_//advback.com/android/working-with-app-widgets-android/_amp_t=Working+with+App+widgets+-+Android&amp;referer=');">Share this on Facebook</a>
		</li>
		<li class="shr-googlebuzz">
			<a href="http://www.google.com/buzz/post?url=http://advback.com/android/working-with-app-widgets-android/&amp;imageurl=" rel="nofollow" class="external" title="Post on Google Buzz" onclick="pageTracker._trackPageview('/outgoing/www.google.com/buzz/post?url=http_//advback.com/android/working-with-app-widgets-android/_amp_imageurl=&amp;referer=');">Post on Google Buzz</a>
		</li>
		<li class="shr-reddit">
			<a href="http://reddit.com/submit?url=http://advback.com/android/working-with-app-widgets-android/&amp;title=Working+with+App+widgets+-+Android" rel="nofollow" class="external" title="Share this on Reddit" onclick="pageTracker._trackPageview('/outgoing/reddit.com/submit?url=http_//advback.com/android/working-with-app-widgets-android/_amp_title=Working+with+App+widgets+-+Android&amp;referer=');">Share this on Reddit</a>
		</li>
		<li class="shr-twitter">
			<a href="http://twitter.com/home?status=Working+with+App+widgets+-+Android+-+http://tinyurl.com/2bwdorj&amp;source=shareaholic" rel="nofollow" class="external" title="Tweet This!" onclick="pageTracker._trackPageview('/outgoing/twitter.com/home?status=Working+with+App+widgets+-+Android+-+http_//tinyurl.com/2bwdorj_amp_source=shareaholic&amp;referer=');">Tweet This!</a>
		</li>
</ul>
<div style="clear:both;"></div>
</div>

]]></content:encoded>
			<wfw:commentRss>http://advback.com/android/working-with-app-widgets-android/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>ListPreference bug? &#8211; Android</title>
		<link>http://advback.com/android/108/</link>
		<comments>http://advback.com/android/108/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 22:29:01 +0000</pubDate>
		<dc:creator>Jeremy Cerise</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Mobile Programming]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[bug report]]></category>
		<category><![CDATA[bugs]]></category>

		<guid isPermaLink="false">http://advback.com/?p=108</guid>
		<description><![CDATA[In my ongoing quest to write about little known or poorly documented features of Android, I stumbled across something this morning that I feel needs a little bit more exposure, as it frustrated me for quite a while trying to figure it out. The set up: I was trying to include into my application a [...]]]></description>
			<content:encoded><![CDATA[<p>In my ongoing quest to write about little known or poorly documented features of Android, I stumbled across something this morning that I feel needs a little bit more exposure, as it frustrated me for quite a while trying to figure it out.</p>
<p><span id="more-108"></span></p>
<p>The set up: I was trying to include into my application a ListPreference object, which basically just creates a dialog with a list of selectable items in it for use with a PreferenceActivity. Quite handy, particularly if you need to let the user select from more than one option, say, for an update timer or similar.</p>
<p>So, I set up my preferences page thusly:</p>
<pre name="code" class="xml">
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference
  	android:key="set_timer"
  	android:title="@string/timer_title"
  	android:summary="@string/timer_summary"
  	android:entries="@array/entries"
  	android:entryValues="@array/entry_values" />
</PreferenceScreen>
</pre>
<p>Nothing fancy here, except to note that the ListPreference takes a couple additional arguments, namely entries, which is an array of human readable values, and entryValues, which is an array of data values that each correspond to the values in entries. </p>
<p>Next, I set up a PreferenceActivity to create my preferences page:</p>
<pre name="code" class="java">
public class Prefs extends PreferenceActivity {

	private static final String OPT_TIMER = "set_timer";
	private static final String OPT_TIMER_DEF = "5";

	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.settings);
	}

	public static String getTimer(Context context) {
		return PreferenceManager.getDefaultSharedPreferences(context)
		.getString(OPT_TIMER, OPT_TIMER_DEF);
	}

}
</pre>
<p>Okay, at this point, we should be all set up to start using our preferences&#8230;or at least we would be if there weren&#8217;t a bit of bug with the current release of Android. If you were to run this code right now, with your two arrays, entries and entryValues set up in a resource file, chances are you would get a null pointer exception. How can that be possible though, since technically, nothing we&#8217;ve written is even doing anything? Its all relying on the underlying Android framework at this point&#8230;</p>
<p>Well, as it turns out, we can track this issue back the arrays we are using. When I first set up my preferences page, I built two arrays that looked like the following:</p>
<pre name="code" class="xml">
<resources>
	<string-array name="entries">
		<item>1 minute</item>
		<item>2 minutes</item>
		<item>5 minute</item>
		<item>10 minutes</item>
	</string-array>
	<integer-array name="entry_values">
		<item>1</item>
		<item>2</item>
		<item>5</item>
		<item>10</item>
	</string-array>
</resources>
</pre>
<p>As you can see, one is an array of String, while the other is an array of int. This is where the bug lies. The ListPreference object does not support type mismatches on the two arrays it needs. If we were to change the above code to:</p>
<p><Pre name="code" class="xml">
<resources>
	<string-array name="entries">
		<item>1 minute</item>
		<item>2 minutes</item>
		<item>5 minute</item>
		<item>10 minutes</item>
	</string-array>
	<string-array name="entry_values">
		<item>1</item>
		<item>2</item>
		<item>5</item>
		<item>10</item>
	</string-array>
</resources>
</pre>
<p>...Where both arrays are of type String, the null pointer exception goes away, and everything chugs along just fine. This really is only a minor, if not perplexing bug, as it is not a big deal to cast a string into an int. But, as I stated earlier, I felt it was worth bringing up, if only to save some fellow programmers some of the headaches I endured trying to figure it out.</p>
<p>The official bug report can be found <a href="http://code.google.com/p/android/issues/detail?id=2096" onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/android/issues/detail?id=2096&amp;referer=');">here</a>.</p>


<div class="shr-bookmarks shr-bookmarks-expand shr-bookmarks-center shr-bookmarks-bg-enjoy">
<ul class="socials">
		<li class="shr-digg">
			<a href="http://digg.com/submit?phase=2&amp;url=http://advback.com/android/108/&amp;title=ListPreference+bug%3F+-+Android" rel="nofollow" class="external" title="Digg this!" onclick="pageTracker._trackPageview('/outgoing/digg.com/submit?phase=2_amp_url=http_//advback.com/android/108/_amp_title=ListPreference+bug_3F+-+Android&amp;referer=');">Digg this!</a>
		</li>
		<li class="shr-facebook">
			<a href="http://www.facebook.com/share.php?v=4&amp;src=bm&amp;u=http://advback.com/android/108/&amp;t=ListPreference+bug%3F+-+Android" rel="nofollow" class="external" title="Share this on Facebook" onclick="pageTracker._trackPageview('/outgoing/www.facebook.com/share.php?v=4_amp_src=bm_amp_u=http_//advback.com/android/108/_amp_t=ListPreference+bug_3F+-+Android&amp;referer=');">Share this on Facebook</a>
		</li>
		<li class="shr-googlebuzz">
			<a href="http://www.google.com/buzz/post?url=http://advback.com/android/108/&amp;imageurl=" rel="nofollow" class="external" title="Post on Google Buzz" onclick="pageTracker._trackPageview('/outgoing/www.google.com/buzz/post?url=http_//advback.com/android/108/_amp_imageurl=&amp;referer=');">Post on Google Buzz</a>
		</li>
		<li class="shr-reddit">
			<a href="http://reddit.com/submit?url=http://advback.com/android/108/&amp;title=ListPreference+bug%3F+-+Android" rel="nofollow" class="external" title="Share this on Reddit" onclick="pageTracker._trackPageview('/outgoing/reddit.com/submit?url=http_//advback.com/android/108/_amp_title=ListPreference+bug_3F+-+Android&amp;referer=');">Share this on Reddit</a>
		</li>
		<li class="shr-twitter">
			<a href="http://twitter.com/home?status=ListPreference+bug%3F+-+Android+-+http://tinyurl.com/y3dp63c&amp;source=shareaholic" rel="nofollow" class="external" title="Tweet This!" onclick="pageTracker._trackPageview('/outgoing/twitter.com/home?status=ListPreference+bug_3F+-+Android+-+http_//tinyurl.com/y3dp63c_amp_source=shareaholic&amp;referer=');">Tweet This!</a>
		</li>
</ul>
<div style="clear:both;"></div>
</div>

]]></content:encoded>
			<wfw:commentRss>http://advback.com/android/108/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Activity launchmodes &#8211; Android</title>
		<link>http://advback.com/android/activity-launchmodes-android/</link>
		<comments>http://advback.com/android/activity-launchmodes-android/#comments</comments>
		<pubDate>Sat, 20 Mar 2010 03:01:47 +0000</pubDate>
		<dc:creator>Jeremy Cerise</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Mobile Programming]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[activity]]></category>
		<category><![CDATA[launchmode]]></category>

		<guid isPermaLink="false">http://advback.com/?p=78</guid>
		<description><![CDATA[Here&#8217;s something handy I learned with Android the other day. Lets say you have two activities. The first one, A, has a button that opens up the second activity, B. B, in turn has a button that returns the user to activity A. So, if you were to push the button in activity A, you [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s something handy I learned with Android the other day.</p>
<p>Lets say you have two activities. The first one, A, has a button that opens up the second activity, B. B, in turn has a button that returns the user to activity A. So, if you were to push the button in activity A, you would end up in activity B and vice versa. Pretty straight forward.</p>
<p>Now, lets say you just pushed the button in activity A, and ended up in activity B. You now want to go back to activity A. Pretty simple, just push the button in B, right? While if we push the button, we do in fact end up looking at activity A again, but it is not, in fact, the same instance of activity A that brought us to B in the first place.</p>
<p><span id="more-78"></span></p>
<p>If we think about this from an object oriented standpoint, this makes sense. When we create a new intent to change the activity from A to B and back, Android creates a new instance of the class for each intent. This means that every time we push the button, we are pushing a new instance of either A or B (depending on where we are) onto the stack, rather than re-using the already existing instance that we created previously. For our little sample application detailed here, this really doesn&#8217;t matter too much, as there is no difference between a new instance of A and one that has been around for a while.</p>
<p>Say though, that activity A changes state based off of user interaction, for example, the background on the button changes when pressed. If we pressed the button to go to activity B, and from B pressed the button to activity A, we would see no change on our button, even though we pressed it to get to B. This is because, as described above, when we press the button in B to go to A, a new instance of A is created, meaning that our original A is pushed deeper into the stack by the new A, and all state changes in the original A are not reflected in the new A.</p>
<p>This problem is easily solved through the use of a &#8220;launchmode&#8221; for the desired activity. A launchmode dictates what happens when an activity is launched. In this case, this means when we create a new intent and call startActivity() on said intent. There are four types of launchmodes: standard, singletop, singletask, singleinstance. For simplicities sake, Im going to ignore the last two and focus on the first two.</p>
<p>The default launchmode for an activity is standard (makes sense). Standard means that when a new intent for the activity is created, a new instance is created of the activity, even if one already exists on the activity stack. This is what creates the behavior outlined above when transferring between activity A and B. Even though we already have an instance of A on the top of the stack, when we use B to return, Android creates a new instance of A.</p>
<p>The second launchmode is singletop. This launchmode first looks to see if there is already an instance of a matching activity on the top of the stack, and if so, it uses the exsiting instance in the new intent rather than create a new instance. This is exactly what we would need if we wanted A to reflect state changes upon returning from B, as we would be recycling the original instance, rather than creating a new one each time.</p>
<p>All of this launchmode goodness happens in the applications AndroidManifest.xml file, within each individual activity declaration. The code would look like this:</p>
<pre name="code" class="xml">
<activity android:name=".A"
                  android:label="@string/a_label"
                  android:launchMode="singleTop" />
</pre>
<p>You can read more about launchmodes <a href="http://developer.android.com/guide/topics/manifest/activity-element.html" onclick="pageTracker._trackPageview('/outgoing/developer.android.com/guide/topics/manifest/activity-element.html?referer=');">here</a>.</p>


<div class="shr-bookmarks shr-bookmarks-expand shr-bookmarks-center shr-bookmarks-bg-enjoy">
<ul class="socials">
		<li class="shr-digg">
			<a href="http://digg.com/submit?phase=2&amp;url=http://advback.com/android/activity-launchmodes-android/&amp;title=Activity+launchmodes+-+Android" rel="nofollow" class="external" title="Digg this!" onclick="pageTracker._trackPageview('/outgoing/digg.com/submit?phase=2_amp_url=http_//advback.com/android/activity-launchmodes-android/_amp_title=Activity+launchmodes+-+Android&amp;referer=');">Digg this!</a>
		</li>
		<li class="shr-facebook">
			<a href="http://www.facebook.com/share.php?v=4&amp;src=bm&amp;u=http://advback.com/android/activity-launchmodes-android/&amp;t=Activity+launchmodes+-+Android" rel="nofollow" class="external" title="Share this on Facebook" onclick="pageTracker._trackPageview('/outgoing/www.facebook.com/share.php?v=4_amp_src=bm_amp_u=http_//advback.com/android/activity-launchmodes-android/_amp_t=Activity+launchmodes+-+Android&amp;referer=');">Share this on Facebook</a>
		</li>
		<li class="shr-googlebuzz">
			<a href="http://www.google.com/buzz/post?url=http://advback.com/android/activity-launchmodes-android/&amp;imageurl=" rel="nofollow" class="external" title="Post on Google Buzz" onclick="pageTracker._trackPageview('/outgoing/www.google.com/buzz/post?url=http_//advback.com/android/activity-launchmodes-android/_amp_imageurl=&amp;referer=');">Post on Google Buzz</a>
		</li>
		<li class="shr-reddit">
			<a href="http://reddit.com/submit?url=http://advback.com/android/activity-launchmodes-android/&amp;title=Activity+launchmodes+-+Android" rel="nofollow" class="external" title="Share this on Reddit" onclick="pageTracker._trackPageview('/outgoing/reddit.com/submit?url=http_//advback.com/android/activity-launchmodes-android/_amp_title=Activity+launchmodes+-+Android&amp;referer=');">Share this on Reddit</a>
		</li>
		<li class="shr-twitter">
			<a href="http://twitter.com/home?status=Activity+launchmodes+-+Android+-+http://tinyurl.com/y7hmzuw&amp;source=shareaholic" rel="nofollow" class="external" title="Tweet This!" onclick="pageTracker._trackPageview('/outgoing/twitter.com/home?status=Activity+launchmodes+-+Android+-+http_//tinyurl.com/y7hmzuw_amp_source=shareaholic&amp;referer=');">Tweet This!</a>
		</li>
</ul>
<div style="clear:both;"></div>
</div>

]]></content:encoded>
			<wfw:commentRss>http://advback.com/android/activity-launchmodes-android/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Finding distance between two points with Google Maps &#8211; Android</title>
		<link>http://advback.com/android/finding-distance-between-two-points-with-google-maps-android/</link>
		<comments>http://advback.com/android/finding-distance-between-two-points-with-google-maps-android/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 08:00:46 +0000</pubDate>
		<dc:creator>Jeremy Cerise</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Mobile Programming]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[geopoint]]></category>
		<category><![CDATA[Haversine]]></category>

		<guid isPermaLink="false">http://advback.com/?p=68</guid>
		<description><![CDATA[So, lets say your application needs to let the user know when he/she is within, say, 1 mile of a given location. Or, you want to sort a series of locations based on how close to the user the points are in a straight line. How do you go about doing that? One way would [...]]]></description>
			<content:encoded><![CDATA[<p>So, lets say your application needs to let the user know when he/she is within, say, 1 mile of a given location. Or, you want to sort a series of locations based on how close to the user the points are in a straight line. How do you go about doing that? One way would be to use the Haversine formula to figure out the distances between two points, considering that Earth is spherical, but that takes math, and who likes doing that?</p>
<p>Thankfully, there is a much simpler way to figure out distances between two points on a map: the distanceTo() method in the Location class. Using this handy little method, we can quickly find out the distance between two locations:</p>
<pre name="code" class="java">
double distance;

Location locationA = new Location("point A");

locationA.setLatitude(latA);
locationA.setLongitude(lngA);

Location locationB = new Location("point B");

locationB.setLatitude(latB);
LocationB.setLongitude(lngB);

distance = locationA.distanceTo(locationB);
</pre>
<p>One thing to note is that the distanceTo() method returns the distance in meters, so you will need to do the appropriate calculations if you want your distances in other units.</p>


<div class="shr-bookmarks shr-bookmarks-expand shr-bookmarks-center shr-bookmarks-bg-enjoy">
<ul class="socials">
		<li class="shr-digg">
			<a href="http://digg.com/submit?phase=2&amp;url=http://advback.com/android/finding-distance-between-two-points-with-google-maps-android/&amp;title=Finding+distance+between+two+points+with+Google+Maps+-+Android" rel="nofollow" class="external" title="Digg this!" onclick="pageTracker._trackPageview('/outgoing/digg.com/submit?phase=2_amp_url=http_//advback.com/android/finding-distance-between-two-points-with-google-maps-android/_amp_title=Finding+distance+between+two+points+with+Google+Maps+-+Android&amp;referer=');">Digg this!</a>
		</li>
		<li class="shr-facebook">
			<a href="http://www.facebook.com/share.php?v=4&amp;src=bm&amp;u=http://advback.com/android/finding-distance-between-two-points-with-google-maps-android/&amp;t=Finding+distance+between+two+points+with+Google+Maps+-+Android" rel="nofollow" class="external" title="Share this on Facebook" onclick="pageTracker._trackPageview('/outgoing/www.facebook.com/share.php?v=4_amp_src=bm_amp_u=http_//advback.com/android/finding-distance-between-two-points-with-google-maps-android/_amp_t=Finding+distance+between+two+points+with+Google+Maps+-+Android&amp;referer=');">Share this on Facebook</a>
		</li>
		<li class="shr-googlebuzz">
			<a href="http://www.google.com/buzz/post?url=http://advback.com/android/finding-distance-between-two-points-with-google-maps-android/&amp;imageurl=" rel="nofollow" class="external" title="Post on Google Buzz" onclick="pageTracker._trackPageview('/outgoing/www.google.com/buzz/post?url=http_//advback.com/android/finding-distance-between-two-points-with-google-maps-android/_amp_imageurl=&amp;referer=');">Post on Google Buzz</a>
		</li>
		<li class="shr-reddit">
			<a href="http://reddit.com/submit?url=http://advback.com/android/finding-distance-between-two-points-with-google-maps-android/&amp;title=Finding+distance+between+two+points+with+Google+Maps+-+Android" rel="nofollow" class="external" title="Share this on Reddit" onclick="pageTracker._trackPageview('/outgoing/reddit.com/submit?url=http_//advback.com/android/finding-distance-between-two-points-with-google-maps-android/_amp_title=Finding+distance+between+two+points+with+Google+Maps+-+Android&amp;referer=');">Share this on Reddit</a>
		</li>
		<li class="shr-twitter">
			<a href="http://twitter.com/home?status=Finding+distance+between+two+points+with+Google+Maps+-+Android+-+http://tinyurl.com/y688xnh&amp;source=shareaholic" rel="nofollow" class="external" title="Tweet This!" onclick="pageTracker._trackPageview('/outgoing/twitter.com/home?status=Finding+distance+between+two+points+with+Google+Maps+-+Android+-+http_//tinyurl.com/y688xnh_amp_source=shareaholic&amp;referer=');">Tweet This!</a>
		</li>
</ul>
<div style="clear:both;"></div>
</div>

]]></content:encoded>
			<wfw:commentRss>http://advback.com/android/finding-distance-between-two-points-with-google-maps-android/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Checking if GPS is enabled &#8211; Android</title>
		<link>http://advback.com/android/checking-if-gps-is-enabled-android/</link>
		<comments>http://advback.com/android/checking-if-gps-is-enabled-android/#comments</comments>
		<pubDate>Fri, 05 Mar 2010 02:11:24 +0000</pubDate>
		<dc:creator>Jeremy Cerise</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Mobile Programming]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[GPS]]></category>

		<guid isPermaLink="false">http://advback.com/?p=50</guid>
		<description><![CDATA[The application I&#8217;m currently working requires that the user has the GPS active on his/her phone. This can be either the coarse (cell tower triangulation) or fine (GPS satellites) methods, but whichever it is, the application needs the Geodata to function. This brought up the issue of, how do we know if the user actually [...]]]></description>
			<content:encoded><![CDATA[<p>The application I&#8217;m currently working requires that the user has the GPS active on his/her phone. This can be either the coarse (cell tower triangulation) or fine (GPS satellites) methods, but whichever it is, the application needs the Geodata to function. This brought up the issue of, how do we know if the user actually has the GPS enabled on the phone? If they don&#8217;t, the application will still work, but all the coordinates it stores will end up being 0 degrees for both latitude and longitude, not very useful. To combat this, we can do a simple check when the application starts up to make sure the user knows that their GPS is disabled, and their location will be recorded as somewhere along the equator.</p>
<p>To start with, we need a locationManager object:</p>
<pre name="code" class="java">LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
</pre>
<p>Now that we have a location manager, its a simple process to check to see if the GPS is enabled or not:</p>
<pre name="code" class="java">if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
      createGpsDisabledAlert();
}
</pre>
<p>This just checks to see if GPS is on, and if not, it calls a method, createGpsDisabledAlert(), which will build an alert dialog to warn the user that their GPS is off:</p>
<pre name="code" class="java">private void createGpsDisabledAlert(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS is disabled! Would you like to enable it?")
     .setCancelable(false)
     .setPositiveButton("Enable GPS",
          new DialogInterface.OnClickListener(){
          public void onClick(DialogInterface dialog, int id){
               showGpsOptions();
          }
     });
     builder.setNegativeButton("Do nothing",
          new DialogInterface.OnClickListener(){
          public void onClick(DialogInterface dialog, int id){
               dialog.cancel();
          }
     });
AlertDialog alert = builder.create();
alert.show();
}
</pre>
<p>If the user decides they want to turn their GPS on, and they select the positive action of the dialog, showGpsOptions() is called. All this method does is to show the &#8220;Locations and Security&#8221; page from the Android settings menu. As a small sidenote, as of Android 1.5, there is no way to directly toggle the location settings through code, so we have to assume the user can figure it out if shown the proper screen. The code for showGpsOptions() is very simple:</p>
<pre name="code" class="java">private void showGpsOptions(){
		Intent gpsOptionsIntent = new Intent(
				android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		startActivity(gpsOptionsIntent);
	}
</pre>
<p>And thats it! When the user starts the activity, if the GPS is off, the dialog will pop up asking them what they want to do. If the GPS is already on, nothing will happen. Sweet. The full code looks like the following:</p>
<pre name="code" class="java">protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
     LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE);

     if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
          createGpsDisabledAlert();
     }
}

private void createGpsDisabledAlert(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS is disabled! Would you like to enable it?")
     .setCancelable(false)
     .setPositiveButton("Enable GPS",
          new DialogInterface.OnClickListener(){
          public void onClick(DialogInterface dialog, int id){
               showGpsOptions();
          }
     });
     builder.setNegativeButton("Do nothing",
          new DialogInterface.OnClickListener(){
          public void onClick(DialogInterface dialog, int id){
               dialog.cancel();
          }
     });
AlertDialog alert = builder.create();
alert.show();
}

private void showGpsOptions(){
		Intent gpsOptionsIntent = new Intent(
				android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		startActivity(gpsOptionsIntent);
}
</pre>


<div class="shr-bookmarks shr-bookmarks-expand shr-bookmarks-center shr-bookmarks-bg-enjoy">
<ul class="socials">
		<li class="shr-digg">
			<a href="http://digg.com/submit?phase=2&amp;url=http://advback.com/android/checking-if-gps-is-enabled-android/&amp;title=Checking+if+GPS+is+enabled+-+Android" rel="nofollow" class="external" title="Digg this!" onclick="pageTracker._trackPageview('/outgoing/digg.com/submit?phase=2_amp_url=http_//advback.com/android/checking-if-gps-is-enabled-android/_amp_title=Checking+if+GPS+is+enabled+-+Android&amp;referer=');">Digg this!</a>
		</li>
		<li class="shr-facebook">
			<a href="http://www.facebook.com/share.php?v=4&amp;src=bm&amp;u=http://advback.com/android/checking-if-gps-is-enabled-android/&amp;t=Checking+if+GPS+is+enabled+-+Android" rel="nofollow" class="external" title="Share this on Facebook" onclick="pageTracker._trackPageview('/outgoing/www.facebook.com/share.php?v=4_amp_src=bm_amp_u=http_//advback.com/android/checking-if-gps-is-enabled-android/_amp_t=Checking+if+GPS+is+enabled+-+Android&amp;referer=');">Share this on Facebook</a>
		</li>
		<li class="shr-googlebuzz">
			<a href="http://www.google.com/buzz/post?url=http://advback.com/android/checking-if-gps-is-enabled-android/&amp;imageurl=" rel="nofollow" class="external" title="Post on Google Buzz" onclick="pageTracker._trackPageview('/outgoing/www.google.com/buzz/post?url=http_//advback.com/android/checking-if-gps-is-enabled-android/_amp_imageurl=&amp;referer=');">Post on Google Buzz</a>
		</li>
		<li class="shr-reddit">
			<a href="http://reddit.com/submit?url=http://advback.com/android/checking-if-gps-is-enabled-android/&amp;title=Checking+if+GPS+is+enabled+-+Android" rel="nofollow" class="external" title="Share this on Reddit" onclick="pageTracker._trackPageview('/outgoing/reddit.com/submit?url=http_//advback.com/android/checking-if-gps-is-enabled-android/_amp_title=Checking+if+GPS+is+enabled+-+Android&amp;referer=');">Share this on Reddit</a>
		</li>
		<li class="shr-twitter">
			<a href="http://twitter.com/home?status=Checking+if+GPS+is+enabled+-+Android+-+http://tinyurl.com/y7e4sds&amp;source=shareaholic" rel="nofollow" class="external" title="Tweet This!" onclick="pageTracker._trackPageview('/outgoing/twitter.com/home?status=Checking+if+GPS+is+enabled+-+Android+-+http_//tinyurl.com/y7e4sds_amp_source=shareaholic&amp;referer=');">Tweet This!</a>
		</li>
</ul>
<div style="clear:both;"></div>
</div>

]]></content:encoded>
			<wfw:commentRss>http://advback.com/android/checking-if-gps-is-enabled-android/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Creating directories on the SD card &#8211; Android</title>
		<link>http://advback.com/android/creating-directories-on-the-sd-card-android/</link>
		<comments>http://advback.com/android/creating-directories-on-the-sd-card-android/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 07:00:10 +0000</pubDate>
		<dc:creator>Jeremy Cerise</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Mobile Programming]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[sd card]]></category>

		<guid isPermaLink="false">http://advback.com/?p=32</guid>
		<description><![CDATA[This is a topic that I couldn&#8217;t help but notice is MIA from many Android tutorials and books, even though its a relatively simple process. If you are familiar with creating and working with directories and files in Java, there&#8217;s nothing new here, but what threw me off initially was where to actually put the [...]]]></description>
			<content:encoded><![CDATA[<p>This is a topic that I couldn&#8217;t help but notice is MIA from many Android tutorials and books, even though its a relatively simple process. If you are familiar with creating and working with directories and files in Java, there&#8217;s nothing new here, but what threw me off initially was where to actually put the darn directory.</p>
<pre name="code" class="java">
public class DirectoryTest extends Activity {

     private static final String TAG = "DirTest Output:";

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

        File sddir = new File("/sdcard/testDirectory");

        if (sddir.mkdirs()) {
             Toast toast = Toast.makeText(this,
             "Directory successfully created!",
					Toast.LENGTH_SHORT);
	     toast.setGravity(Gravity.CENTER, 0, 0);
	     toast.show();
        }else{
             Log.e(TAG, "Create dir in sdcard failed");
             Toast toast = Toast.makeText(this,
             "Directory creation failed!",
 					Toast.LENGTH_SHORT);
 	     toast.setGravity(Gravity.CENTER, 0, 0);
 	     toast.show();
        }
    }
}
</pre>
<p>Like I said, pretty simple. We create a new file object with the path to the SD card, which happens to just be /sdcard, and then we call the mkdirs() method, which will create all the directories along the chain we specified in our File object. Nice and easy.</p>


<div class="shr-bookmarks shr-bookmarks-expand shr-bookmarks-center shr-bookmarks-bg-enjoy">
<ul class="socials">
		<li class="shr-digg">
			<a href="http://digg.com/submit?phase=2&amp;url=http://advback.com/android/creating-directories-on-the-sd-card-android/&amp;title=Creating+directories+on+the+SD+card+-+Android" rel="nofollow" class="external" title="Digg this!" onclick="pageTracker._trackPageview('/outgoing/digg.com/submit?phase=2_amp_url=http_//advback.com/android/creating-directories-on-the-sd-card-android/_amp_title=Creating+directories+on+the+SD+card+-+Android&amp;referer=');">Digg this!</a>
		</li>
		<li class="shr-facebook">
			<a href="http://www.facebook.com/share.php?v=4&amp;src=bm&amp;u=http://advback.com/android/creating-directories-on-the-sd-card-android/&amp;t=Creating+directories+on+the+SD+card+-+Android" rel="nofollow" class="external" title="Share this on Facebook" onclick="pageTracker._trackPageview('/outgoing/www.facebook.com/share.php?v=4_amp_src=bm_amp_u=http_//advback.com/android/creating-directories-on-the-sd-card-android/_amp_t=Creating+directories+on+the+SD+card+-+Android&amp;referer=');">Share this on Facebook</a>
		</li>
		<li class="shr-googlebuzz">
			<a href="http://www.google.com/buzz/post?url=http://advback.com/android/creating-directories-on-the-sd-card-android/&amp;imageurl=" rel="nofollow" class="external" title="Post on Google Buzz" onclick="pageTracker._trackPageview('/outgoing/www.google.com/buzz/post?url=http_//advback.com/android/creating-directories-on-the-sd-card-android/_amp_imageurl=&amp;referer=');">Post on Google Buzz</a>
		</li>
		<li class="shr-reddit">
			<a href="http://reddit.com/submit?url=http://advback.com/android/creating-directories-on-the-sd-card-android/&amp;title=Creating+directories+on+the+SD+card+-+Android" rel="nofollow" class="external" title="Share this on Reddit" onclick="pageTracker._trackPageview('/outgoing/reddit.com/submit?url=http_//advback.com/android/creating-directories-on-the-sd-card-android/_amp_title=Creating+directories+on+the+SD+card+-+Android&amp;referer=');">Share this on Reddit</a>
		</li>
		<li class="shr-twitter">
			<a href="http://twitter.com/home?status=Creating+directories+on+the+SD+card+-+Android+-+http://tinyurl.com/y2nhgjh&amp;source=shareaholic" rel="nofollow" class="external" title="Tweet This!" onclick="pageTracker._trackPageview('/outgoing/twitter.com/home?status=Creating+directories+on+the+SD+card+-+Android+-+http_//tinyurl.com/y2nhgjh_amp_source=shareaholic&amp;referer=');">Tweet This!</a>
		</li>
</ul>
<div style="clear:both;"></div>
</div>

]]></content:encoded>
			<wfw:commentRss>http://advback.com/android/creating-directories-on-the-sd-card-android/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

