Archive
Dealing with AsyncTask and Screen Orientation
A common task in Android is to perform some background activity in another thread, meanwhile displaying a ProgressDialog to the user. Example of these tasks include downloading some data from internet, logging into an application, etc. Implementing an AsyncTask is fairly a simple job, the big challenge is how to handle it properly when an orientation change occurs.
In this article I will walk though a series of potential solutions to address the screen orientation issues when using an AsyncTask.
So, lets create a proof of concept application that makes use of an AsyncTask which does not handle configuration changes yet, and then present a few solutions.
Here’s the AsyncTask implementation that we will be using during the tutorial:
public class AsyncTaskExample extends AsyncTask<String, Integer, String> {
private final TaskListener listener;
public AsyncTaskExample(TaskListener listener) {
this.listener = listener;
}
@Override
protected void onPreExecute() {
listener.onTaskStarted();
}
@Override
protected String doInBackground(String... params) {
for (int i = 1; i <= 10; i++) {
Log.d("GREC", "AsyncTask is working: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "All Done!";
}
@Override
protected void onPostExecute(String result) {
listener.onTaskFinished(result);
}
}
- doInBackground() – this will be called by the AsyncTask on a background thread, and performs all the heavy work. For the sake of this example, I just wrote a simple loop with a delay of 1 sec between iterations to simulate a task that takes some time.
- The constructor of the class takes a listener as a parameter. The listener will be used to delegate the work of onPreExecute()/onPostExecute() to the calling Activity.
This is the interface definition used by AsyncTaskExample:
public interface TaskListener {
void onTaskStarted();
void onTaskFinished(String result);
}
And here’s the usage of AsyncTaskExample (the problematic case):
public class MainActivity extends Activity implements TaskListener, OnClickListener {
private ProgressDialog progressDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.start).setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.start) {
new AsyncTaskExample(this).execute();
}
}
@Override
public void onTaskStarted() {
progressDialog = ProgressDialog.show(CopyOfMainActivity.this, "Loading", "Please wait a moment!");
}
@Override
public void onTaskFinished(String result) {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
The Activity implements the TaskListener interface and provides appropriate implementation for its methods, displaying the ProgressDialog when the task is started, and dismissing it when the task is finished. The AsyncTask is fired when clicking on a button.
Now, if you run this example without changing the screen orientation, the AsyncTask will start and finish its work normally. Problems begin to appear when the device orientation is changed while the AsyncTask is in the middle of the work. The application will crash, and an exception similar to these ones will be thrown: java.lang.IllegalArgumentException: View not attached to window manager, or Activity has leaked window com.android.internal.policy….
The cause relies in the Activity life cycle. A change in device orientation is interpreted as a configuration change which causes the current activity to be destroyed and then recreated. Android calls onPause(), onStop(), and onDestroy() on currently instance of activity, then a new instance of the same activity is recreated calling onCreate(), onStart(), and onResume(). The reason why Android have to do this, is because depending of screen orientation, portrait or landscape, we may need to load and display different resources, and only through re-creation Android can guarantee that all our resources will be re-requested.
But don’t panic, you are not alone, there are several solutions that will help us to deal with this situation.
Solution 1 – Think twice if you really need an AsyncTask.
AsyncTasks are good for performing background work, but they are bound to the Activity which adds some complexity. For things like making HTTP requests to a server perhaps you should consider an IntentService. IntentService used in conjunction with a BroadcastReceiver or ResultReceiver to deliver results, could do a better job than an AsyncTask in certain situations.
Solution 2 – Put the AsyncTask in a Fragment.
Using fragments probably is the cleanest way to handle configuration changes. By default, Android destroys and recreates the fragments just like activities, however, fragments have the ability to retain their instances, simply by calling: setRetainInstance(true), in one of its callback methods, for example in the onCreate().
There’s however one aspect that should be taken in consideration in order to achieve the desired result. Our AsyncTask uses a ProgressDialog to signal when the AsyncTask is started, and dismisses it when the task is done. This complicates a bit the things because even if we are using setRetainInstance(true), we should close all windows and dialogs when the Activity is destroyed, otherwise we will get an: Activity has leaked window com.android.internal.policy… exception. This happens when you try to show a dialog after you have exited the Activity.
In order to address this issue, we will add some logic to keep track of AsyncTask status (running/not running). We will dismiss the ProgressDialog when the fragment is detached from activity, and check in onActivityCreated() the status of AsyncTask. If the status is “running”, this means we are returning from a screen orientation and we will just re-create and display the ProgressDialog to show that the AsyncTask is still working.
public class ExampleFragment extends Fragment implements TaskListener, OnClickListener {
private ProgressDialog progressDialog;
private boolean isTaskRunning = false;
private AsyncTaskExample asyncTask;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// If we are returning here from a screen orientation
// and the AsyncTask is still working, re-create and display the
// progress dialog.
if (isTaskRunning) {
progressDialog = ProgressDialog.show(getActivity(), "Loading", "Please wait a moment!");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);
Button button = (Button) view.findViewById(R.id.start);
button.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
if (!isTaskRunning) {
asyncTask = new AsyncTaskExample(this);
asyncTask.execute();
}
}
@Override
public void onTaskStarted() {
isTaskRunning = true;
progressDialog = ProgressDialog.show(getActivity(), "Loading", "Please wait a moment!");
}
@Override
public void onTaskFinished(String result) {
if (progressDialog != null) {
progressDialog.dismiss();
}
isTaskRunning = false;
}
@Override
public void onDetach() {
// All dialogs should be closed before leaving the activity in order to avoid
// the: Activity has leaked window com.android.internal.policy... exception
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
super.onDetach();
}
}
Solution 3 – Lock the screen orientation
You could do this in 2 ways:
a) permanently locking the screen orientation of the activity, specifying the screenOrientation attribute in the AndroidManifest with “portrait” or “landscape” values:
<activity android:screenOrientation="portrait" ... />
b) or, temporarily locking the screen in onPreExecute(), and unlocking it in onPostExecute(), thus preventing any orientation change while the AsyncTask is working:
@Override
public void onTaskStarted() {
lockScreenOrientation();
progressDialog = ProgressDialog.show(CopyOfCopyOfMainActivity.this, "Loading", "Please wait a moment!");
}
@Override
public void onTaskFinished(String result) {
if (progressDialog != null) {
progressDialog.dismiss();
}
unlockScreenOrientation();
}
private void lockScreenOrientation() {
int currentOrientation = getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
private void unlockScreenOrientation() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
Solution 4 – Prevent the Activity from being recreated.
This is the easiest way to handle configuration changes, but the less advised. The only thing you need to do is to specify the configChanges attribute followed by a list of values that specifies when the activity should prevent itself from restarting.
<activity android:configChanges="orientation|keyboardHidden" android:name=".MainActivity" .... />
Using this approach however, is not recommended, and this is clearly stated in the Android documentation: Using this attribute should be avoided and used only as a last-resort.
You may ask what’s wrong with this approach. Well, if you build the above example against Android 2.2 it will work fine, but if you build it against Android 3.0 and higher, you may notice that the application still crashes on orientation change. This is because starting with Android 3.0 you need also to handle the screenSize, and smallestScreenSize:
<activity android:configChanges="orientation|keyboardHidden|screenSize|smallestScreenSize" android:name=".MainActivity" .... />
As it turns out, not only a screen orientation causes the Activity to recreate, there are also other events which may produce configuration changes and restart the Activity, and there’s a good chance that we won’t handle them all. This is why the use of this technique is discouraged.
Taking a screenshot of current Activity in Android
In this post I’ll show how you can take a screenshot of your current Activity and save the resulting image on /sdcard.
The idea behind taking a screenshot actually is pretty simple: what we need to do is to get a reference of the root view and generate a bitmap copy of this view.
Considering that we want to take the screenshot when a button is clicked, the code will look like this:
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
}
});
First of all we should retrieve the topmost view in the current view hierarchy, then enable the drawing cache, and after that call getDrawingCache().
Calling getDrawingCache(); will return the bitmap representing the view or null if cache is disabled, that’s why setDrawingCacheEnabled(true); should be set to true prior invoking getDrawingCache().
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
And the method that saves the bitmap image to external storage:
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
Since the image is saved on external storage, the WRITE_EXTERNAL_STORAGE permission should be added AndroidManifest to file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Using Custom Fonts in Android
By default Android comes with three standard fonts: Droid Sans (default font), Droid Serif, and Droid Sans Mono. They all can be applied to any view that supports styling, such as TextView, Button, by specifying the “android:typeface” attribute in the XML declaration with any of these values: sans, serif, monospace.
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Sans" android:typeface="sans" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Serif" android:typeface="serif" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Monospace" android:typeface="monospace" />
Using custom fonts in Android is pretty straightforward. First find a free font and put it in the assets/fonts directory. (It’s not mandatory to have a /fonts directory, but if I have a lot of stuff in the /assets directory I organize them in separate directories). Then get a reference to your TextView and create a Typeface object specifying the font path. Lastly, apply the typeface to the TextView.
In this particular example I used the font: christmaseve.ttf
TextView textView = (TextView) findViewById(R.id.textView); Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/christmaseve.ttf"); textView.setTypeface(tf);
RuntimeException: Native typeface cannot be made
If you get this exception while trying to integrate the custom font into your application, make sure the path to the font file is correct, and the font name is spelled correctly. I noticed I was getting this exception when my font path was misspelled, for example writing “.tff” instead of “.ttf”, or forgetting to add the “fonts/” prefix to the path.
Custom font used in this example provided by: http://bythebutterfly.com
Integrating Google Analytics SDK (V2) with Android
The Google Analytics SDK for Android makes it easy for developers to collect valuable statics about how the users are using their app.
Here are some features that Android Google Analytics SDK offers:
- The number of active users that are using the application
- Usage of specific features
- The number and type of application crashes
- From where in the world the application is used
- And many other useful metrics.
Just to illustrate the integration process lets create a simple proof of concept application with 2 activities: MainActivity and AboutActivity, and 2 buttons: Rate and Share.
Our mission is to integrate Google Analytics SDK with the application, to:
- track activity views, (MainActivity and About)
- track events (how many times the buttons “Rate”, and “Share” are clicked)
If you are searching for Google Analytics I’m assuming you are already pretty familiar with Android and could create the proof of concept application yourself, so I will skip this step and concentrate solely on integration.
1. Downloading the SDK
Go to downloads page and download GoogleAnalyticsAndroid.zip Version 2.0. Extract the archive and add libGoogleAnalyticsV2.jar to your project’s /libs directory.
At the moment of writing this post, Google provides two versions: version 1.5.1 (legacy), and version 2.0 beta. Still if the Version 2 of SDK is beta, I highly suggest you choose this version, over the 1.5.1 (legacy).
The reason not to choose SDK 1.5.1 is that it uses a tracking model that is designed to track visitors to traditional websites and interaction with widgets in traditional web pages.
The new “App” profiles and reports will only accept data from version 2 or higher of the SDK.
2. Creating a Google Analytics account
Before starting to use the SDK you first must create an account at: http://www.google.com/analytics/
- Sign in to your account.
- Click Admin.
- Click Account list (just below the menu bar)
- Click +New Account
- When asked what you would like to track, select App property.

- Enter all the necessary information and click Get Tracking ID.
Now that you have a Tracking ID, you can begin the integration with the application. The first step is to update the AndroidManifest file.
3. Updating AndroidManifest file.
Add folowing permissions to the AndroidManifest file:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
4. Creating the analytics.xml file
In version 2 of Google Analytics SDK for Android, the tracking settings are managed from an xml resource file called: analytics.xml. You will need to create this file in res/values directory, and add your tracking ID as well as other settings here.
<?xml version="1.0" encoding="utf-8"?> <resources> <!-- Replace placeholder ID with your tracking ID --> <string name="ga_trackingId">UA-00000000-0</string> <!-- Enable Activity tracking --> <bool name="ga_autoActivityTracking">true</bool> <!-- Enable debug --> <bool name="ga_debug">true</bool> <!-- The screen names that will appear in your reporting --> <string name="com.testgoogleanalytics.MainActivity">MainActivity</string> <string name="com.testgoogleanalytics.About">About</string> <!-- The inverval of time after all the collected data should be sent to the server, in seconds. --> <integer name="ga_dispatchPeriod">30</integer> </resources>
5. Tracking activities.
To track activities add the tracking methods to the onStart() and onStop() of each of your activities.
// Example of tracking MainActivity
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStart() {
super.onStart();
EasyTracker.getInstance().activityStart(this); // Add this method
}
@Override
protected void onStop() {
super.onStop();
EasyTracker.getInstance().activityStop(this); // Add this method
}
}
One thing to note here is that EasyTraker requires a context before you can use it. If you attempt to call any of its methods but did not pass first a context, you may end up with an IllegalStateException.
In the above example, in the onStart() and onStop() methods the context is passed as an argument to activityStart() and activityStop(), but if you need to make EasyTracker calls in other classes or methods, you’ll need to call EasyTracker’s setContext(Context context) method first:
Context context= this; // Get current context. EasyTracker.getInstance().setContext(context); // Set context // EasyTracker is now ready for use.
6. Tracking events
Tracking events is just as easy as tracking activities, you just need a Tracker object and call the trackEvent(String category, String action, String label, int value) method.
public class MainActivity extends Activity {
private Tracker tracker;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set context
EasyTracker.getInstance().setContext(getApplicationContext());
// Instantiate the Tracker
tracker = EasyTracker.getTracker();
// Add tracking functionality to "Rate" button
Button rate = (Button) findViewById(R.id.rate);
rate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// The rest of your code
tracker.trackEvent("Buttons Category", "Rate", "", 0L);
}
});
// Add tracking functionality to "Share" button....
}
}
In this particular example I don’t need a label nor a value, that is why I set for the last 2 parameters of trackEvent() method, an empty string a 0 (zero), but depending of your needs you may populate them with some data.
7. Debugging
Debugging helps you deal with troubleshooting, and make you sure that the data actually is sent to the server. To set the Google Analytics in debug mode, add the following setting in the analytics.xml
<bool name="ga_debug">true</bool>
Once your are in debug mode, you can watch the log information in LogCat:
Waiting for the big moment!
If everything is configured correctly, the reports should appear on live. Usually it takes about 24 hours to see the data in your account.
What happens if my application is used when no network is available?
Just in case you asked this yourself…, all the events are persisted in a local storage, and they will be sent the next time your app is running and dispatch is called.
Last but not least
One important thing not to be forgotten: you must indicate to your users, either in the application itself or in your terms of service, that you reserve the right to anonymously track and report a user’s activity inside of your app.
Android Google Analytics SDK offers more than tracking activities and events, see: https://developers.google.com/analytics/devguides/collection/android/v2/ to get the most out of it.
Please visit the Android Tutorials page for more tutorials.
Android Asset Studio – The easiest way to create icons for your android apps!
Android Asset Studio is an online utility that lets you generate all kind of icons you may need for your android applications, starting with launcher icons, action bar and tab icons, notification icons, and menu icons. It even includes a simple 9-patch generator allowing you to create 9-patch images.
One of the trickier parts when creating the icons is that you should create them for all kinds of resolutions: ldpi, mdpi, hdpi, and xhdpi. With Android Asset Studio this is as simple as uploading an image. The tool generates automatically for you all the versions of the icon under all resolutions, and make them available as a downloadable zip archive.
The icons may be generated from an image uploaded, or from a clipart library, or from text. It’s a very convenient tool and I highly recommend using it if you want to have professional, good looking icons on all resolutions.
Android – [APP] Amazing Drunk Detection Scanner
Ready to go to party? Then don’t forget to put Amazing Drunk Detection Scanner in your pocket!
Drunk Detection Scanner is a simple application that helps you make fun with your friends. Make fun of your best friends by scanning their eye, and determine how drunk are they!
Here is how the prank works:
1. Just in the middle of the party open the Drunk Detection Scanner and say something like “Alright gentlemen, time to do some analysis!”
2. Invite one of your friends and tell him that this app will reveal how drunk he is.
3. Aim the camera close to your friend’s eye
4. Focus
5. Press “Start Scanning”
6. Wait till the result is calculated
7. Have fun!
DISCLAIMER:
Amazing Drunk Detection Scanner is a simple application designed for entertainment purposes only. It does not encourage the consumption of alcohol, and it does not take any legal responsibility.
Android – Scheduling an application to start later.
Recently I have been working on a simple application that should have the ability to start itself after a period of time, after the application is closed. Hopefully, it turned out that this is quite simple to implement, and to achieve this, the AlarmManager in conjuction with a BroadcastReceiver can be used.
The basic idea is as follows: the AlarmManger registers an intent, when the alarm goes off, the intent that had been registered automatically will start the target application if it is not already running. The BroadcastReceiver will be listening for that intent, and when the intent is received, it will start the desired activity from the application.
The broadcast receiver implementation looks like this:
public class OnAlarmReceive extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(Globals.TAG, "BroadcastReceiver, in onReceive:");
// Start the MainActivity
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
Register the OnAlarmReceive in the AndroidManifest file:
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
// ......
<receiver
android:name=".OnAlarmReceive" />
</application>
And finally, here’s how to setup the alarm:
/**
* Sets up the alarm
*
* @param seconds
* - after how many seconds from now the alarm should go off
*/
private void setupAlarm(int seconds) {
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(getBaseContext(), OnAlarmReceive.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
MainActivity.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Log.d(Globals.TAG, "Setup the alarm");
// Getting current time and add the seconds in it
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, seconds);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
// Finish the currently running activity
MainActivity.this.finish();
}
The last line from the code – finishing the current activity – is optional of course, but in case you need to finish the activity, here’s how to do.
For a live demo of the code, download the Amazing Cracked Screen application and see how it works. There you have the possibility to set up the delay in seconds when the application should start later and show the “broken” screen.
Introducing “Even or Odd” – My First Android Game :)
Hello everyone,
I would like to introduce you the freshly cooked “Even or Odd” game, an addictive casual game for Android.
The idea of the game is pretty simple: you are given a series of numbers, and have 30 seconds at your disposal to answer if the given numbers are even or odd ones. Give a correct answer and you get +100 points, you give a wrong answer and you go down: -100 points. Try to give as many correct answers as you can in 30 sec.
This is my first attempt into this kind of Android apps. What was new from what I did previously, is that I made use of MediaPlayer to play sounds. Using MediaPlayer to play sounds will be the subject of another tutorial in the upcoming period of time. Stay tuned.
Give it a try and let me know your high score
.
How to verify an RSS Feed if New Articles have been published.
Recently I built an rss app for a site that publishes daily IT News – ITMoldova.com. The main feature of application is to launch a service in background (at a given interval of time), and check if new articles have been published on http://itmoldova.com site. If it turns out that new articles have been published, then fire a notification message and notify the user about this, something like this: “4 New Articles Published on ITMoldova.com”.
The mechanism to identify if new articles have been published on the site (and how many) is pretty straightforward: when the application is installed and launched for the first time, it parses the Rss Feed and creates a new entry in the SharedPreferences with the value of <pubDate> element, of the first item from the rss list (pubDate = publication date). Then, everytime the service starts, it parses the RSS Feed and checks the value of first item from the rss list against the value stored in SharedPreferences, if the value stored in SharedPreferences is less than value returned by the service, then it means that there are new articles and it’s time to notify the user! Lastly, update the SharedPreferences with the most recent pubDate.
For the sake of simplicity and keeping things consistent, I will post here only snippets of most relevant code, but this will be good enough to give you an idea about how things works.
To compare the dates we need to convert them to milliseconds. The getTime() method of Date class can help us return the number of milliseconds of a given date:
Date date=new Date(); int timeMilliseconds=date.getTime();
Below is the implementation of verifyDates(String, String) method that will be used by the Service. The method takes 2 string parameters, the pubDate of rss item, and the pubDate stored in SharedPreferences.
public class Tools {
public int newArticles;
public boolean hasMoreArticles = true;
public void verifyDates(String rssPubDate, String sharedPrefLastPubDate) {
if (hasMoreArticles) {
SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
Date dLastPubDate = null;
Date dRssPubDate = null;
try {
dLastPubDate = df.parse(sharedPrefLastPubDate.substring(5));
dRssPubDate = df.parse(rssPubDate.substring(5));
} catch (ParseException e) {
Log.d("GREC", "Exception in verifayDates: " + e.getMessage());
e.printStackTrace();
}
//We want to count how many new articles were published.
if (dRssPubDate.getTime() > dLastPubDate.getTime()) {
newArticles++;
} else {
hasMoreArticles = false;
}
}
}
}
The service will parse the Rss Feed and do the comparison. Also, it will launch a status bar notification if it turns out that new articles were published.
public class RssService extends IntentService {
public RssService() {
super("ITMoldovaRssService");
}
@Override
protected void onHandleIntent(Intent intent) {
// Retrieve the date from SharedPreferences
String lastPubDate = getDateFromSharedPrefs();
// The AndroidFeedParser class helps us parse the Rss Feed.
AndroidFeedParser parser;
try {
parser = new AndroidFeedParser(new URL("http://itmoldova.com/feed/"));
List<Message> list = parser.parse();
if (list != null) {
for (int i = 0; i < list.size(); i++) {
// Verify the pubDate of each item, against pubDate stored in SharedPreferences
tools.verifyDates(list.get(i).getDate(), lastPubDate);
}
// Get the last pubDate and save it to SharedPreferences.
lastPubDate = list.get(0).getDate();
saveToSharedPreferences(lastPubDate);
}
} catch (MalformedURLException e) {
Log.d("GREC", "Malformed URL Exception: " + e.getMessage());
e.printStackTrace();
}
if (tools.newArticles > 0) {
displayNotification();
} else {
Log.d("GREC", "No new articles ");
}
}
}
The service begins with parsing the Rss Feed and return the list of items:
List<Message> list = parser.parse();
then iterate through it comparing the publication date:
for (int i = 0; i < list.size(); i++) {
// Verify the pubDate of each item, against pubDate stored in SharedPreferences
tools.verifyDates(list.get(i).getDate(), lastPubDate);
}
and then ends getting the most recent publication date and saving it to SharedPreferences:
// Get the last pubDate and save it to SharedPreferences. lastPubDate = list.get(0).getDate(); saveToSharedPreferences(lastPubDate);
If it turns out that new articles were published, display a status bar notification.
if (tools.newArticles > 0) {
displayNotification();
}
How to parse an XML feed and how to display a status bar notification are some helper topics you may need to take a look in order to fully complete this task.














