Tutorial 4 – A Simple Stopwatch (Ads & Landscape)

After spending this much time and effort creating your app, won’t it be great it you could get some sort of returns for all your hard work? In this tutorial we will be covering one of the most widely used methods for monetizing your app; Mobile advertising. We will be covering the basics on how to include ads in your app (Admob our example). We will also be covering how to handle the change in screen orientation in this tutorial You may have noticed that changes in screen orientation while running causes the application to reset. We look at handling this issue.

If you wish to follow along from this point but you have not completed the previous tutorials you can download the files at the end of the Tutorial 3 and follow along from this point.

 

Setting up Ads

In example we will be using Admob ads. In order to setup admob ads you need to have a user account, so if you did not do this already head on over to admob.com and register. Note: If you already have an existing gmail account, you can use this to sign in. Once you are registered and logged in you should see a page similar to the this


If not, then click on the Marketplace link at the top of your screen.

From the above page Go to Sites & Apps > Add Site/App.

Select Android App and fill out the required information.

You will then be directed to a new page that allows you to download the Admob Android SDK. Download the SDK, then click on the Go to Site / Apps button.

You should now see your app listed but the status will have a red dot indicating that no ad requests were received from your app, this is normal and expected.

Hover over the App name and a “Manage Settings” link would then appear, click on this link and you will be redirected to a new page that has your site url and your publisher id, make a note of the publisher id as this required later on to add the ads to your application.

The next step is to add the .jar file you downloaded to your project build path.

Unzip the SDK you downloaded two steps above and place the .jar file in a convenient location, I usually place mine somewhere within my workspace so that it is kept together with all of my Android Projects.

While still in Eclipse right click on the project folder and select Properties. A Window similar to the one below should pop up.

 

 

On the left side column, select java build path and on the right select Add external JARs. Browse to your unizpped SDK and select the GoogleAdMobAdsSdk-x.x.x.jar file. (x.x.x will vary depending on the version available at the time you are downloading). Select Ok at the bottom of the window.

The ads require special permissions to work. In order to grant Admob the required permissions you need to edit your AndroidManifest.xml file loacted within the project file.

Open the AndroidManifest.xml file and add the following lines before the closing manifest tag (</manifest>)

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

as well as the following after the </activity> tags but before the </application> tag

<activity android:name="com.google.ads.AdActivity"
                  android:configChanges="keyboard|keyboardHidden|orientation"/>

When users are installing your application they are notified of the permissions required and at that point its up to them to choose to continue or not. In my experience however the permissions required for ads are usually readily accepted by most users.

Before we add the code to the activity file, we need to update the main.xml file and remove the placeholder we have as the ads will now be in its place. Additionally we need to ensure the Layout we are placing the ad into has an id.

Open the main.xml file and scroll to the bottom of the file,before the last closing RelativeLayout tag there is a TextView which is inside a LinearLayout which is inside a RelativeLayout. We want to delete the TextView as this was just a temporary place holder, we also want to supply an id for the  LinearLayout where the ads will be placed. Update the last couple of lines in the code to the following

<RelativeLayout
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:layout_alignParentBottom="true" >
		<LinearLayout
		android:orientation="vertical"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:id="@+id/adsLayout">
		</LinearLayout>
	</RelativeLayout>
</RelativeLayout>

 

Note: the last closing RelativeLayout tag at line 13 is the closing tag for RelativeLayout at the very first line in main.xml layout file (not shown in this snippet) so you do not need to add that line.

 

The next step is to update the code, however in order to use the AdView classes provided by admob we need to import the packages. This is done by adding the line

import com.google.ads.*;

near the top of the StopwatchActivity.java file where the other import statements are. You also need to declare an AdView variable which we will be initializing in the onCreate method.

Note: we will also need to import the Android LinearLayout widget as we will be using it to specify where we want the ad to be placed.

Below is the actual code to import the packages

import com.google.ads.*;
import android.widget.LinearLayout;

Declaring the AdView variable

public class StopwatchActivity extends Activity {
    /** Called when the activity is first created. */

	private AdView adView;
	private TextView tempTextView; //Temporary TextView
	private Button tempBtn; //Temporary Button

 

Implementing the AdView Variable in the onCreate procedure

@Override
 public void onCreate(Bundle savedInstanceState) {

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

     adView = new AdView(this, AdSize.BANNER,"YOUR PUBLISHER ID GOES HERE");
     LinearLayout layout = (LinearLayout)findViewById(R.id.adsLayout);
     layout.addView(adView);
     adView.loadAd(new AdRequest());

Remember to change the “YOUR PUBLISHER ID GOES HERE” to the publisher id that you took note of earlier. The last step that is required is to destroy the adView whenever the Activity itself is being destroyed. This is done by adding the following code.

@Override
public void onDestroy() {
   adView.destroy();
   super.onDestroy();
}

That’s it for adding ads to your mobile application. Go ahead and run your app and see your ads. Please note however when you are requesting ads for the first time using a new publisher id it usually takes some time (don;t worry its only a couple of minutes) before the ads are displayed but don’t worry it will show up eventually and when it does the original delay should no longer be present.

 

Dealing with screen rotation.

By default any configuration changes such as a change in the screen orientation or even the siding out of the keyboard on your device (if you have a device with a keyboard) causes your Activity to be destroyed and a new instance is created from what information was saved in the last instance. In most cases this would not be a problem, such if you were reading an email and you decided to rotate your screen your activity will be destroyed, but then it would be recreated right away perhaps even in a layout more suited to your needs and you can continue reading your email. For our application however this poses a problem, we do not want our activity to be destroyed while we are timing some event as this will throw our whole timing off and then we would need to restart from the beginning. This is an issue that needs to be handled. The two main ways of dealing with this is

    1. Specify in code that we do not want to the screen to be able to rotate or
    2. Override the default handling of the screen rotation and handle the situation ourselves.

 

Since there are many advantages to having a screen that can rotate we look at the latter option
First we specify that we would like to bypass the restarting of the activity when the screen orientation changes as well as when the user slides out the keyboard, we do this by adding an extra line in the AndroidManifest.xml file within opening activity tag. (Line 4 of the code below)
<activity android:name=".StopwatchActivity"
   android:label="@string/app_name"
   android:theme="@android:style/Theme.NoTitleBar"
   android:configChanges="keyboardHidden|orientation">

If we run the application at this point, and rotate the handset you will notice that the stopwatch no longer restarts, but what if we wanted to make changes to application when the screen orientation is changed? Say for example we may want the layout changed to make use of the wider screen space that is now available. This can be done by using the onConfigurationChanged method. In the example below I will implement the code to increase the timer TexView size to fill more of the screen and also hide the ads when the phone is switch to landscape mode and do the reverse when it returns to portrait mode

    @Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			TextView timer = (TextView) findViewById(R.id.timer);
			timer.setTextSize(TypedValue.COMPLEX_UNIT_SP, 90);
			TextView timerMs = (TextView) findViewById(R.id.timerMs);
			timerMs.setTextSize(TypedValue.COMPLEX_UNIT_SP, 40);
			((LinearLayout) findViewById(R.id.adsLayout)).setVisibility(View.GONE);
		}
		else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
			TextView timer = (TextView) findViewById(R.id.timer);
			timer.setTextSize(TypedValue.COMPLEX_UNIT_SP, 70);
			TextView timerMs = (TextView) findViewById(R.id.timerMs);
			timerMs.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);
			((LinearLayout) findViewById(R.id.adsLayout)).setVisibility(View.VISIBLE);
		}
	}

If you ahead and run the application now you would notice that the timer text size increases when in landscape mode and then decreases back to it original size when switched back to portrait mode.

And the final results in portrait and landscape.

 

 

Now you fully functioning stopwatch.You can take the lessons learned in these tutorials and expand on it, probably re-arrange the whole layout when in landscape mode, or even implement a lap timer into the stopwatch, you should have a fair understanding of what is required to build a simple android application and can now expand on it. If you have any suggestions for future tutorials please let me know and I will do my best to get them to you.

See you soon at the next tutorial or rant :)

 

Market Link for this Stopwatch


Download from Android Market (free)


 

Resources


Completed Stopwatch files.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>