Facoltà di Ingegneria Corso di Studi in Ingegneria Informatica

tesi di laurea specialistica Investigating Mobile Solutions for News Spreading

Anno Accademico 2011/2012

relatore Ch.mo prof. Marcello Cinque

candidato Pasquale Perozzino matr. 885/261

To my family

Investigating Mobile Solutions for News Spreading

Index

Introduction 5

Chapter 1. Background: Cloud, Facebook and Fanpage 9

1.1 Cloud 9 1.2 Facebook 11 1.3 Fanpage 14

Chapter 2. Android OS 19

2.1 The and the Android challenge 19 2.2 The stack 19 2.3 Android component architecture 24 2.4 Android development framework 30 2.5 The AndroidManifest File 31 2.6 Android User Interface 32

Chapter 3. Requirements analysis and architectural solutions 36

3.1 Requirements 37 3.2 The Fanpage app use cases 38 3.3 Architectural solutions 41

Chapter 4. Design and implementation of the prototype 57

4.1 Preliminary considerations 57 4.2 Main Activities 64 4.2.1 The registration to GCM 64 4.2.2 The push handling 68 4.2.3 The Facebook login 70 4.3 The Fanpage app: a global overview 75 4.3.1 The registration to GCM 75 4.3.2 The push handling 81 4.3.3 The Facebook login 83

III Investigating Mobile Solutions for News Spreading

Chapter 5. The Fanpage app: code and use examples 87

5.1 The code 87 5.1.1 The registration to GCM 88 5.1.1.1 The BaseActivity class 88 5.1.1.2 The GCM_Registration class 88 5.1.1.3 The GCM_registrationReceiver class 90 5.1.2 The push handling 92 5.1.2.1 The GCM_MessageReceiver class 92 5.1.2.2 The GCM_MessageReceivedActivity class 93 5.1.3 The Facebook login 94 5.1.3.1 The Login class 94 5.2 Examples of use 97 5.2.1 The registration to GCM 98 5.2.2 The push handling 101 5.2.3 The Facebook login 102

Conclusions 104 Future Works 106 Bibliography 108 Sitography 109

IV Investigating Mobile Solutions for News Spreading

Introduction

Communication takes place when one mind so acts upon its environment that another mind is influenced, and in that other mind an experience occurs which is like the experience in the first mind, and is caused in part by that experience (Ivor Armstrong Richards). Interest in communication has been stimulated by advances in science and technology, which, by their nature, have called attention to man as a communicating creature. Among the first and most dramatic examples of the inventions resulting from technological ingenuity were the telegraph and telephone, followed by others like wireless radio and telephoto devices. The development of popular newspapers and periodicals, broadcasting, motion pictures, and television led to institutional and cultural innovations that permitted efficient and rapid communication between a few individuals and large populations; these media have been responsible for the rise and social power of the new phenomenon of mass communication.[6] But what does mass communication mean? Mass communication is the transmission process of a message to a large group of people using some form of media such as newspapers, television, or the Internet. Someone could assert that, nowadays, mass communication has a profound impact on virtually every aspect of our life; and, what’s more, the information reported may not be authentic from every angle. There are various opinions regarding these questions. Some

5 Investigating Mobile Solutions for News Spreading believe that the main effects of mass communication are harmless; others think that it may influence only values already accepted and operating in the culture while someone else believes that mass communication provides potent sources of informal education and persuasion. In this period, indeed, news is more entertaining than informing, it’s mostly politically corrupted (it can be easily manipulated to influence the minds of the audiences), and supplies gossip, sex, and violence rather than the actual social, territorial and political issues. Political news is more about scandals and personal problems than about their ideologies. Along with this setting, the voters and the public opinion are left with paid political propaganda containing only meaningless slogans making them disinterested and cynical about politics. The success of public communication as an instrument of commercial advertising has also been constant and noticeable. But now there is a big change going on. Over the past several years, users have moved increasingly from slow dial-up connections to high-speed “always on” connections that have changed how people view and use the Internet: the World Wide Web has turned the Internet into a major mass medium that provides news, entertainment, and community interaction. The Web offers a mix of content providers, including traditional media companies, new media companies offering publications available only on the Web, aggregator sites that offer help in navigating the Web, and individuals who have something they want to say. [1] Moreover, the easy access to the personal computer and to global communications networks makes it feasible for virtually anyone to publish his or her opinions on the Internet. So what is the main effect of this change? While in the last decades we have just been passive receivers of what newspaper, radio and television wanted to let us know, now we find ourselves overcome by the several ways to interact with another person. Most people today learn how to us a smartphone, a

6 Investigating Mobile Solutions for News Spreading laptop or a desktop computer at a very young age and, with the increased amount of easy to use web writing platforms, everyone is posting online on their own will. Sometimes, this means communicate intimacy aspects of about their personal lives via blogging. Other times, private citizens will report on the news themselves. This has brought to a couple of consequences. First, we are communicating without any worries, writing who we are, what we like and so on: this is something we would probably not do when talking to another person. Second, our relation with the news has changed dramatically, increasing transparency in some ways and obfuscating the real issues in others: each person assumes a central role in broadcasting certain news or deciding which contents are interesting for themselves. In which way? There are various tools that can allow you to communicate one-to-one or one-to-many, depending on our communication needs: Blog (a website that allows a Web author to simply and easily share thoughts and ideas with other Web users), RSS Feeds (allows you to track new content on a website or blog or to keep up with the latest news stories), Podcast (it expands the concept of RSS feeds into multimedia formats, such as audio programs or music videos), Mailing list (which distributes information to an e-mail subscription list) and, of course, Facebook and Tweeter (which everyone publishes his or her opinions with). All these reading and activities we do on a day-to-day has always been made thanks to the desktop browsing. But the introduction of the iPhone by Apple has changed the prospective, slowly moving the desktop browsing to the mobile browsing. Before the summer of 2012, 362 million mobile phones has been sold and it is increasingly rare to see someone who don’t have smartphones or tablet devices. With the arrival of the iPhone 5, the Samsung SIII, the new Windows Mobile and the new tablets from Amazon, Microsoft and Apple, the world is progressively mobile first. By this time, the distinction mobile-desktop is very clear: desktop computer are used for work-related business and browsing, while mobile phones are used for casual browsing (news, social media, tech, blogs, etc). As a consequence to these assumptions, the majority of the leading news agencies that have their own websites where the Internet users can read the news online (for instance,

7 Investigating Mobile Solutions for News Spreading the New York Times and The Washington Post, but also Corriere della Sera and La Repubblica), have invested a lot of money to re-design their own desktop website in order to turn it into a mobile application and a mobile website. A mobile website is nothing else that any other website but it is designed for the smaller, touch-screen display. On the other hand, mobile apps are applications that can be installed on our device, rather than being rendered within a browser. The app may pull content and data from the Internet, in similar fashion to a website, or it may download the content so that it can be accessed without an Internet connection. Fanpage, like the previously mentioned websites, is mainly a news website that is grown thanks to its social soul: catching the opportunity that Facebook offers (in giving the chance to make a third party applications on their platform), Ciaopeople developers have produced their own Facebook application, building the Fanpage success tracking readers’ interactions with the application itself. In this way, Fanpage is able to understand which- news-is-interesting-for-which-person. The drawback is that the Fanpage application, on the mobile side, doesn’t give back the comfortable user-experience that the reader has when “surfs” on the desktop system. That’s why, during the last months, Ciaopeople (the company that own and created the Fanpage project) has finally realized that it was the time to create a mobile app, still connected with the Facebook platform (not anymore like a third party application, but just as bare user of their API) but designed and hoc for the devices that would host it. Starting from November 2011, the collaboration between me, prof.Cinque and Ciaopeople begun with the final goal of realizing a prototype of an Android application that would preserve the main characteristics that made Fanpage the first web magazine in Italy.

8 Investigating Mobile Solutions for News Spreading

Chapter 1 Background: Cloud, Facebook and Fanpage

1.1 Cloud

Once upon a time, there were “social” networks that helped people to connect with friends. Nowadays, every application and web service can be considered social. Why? Simply put, it’s because people like to share. Whether it’s publishing a high score in a video game or posting a picture where friends can see it, mobile users have become accustomed to showing their digital life to their network of friends, family, and colleagues. The vast amount of ways in which people can be connected online has sparked the interest of cloud computing services. Cloud computing services have been developing ways to tap into the Web 2.0 world and establish means of turning the flow of information and

communication into business potential. What do we mean for “cloud computing”? The following definition of cloud computing has been developed by the U.S. National Institute of Standards and Technology (NIST): “Cloud computing is a model for enabling convenient, on-demand network access to a shared pool of configurable computing resources (e.g., networks, servers, storage, applications, and services) that can be rapidly provisioned and released with minimal management effort or service provider interaction. This cloud model promotes availability and is composed of five essential characteristics, three service models, and four

9 Investigating Mobile Solutions for News Spreading deployment models”[7] Characteristics The characteristics of cloud computing include on-demand self service, broad network access, resource pooling, rapid elasticity and measured service. On-demand self service means that customers (usually organizations) can request and manage their own computing resources. Broad network access allows services to be offered over the Internet or private networks. Pooled resources means that customers draw from a pool of computing resources, usually in remote data centres. Services can be scaled larger or smaller; and use of a service is measured and customers are billed accordingly. Service models The cloud computing service models are Software as a Service (SaaS), Platform as a Service (PaaS) and Infrastructure as a Service (IaaS). In a Software as a Service model, a pre-made application, along with any required software, operating system, hardware, and network are provided. In PaaS, an operating system, hardware, and network are provided, and the customer installs or develops its own software and applications. The IaaS model provides just the hardware and network; the customer installs or develops its own operating systems, software and applications.

Therefore cloud computing is a computing model that is tied to virtualized and scalable resources that are provided as a service over the Internet. With these services users run applications like email and networking applications over the Internet without actually having to purchase software, server space to store information, or provide their own technical support to resolve problems. Instead, users simply access the applications and let the application services take care of the rest. Software, processing, storage, and support might all be supported by the cloud. Examples of this sort of service are Hotmail, Gmail, and Facebook. But Facebook is not a cloud. It's not SaaS. It's a social networking application. Just like the Bank of America web site that provides access to a checking account. You can log on to it and it provides a service. Plain and simple.

10 Investigating Mobile Solutions for News Spreading

Facebook uses a lot of large-scale web application technologies. It may run some of its processing on external clouds and its internal datacenters using a cloud operating model. It just provides SaaS applications for advertisers and businesses. The messaging and chat services are SaaS as are the ability to share updates, links, videos, events, contact information etc. So, it's probably safe to say that Facebook is a “user” of clouds. But merely being a user of clouds doesn't make you a cloud yourself. We have talked about Facebook. But what is Facebook, and what made it the top social network?

1.2 Facebook

Facebook is the biggest and most popular social networking website in the world. With more than 950 million active users has established its leadership position in 126 out of 137 countries. Countries where Facebook is not the leader:

• Russian territories where there is an on-going battle between the two main local players: V Kontakte and Odnoklassniki.

• China where QZone claims 560 million users, followed by Tencent Weibo (337 million) e Sina Weibo (334 million)

• Iran where it’s hard to access Facebook due to state censorship • Vietnam and Latvia still likely to use local social networks: Zing and Draugiem respectively

Figure 1.1 - World map of social networks 11 Investigating Mobile Solutions for News Spreading

Facebook is universal. It can connect people from Bacoli (me) with people all the way in Nampuca, Mozambico. You can choose to post quotes or what you are doing, play games, share photos, articles, videos, and links from other sites. Famous movie or music stars can keep in touch with their fans, companies can make business or can promote their own events and persuade people to being part of it. Everyone can keep in touch with friends and family, so they can find out how are you doing, how do you look like. Besides these peculiarities, Facebook is safe and free to use. Also, you can personalize your privacy: for instance, you can limit who can see certain things on your profile or not permit anyone to find you by a Google research. At the core of Facebook is the social graph, the tracks all the people relations and all the things they care about. It has been referred to as "the global mapping of everybody and how they're related"[8]. Also, Facebook has created Open Graph protocol so that the social graph could include pages people “liked” anywhere on the web. Facebook has also extended Open Graph to add arbitrary actions and objects created by mobile apps. As the “like” button is omnipresent in all the websites, the “like” expressed in apps are now part of the Facebook experience, as well. Anyone can easily create and run applications on Facebook. This is one of the uniqueness of Facebook. This site is not only a friendship site that collects friends, but it also could be developed in accordance with user needs. In order to create a Facebook app, you first have to add the Facebook developer application to your profile. Then you must have access to a reliable Web server where you store your application since Facebook does not host third-party programs. Applications can be Web-based, desktop-based or mobile-device-based. The Facebook API is currently in an on-going transitional phase. The original Facebook API was a Representational State Transfer (REST) API, but this API is being phased out and is officially deprecated. All Facebook development moving forward should use Facebook’s new Graph API. The Graph API is where you will find support for all new and future Facebook features, and it

12 Investigating Mobile Solutions for News Spreading is continuously updated to include the full set of original features from the REST API. Note that the Graph API only supports responses as JavaScript Object Notation (JSON) objects. A basic summary of these APIs follows.

Graph API The Graph API presents a simple, consistent view of the Facebook social graph, uniformly representing objects in the graph and the connections between them. Every object in the social graph has a unique ID. You can access the properties of an object by requesting https://graph.facebook.com/ID. Alternatively, people and pages with usernames can be accessed using their username as an ID. All responses are JSON objects.

FQL Facebook Query Language, or FQL, enables you to use a SQL-style interface to query the data exposed by the Graph API. It provides for some advanced features not available in the Graph API such as using the results of one query in another. Developers can also use the Facebook Query Language (FQL), which is similar to Structured Query Language (SQL). With FQL, a developer can obtain information about any user who downloads his or her application. In a way, that's really what Facebook applications are all about -- gathering information about users. Developers could use this information as a way to create target audiences for advertising or build a consumer base for a particular product.

Legacy REST API The REST API enables you to interact with Facebook web site programmatically via HTTP requests. In terms of Facebook's API, a REST-interface means that applications interfacing with Facebook send method calls using Hypertext Transfer Protocol (HTTP) GET or POST requests. This means that Facebook applications can retrieve information from member

13 Investigating Mobile Solutions for News Spreading

profiles, post messages to profiles or do both. [9]

Facebook document the social graph of its users and push them to make new connections. The company has powerful incentives to expand the social graph: knowing users’ connections and predilections allows them to sell targeted advertisements, deliver recommendations, and initiate partnerships around e-commerce and real-world commerce alike. For app developers, the opportunities are much the same. Adding Facebook functionality to a mobile app can open up vast new opportunities for monetization and new features, but there is plenty of other cool stuff in store, too. Connecting your app to the social graph makes it easier for users to log in, manage their account, and transfer information in and out. And Facebook has built extensive APIs and frameworks that can spare developers from having to reinvent the wheel. [2]

Fanpage developers didn’t want, indeed, to reinvent the wheel: they have taken the Facebook APIs, made them and, starting from today, connected to the “Google Cloud”.

1.3 Fanpage

Fanpage is one of the main projects of the Neapolitan society Ciaopeople, which is “a media company specialized in high traffic web applications promoted with Facebook and Google”.[10] The start up company is born at the end of 2007 and on September 2009 Fanpage.it goes on the web. At the beginning of its adventure, Fanpage was mainly an online newspaper financed by the investments coming from the income connected to the selling of the advertising spaces.

14 Investigating Mobile Solutions for News Spreading

In 22th December 2011, the Fanpage app runs over the Facebook platform: the app is the first in Italy to use the social actions, so that in 5 months more than 1 million and half of people has been profiled.

Figure 1.2 – Fanpage Facebook application

Nowadays, Fanpage is a traditional nanopublishing network (14 vertical magazines) with

Google traffic model, based on the creation of original content, optimizing SEO and link building (with either natural or forced matrix).

15 Investigating Mobile Solutions for News Spreading

Figure 1.3 – Fanpage website

Fanpage results to be an innovative project based on an excellent work of search engine indexing (the 45% of the traffic comes from Google) and on a contents’ viral campaign over the social media (the 45% of the access to the website comes by Facebook).

16 Investigating Mobile Solutions for News Spreading

In 2012 it sees an increasing of his popularity till the achievement of an average of more than 500k readers.

Figure 1.4 – Fanpage statistics: Audiweb and Google Analitycs As a consequence of the amount of fans over Facebook (at the end of September 2012, they are more than 1265k), today Fanpage is the first European newspaper.

Figure 1.5 – Fanpage fan growth

Undoubtedly, the key reason of the success of Fanpage has been to base their app over the social action, that is the act to take into account the actions and the reactions of, in this case, the end-users; so when a Facebook user interacts with Fanpage, every clicks is recorded and their own “key-word cloud” is increased. As a outcome of the profile

17 Investigating Mobile Solutions for News Spreading analysis, the systems starts to “suppose” which are the main tastes of the readers, and will start to push which it retains to be news that can pique the readers’ curiosity. If it succeed in its intent, the user will be likely to share the news over the social networks, that is nothing else that pure publicity for Fanpage. Even though most of the publicity comes by the Facebook platform, Fanpage has also an increasing quantity of followers on two of the most spread social networks: Google+ and Twitter.

Figure 1.6 – Fanpage on Google+

Figure 1.7 – Fanpage on Twitter Hopefully there will be, in the next future, a further platform in which the “Fanpage philosophy” can be spread: Android.

18 Investigating Mobile Solutions for News Spreading

Chapter 2 Android OS

2.1 The Open Handset Alliance and the Android challenge

Android is a comprehensive open source platform designed for mobile devices. It is championed by Google and owned by Open Handset Alliance, a group of 84 technology and mobile companies who have come together “to accelerate innovation in mobile and offer consumers a richer, less expensive, and better mobile experience.” Android is the vehicle to do so. When designing Android, the team looked at which mobile device constraints likely were not going to change for the foreseeable future. For one, mobile devices are battery powered, and battery performance likely is not going to get much better any time soon. Second, the small size of mobile devices means that they will always be limited in terms of memory and speed.

2.2 The stack

The entire Android stack, from low-level modules all the way to native libraries, and from the application framework to complete applications, is totally open. The Android operating system consists of various layers.

19 Investigating Mobile Solutions for News Spreading

Figure 2.1 - The Android stack

Linux Kernel It is built on top of Linux, which is a portable platform that is relatively easy to compile on various hardware architectures. What Linux brings to Android is a level of hardware abstractions. By basing Android on Linux, we don’t have to worry too much about underlying hardware features. Most low-level parts of Linux have been written in fairly portable C code, which allows for third parties to port Android to a variety of devices. Linux is a highly secure system, having been tried and tested through some very harsh environments over the decades. Android heavily relies on Linux for security. All Android applications run as separate Linux processes with permissions set by the Linux system. As such, Android passes many security concerns to the underlying Linux system. Moreover, Linux comes with a lot of very useful features. Android leverages many of them, such as support for memory management, power management, and networking.

20 Investigating Mobile Solutions for News Spreading

Native Libraries The native libraries are C/C++ libraries, often taken from the open source community in order to provide necessary services to the Android application layer. Among others, they include:

• Webkit A fast web-rendering engine used by Safari, Chrome, and other browsers

• SQLite A full-featured SQL database

• Apache Harmony An open source implementation of Java

• OpenGL 3D graphics libraries

• OpenSSL The secure locket layer

Although many of these libraries are used as-is, one notable exception is , which is basically a rewritten version of the standard C library. Bionic is used for two reasons:

• Technology To make it purpose-built for tiny, battery-powered devices

• License To make it license-friendly for others who might want to adopt it and change it

Android Runtime The Runtime layer makes Android something different from a simple mobile Linux implementation; the core libraries and the Dalvik Virtual Machine form it. Dalvik is a purpose-built virtual machine designed specifically for Android, developed by Dan Bornstein and his team at Google. While the Java virtual machine (VM) was designed to be a one-size-fits-all solution, the Dalvik team felt they could do a better job by focusing strictly on mobile devices: they

21 Investigating Mobile Solutions for News Spreading looked at which constraints specific to a mobile environment are least likely to change in the near future. One of these is battery life, and the other is processing power. Dalvik was built from the ground up to address those constraints. Another difference is that in Java, you write your Java source file, compile it into a Java byte code using the Java compiler, and then run this byte code on the Java VM. In Android, things are different. You still write the Java source file, and you still compile it to Java byte code using the same Java compiler. But at that point, you recompile it once again using the Dalvik compiler to Dalvik byte code. It is this Dalvik byte code that is then executed on the Dalvik VM.

Figure 2.2 - Java vs Dalvik

Application Framework In the application framework layer, there are numerous Java libraries specifically built for Android. You can also find many services (or managers) that provide the eco-system of capabilities your application can tap into, such as location, sensors, WiFi, telephony, and so on.

22 Investigating Mobile Solutions for News Spreading

Developers have full access to the same framework APIs used by the core applications. The application architecture is designed to simplify the reuse of components; any application can publish its capabilities and any other application may then make use of those capabilities (subject to security constraints enforced by the framework). This same mechanism allows components to be replaced by the user.

Applications The applications are what end users find valuable about Android. They can come preinstalled on the device or can be downloaded from one of the many Android markets. An application is a single application package (APK) file. An APK file roughly has three main components. An API consists of the following major components:

• Dalvik executable This is all your Java source code compiled down to a Dalvik executable. This is the code that runs your application.

• Resources Resources are everything that is not code. Your application may contain a number of images and audio/video clips, as well as numerous XML files describing layouts, language packs, and so on. Collectively, these items are the resources.

• Native libraries Optionally, your application may include some native code, such as C/C++ libraries. These libraries could be packaged together with your APK file.

Android applications must be signed before they can be installed on a device. One way in which Android is quite different from other platforms is the distribution of its apps. On most other platforms, such as iPhone, a single vendor holds a monopoly over the distribution of applications. On Android, there are many different stores, or markets. Each market has its own set of policies with respect to what is allowed, how the revenue is split, and so on. As such, Android is much more of a free market space in which vendors compete for business.

23 Investigating Mobile Solutions for News Spreading

2.3 Android component architecture

Android is a component-based platform. Applications are built up from loosely coupled, reusable, extendable, and replaceable components that fall within well-defined roles.

Activities An activity is usually a single screen that the user sees on the device at one time. An application typically has multiple activities, and the user flips back and forth among them. As such, activities are the most visible part of your application. Just like a website consists of multiple pages, so does an Android application consist of multiple activities. Just like a website has a “home page,” an Android app has a “main” activity, usually the one that is shown first when you launch the application. And just like a website has to provide some sort of navigation among various pages, an Android app should do the same. On the Web, you can jump from a page on one website to a page on another. Similarly, in Android, you could be looking at an activity of one application, but shortly after you could start another activity in a completely separate application. For example, if you are in your Contacts app and you choose to text a friend, you’d be launching the activity to compose a text message in the Messaging application. Launching an activity can be quite expensive. It may involve creating a new Linux process, allocating memory for all the UI objects, inflating all the objects from XML layouts, and setting up the whole screen. Since we’re doing a lot of work to launch an activity, it would be a waste to just toss it out once the user leaves that screen. To avoid this waste, the activity life cycle is managed via Activity Manager. Activity Manager is responsible for creating, destroying, and managing activities. For example, when the user starts an application for the first time, the Activity Manager will create its activity and put it onto the screen. Later, when the user switches screens, the Activity Manager will move that previous activity to a holding place. This way, if the user wants to go back to an older activity, it can be started more quickly. Older activities that

24 Investigating Mobile Solutions for News Spreading the user hasn’t used in a while will be destroyed in order to free more space for the currently active one. This mechanism is designed to help improve the speed of the user interface and thus improve the overall user experience. Programming for Android is conceptually different than programming for some other environments. In Android, you find yourself responding more to certain changes in the state of your application rather than driving that change yourself. It is a managed, container-based environment similar to programming for Java applets or servlets. So, when it comes to an activity life cycle, you don’t get to say what state the activity is in, but you have plenty of opportunity to say what happens during the transitions from state to state. The figure 2.3 shows the states that an activity can go through.

Figure 2.3 - Activity life cycle

25 Investigating Mobile Solutions for News Spreading

 Starting state When an activity doesn’t exist in memory, it is in a starting state. While it’s starting up, the activity will go through a whole set of callback methods that you as a developer has an opportunity to fill out. Eventually, the activity will be in a running state. The transition from starting state to running state is one of the most expensive operations in terms of computing time, and this also directly affects the battery life of the device. This is the exact reason why we don’t automatically destroy activities that are no longer shown. The user might want to come back to them, so we keep them around for a while.

 Running state The activity in a running state is the one that is currently on the screen and interacting with the user. We also say this activity is in focus, meaning that all user interactions—such as typing, touching the screen, and clicking buttons—are handled by this one activity. As such, there is only one running activity at any given time. The running activity is the one that has priority in terms of getting the memory and resources it needs to run as quickly as possible. This is because Android wants to make sure the running activity is zippy and responsive to the user.

 Paused state When an activity is not in focus (i.e., not interacting with the user) but still visible on the screen, we say it’s in a paused state. We often see this case with dialog boxes that come up in front of an activity, causing it to become paused. All activities go through a paused state en route to being stopped. Paused activities still have high priority in terms of getting memory and other resources. This is because they are visible and cannot be removed from the screen without making it look very strange to the user.

26 Investigating Mobile Solutions for News Spreading

 Stopped state When an activity is not visible, but still in memory, we say it’s in a stopped state. Stopped activity could be brought back to the front to become a Running activity again. Or, it could be destroyed and removed from memory. The system keeps activities around in a stopped state because it is likely that the user will still want to get back to those activities some time soon, and restarting a stopped activity is far cheaper than starting an activity from scratch. That is because we already have all the objects loaded in memory and it has simply to bring it all up to the foreground. Stopped activities can be removed from memory at any point.

 Destroyed state A destroyed activity is no longer in memory. The Activity Manager decided that this activity is no longer needed and has removed it. Before the activity is destroyed, it can perform certain actions, such as save any unsaved information. However, there’s no guarantee that your activity will be stopped prior to being destroyed. It is possible for a paused activity to be destroyed as well. For that reason, it is better to do important work, such as saving unsaved data, en route to a paused state rather than a destroyed state.

Intents Intents are messages that are sent among the major building blocks. They trigger an activity to start up, tell a service to start or stop, or are simply broadcasts. Intents are asynchronous, meaning the code that sends them doesn’t have to wait for them to be completed. An intent could be explicit or implicit. In an explicit intent, the sender clearly spells out which specific component should be on the receiving end. In an implicit intent, the sender specifies the type of receiver.

27 Investigating Mobile Solutions for News Spreading

Services Services run in the background and don’t have any user interface components. They can perform the same actions as activities, but without any user interface. Services are useful for actions that we want to perform for a while, regardless of what is on the Services screen. For example, you might want your music player to play music even as you are flipping between other applications. Services have a much simpler life cycle than activities (see the figure 2.4).

Figure 2.4 - Service life cycle

You either start a service or stop it. Also, the service life cycle is more or less controlled by the developer, and not so much by the system. Consequently, we as developers have to be mindful to run our services so that they don’t consume shared resources unnecessarily, such as the CPU and battery.

Content Providers Content providers are interfaces for sharing data between applications. By default, Android runs each application in its own sandbox so that all data that belongs to an application is totally isolated from other applications on the system. Although small amounts of data can be passed between applications via intents, content providers are much better suited for sharing persistent data between possibly large datasets. As such, the content provider API nicely adheres to the CRUD principle. Figure 2.5 illustrates how the content provider’s CRUD interface pierces the application boundaries and allows other apps to connect to it to share data.

28 Investigating Mobile Solutions for News Spreading

Figure 2.5 - Content provider

The Android system uses this mechanism all the time. For example, Contacts Provider is a content provider that exposes all user contact data to various applications. Settings Provider exposes system settings to various applications, including the built-in Settings application. Media Store is responsible for storing and sharing various media, such as photos and music, across various applications.

Broadcast Receivers Broadcast receivers are Android’s implementation of a system-wide publish/subscribe mechanism, or more precisely, an Observer pattern. The receiver is simply dormant code that gets activated once an event to which it is subscribed happens. You can also send your own broadcasts from one part of your application to another, or to a totally different application. Broadcast receivers themselves do not have any visual representation, nor are they actively running in memory. But when triggered, they get to execute some code, such as starting an activity, a service, or something else.

29 Investigating Mobile Solutions for News Spreading

Notifications Notifications allow to signal users without interrupting their current Activities. They’re the preferred technique for getting a user’s attention from within a Service or Broadcast Receiver. For example, when a device receives a text message or an incoming call, it alerts you somehow (by flashing lights, making sounds, displaying icons, or showing dialog messages).

Widget Widgets are little applications that can be placed on the home screen of your Android device. A Widget gets its data on a periodic timetable. A Widget runs as part of the homescreen process and can display an application's most timely or otherwise relevant information at a glance. The standard Android system image includes several widgets, including a widget for the Analog Clock, Music, and other applications.

2.4 Android development framework

The Android software development kit (SDK) includes everything you need for developing, testing, and debugging Android applications. Let’s see what’s available for download:

• The Android APIs that let developers access the Android software stack. These are the same libraries used by Google to create native Android applications.

• Development Tools to compile and debug your applications such as Dalvik Debug Monitoring Service (DDMS) for monitoring and controlling the Dalvik virtual machines on which you’re debugging your applications, Android Asset Packaging Tool (AAPT) for creating distributable Android package files (.apk) and Android Debug Bridge

30 Investigating Mobile Solutions for News Spreading

(ADB) that provides a link to a running emulator letting you copy files, install .apk files and run shell commands.

• The Android Emulator an interactive emulator that lets you see how your applications will look and behave on a real device. All Android apps run within the Dalvik Virtual Machine so that the emulator is a valuable environment as it is hardware-neutral so providing a better independent test environment than any single hardware implementation.

• Full Documentation of the available APIs • Sample Code that demonstrates some of the possibilities available using Android and how to use individual API features.

• Online Support provided by the developers community included the proper Google Groups, with regular participation of the Android development team.

• The Android Development Tool (ADT) a plugin for the development environment Eclipse that simplifies project creation and tightly integrates Eclipse with the Android Emulator and debugging tools. A similar plug-in for Netbeans is available too.

2.5 The AndroidManifest File

An Android Manifest is an XML file in the android app that has the greatest role in defining the app itself. It ties everything together. It is this file that explains what the application consists of, what all its main building blocks are, what permissions it requires, and so on. In particular, it contains:

31 Investigating Mobile Solutions for News Spreading

Activities and Intents Manifest file should contain all the activity information. If you create a new activity in your application you should first define it on this manifest file.

App Version Manifest file carries the version information of the app. Every modification made in the app should have incremental version number so that if the user sees an updated version if the app on Google Play Store.

Permissions When you install an app from the Google Play Store you will first prompt to accept the app permissions menu. Every app needs to access certain phone resources.

SDK attibutes In manifest file you need to specify the API version that application uses. Every time when Google introduces new android version it will also release the API version that makes the application to be checked for compatibility.

2.6 Android User Interface

There are two ways to create a user interface (UI) in Android. One is declarative while the other one is programmatic.

Declarative User Interface The declarative approach involves using XML to declare what the UI will look like, similar to creating a web page using HTML. You write tags and specify elements to appear on your screen. If you have ever handcoded an HTML page, you did pretty much the same work as creating an Android screen. One advantage of the declarative approach is that you can use what-you-see-is-what-you-

32 Investigating Mobile Solutions for News Spreading get (WYSIWYG) tools. Some of these tools ship with the Eclipse Android Development Tools (ADT) extension, and others come from third parties. Additionally, XML is fairly human-readable, and even people who are unfamiliar with the Android platform and framework can readily determine the intent of the user interface. The disadvantage of a declarative UI approach is that you can get only so far with XML. XML is great for declaring the look and feel of your user interface, but it doesn’t provide a good way of handling user input. That’s where the programmatic approach comes in.

Programmatic User Interface A programmatic user interface involves writing Java code to develop UI. Basically, to create a button programmatically, you have to declare the button variable, create an instance of it, add it to a container and set any button properties that may make sense, such as color, text, text size, background, and so on. You probably also want to declare what the button does once it’s clicked, so that’s another piece of code. All in all, you end up writing quite a few lines of Java. Everything you can do declaratively, you can also do programmatically. But Java also allows you to specify what happens when that button is actually clicked. This is the main advantage of a programmatic approach to the user interface.

Android organizes its UI elements into layouts and views. Everything you see, such as a button, label, or text box, is a view. Layouts organize views, such as grouping together a button and label or a group of these elements. So, a layout can contain other children. Those children can furthermore be layouts themselves, allowing for a complex user interface structure. A layout is responsible for allocating space for each child. Different layouts use different approaches to laying out their child widgets. There are several main layouts that we use more frequently than others, such as LinearLayout, TableLayout, FrameLayout, RelativeLayout, and AbsoluteLayout.

33 Investigating Mobile Solutions for News Spreading

 LinearLayout LinearLayout is one of the simplest and most common layouts. It simply lays out its children next to each other, either horizontally or vertically. The order of the children matters. As LinearLayout asks its children how much space they need, it allocates the desired space to each child in the order they are added. So, if an “older” child comes along and asks for all the space on the screen, there won’t be much left for the subsequent widgets in this layout.

 TableLayout TableLayout lays out its children in a table and consists of only other TableRow widgets. TableRow represents a row in a table and can contain other UI widgets. TableRow widgets are laid out next to each other horizontally, sort of like LinearLayout with a horizontal orientation. For those familiar with HTML, Table Layout is similar to the

element, and Table Row is similar to the element.

 FrameLayout FrameLayout places its children on top of each other so that the latest child is covering the previous, like a deck of cards. This layout policy is useful for tabs, for example. FrameLayout is also used as a placeholder for other widgets that will be added programmatically at some later point in time.

 RelativeLayout RelativeLayout lays out its children relative to each other. As such, it is very powerful because it doesn’t require you to nest unnecessary layouts to achieve a certain look. At the same time, using RelativeLayout can minimize the total number of widgets that need to be drawn, thus improving the overall performance of your application. Having said that, RelativeLayout requires each of its child

34 Investigating Mobile Solutions for News Spreading

views to have an ID set so that we can position it relative to other children.

 AbsoluteLayout AbsoluteLayout positions its children at absolute coordinates on the screen. It is the favourite layout for WYSIWYG tools, and although it is very simple, it is not very flexible. Your user interface would look good on one particular screen, but as soon as the screen size, orientation, or density changed, AbsoluteLayout would not be able to adjust.

35 Investigating Mobile Solutions for News Spreading

Chapter 3 Requirements analysis and architectural solutions

In the first section of the chapter 3 we are going to define the expected behaviour of the app, dividing the functional requirements from the non-functional requirements. The final list is the result of several meetings: it is the synthesis of various kinds of necessities, for the most part connected to the fact that the app should have reproduced the features of the Fanpage application on the Facebook platform, even though it was clear that a simple porting could not be done. Moreover, the development of the mobile app has never been seen as a second best but instead as an opportunity to catch in order to offer an excellent experience to the mobile users. In the second section, I will present a summarizing schema of how I expect the app to respond to some internal and external solicitations, showing which are the main events the app will pass through.

In the third section of the chapter, I will describe some architecture that could fit the needs of the Fanpage app, detailing some different approaches and finally arriving to the conclusion that the “cloud” service provided by Google is the best solution.

36 Investigating Mobile Solutions for News Spreading

3.1 Requirements

Functional Requirements

• The app must provide a login page (with a login button) • The login page must bring to the main page • The app must provide a list of news in the main page • The user can click each news items which must bring to the detailed news page • The logged user can receive further news through push notifications. If the user is not logged, it will not receive any notification

• The push message received must contain the title and a short description of the news

• The list of news provided must contain a title and a short description for each news • The main page must contain the name of the logged user and a logout button, which brings the user to the login page

• The detailed news page must contain the title and the text of the news • The app must contain an error page, which must have an exit button that kills the app

• The app must start with an intro showing the Fanpage logo and playing a 3 second long mp3

• The user can exit from the app using the menu button

Non-Functional Requirements

• The app must work on Android devices with Froyo (Android 2.2) or a newer release

• The app must work only in a portrait orientation • The app must be able to receive push messages in JSON format, even though it is in background

• The app must notify that a user has red a certain news using the Fanpage API • The app must notify the successful installation using the Fanpage API

37 Investigating Mobile Solutions for News Spreading

• The app must show the news retrieved using the Fanpage API • The app must not make use of an external database to store information • The full news can be read if it there is Internet connectivity • The app must extend the Facebook “auth_token” using the Fanpage API • The app must implement the Facebook SSO • The user must sign in providing his Facebook credentials • The user who logged out from the Facebook app is still signed in the Fanpage app until he logs out from the Fanpage app itself

• The app must make the Fanpage REST calls using an application server

3.2 The Fanpage app use cases

The Fanpage app can pass through several different states that we should be aware of. With the following schema I have summed up some of the most interesting, avoiding the ones that can result redundant. Moreover, in this phase, we did not pay attention to the architectural solution that afterwards we will adopt.

Use Case Preconditions Postconditions Main Events

The introduction The user starts the app page will appear

The user is taken to User signed in with his The page containing the the page containing 1 Facebook account list of news is opened the list of news

Available network

connectivity

The introduction The user starts the app page will appear The sign in page is 2 User is not signed in opened The user is taken to with his Facebook the sign in page account

38 Investigating Mobile Solutions for News Spreading

Available network

connectivity

The introduction The user starts the app page will appear

The app will notice User signed in with his the absence of Facebook account The error page is network connectivity 3 opened The user is taken to the error page that Unavailable network will display an connectivity appropriate error message

A message is sent to User signed in with the the device by the Facebook account Fanpage server

The app turns the Available network The page containing the message into a connectivity 4 full single news is notification opened The click on the The user press on the notification brings to received Fanpage the page containing notification the full single news

User NOT signed in A message is sent to with the Facebook the device by the account Fanpage server

5 Nothing happens The device does not Available network show anything connectivity because the user is not signed in The Fanpage server

pushes a message

User NOT signed in The Fanpage app with the Facebook opens the Facebook account app form The page containing the 6 list of news is opened The Facebook Available network platform confirms connectivity the provided credentials

39 Investigating Mobile Solutions for News Spreading

The app user presses the The user is taken to login button in the sing the page containing in page the list of news

The user provides correct Facebook credentials

The Facebook app is

installed in the device

User NOT signed in The Fanpage app with the Facebook opens the form of the account Facebook website The Facebook Available network platform confirms connectivity the provided credentials The app user presses the The user is taken to The page with the list of login button in the sing the page containing 7 news is opened in page the list of news

The user provides correct Facebook credentials

The Facebook app is NOT installed in the device

The user is in the page The user is taken to that shows the list of the page containing news The page containing the the full single news full single news is 8 The app notify to The user click on a opened Fanpage that the news provided by the news has been page opened

Figure 3.1 - Fanpage use cases

40 Investigating Mobile Solutions for News Spreading

3.3 Architectural solutions

The critical side of the software requirements given for the development of the Fanpage app was the choice of an architecture that allows keeping alive a connection between the mobile devices and the Fanpage servers and that, from time to time, would permit to the servers to push messages (news) to them. During the few months before the design of the app, I have been studying several possible approaches that would have fit the requirements. After some researches through various websites, many blogs and a lot of forums, I’ve reached the conclusion that there are three ways, for an Android app, to implement push notifications and all of them are non-trivial, hacky and have their own disadvantages. Let’s go over the list:

Poll The concept is to periodically poll the server to retrieve new messages from a remote server. The more you poll the more you get close to the real-time push. But this is really not even push.

• Advantages: easy to implement. no cost solution • Disadvantages: the more it’s close to a real-time push, the more it drains the battery

SMS The Android app detects encoded SMS messages (an SMS interceptor will accomplish this task) sent by a server: whenever there is something new, the app fetches it from the server, then pops up a notification.

• Advantages: easy to implement, fully real-time updates. • Disadvantages: It has some cost (just in the North America few free services are offered)

41 Investigating Mobile Solutions for News Spreading

Persistent TCP/IP The device initiates a mostly idle TCP/IP connection with the server and maintains it by a constant stream of keep-alive pulses. Whenever there is something new on the server, it sends a message to the phone over the TCP connection.

• Advantages: Fully real-time updates. • Disadvantages: Difficulty to implement a reliable solution since our notifications service can easily not work anymore when the Android OS decides to kill processes when it’s running low on memory. Moreover, the device’s battery will easily “die” due to the continuous sending of keep-alive messages.

What I realized after this initial analysis is that the push solution could have been based on the persistent connection model; eventually I analysed this option in depth. I began studying the MQTT.

MQTT “MQTT stands for MQ Telemetry Transport. It is a publish/subscribe, extremely simple and lightweight messaging protocol, designed for constrained devices and low-bandwidth, high-latency or unreliable networks. The design principles are to minimise network bandwidth and device resource requirements whilst also attempting to ensure reliability and some degree of assurance of delivery. These principles also turn out to make the protocol ideal of the emerging “machine-to-machine” (M2M) or “Internet of Things” world of connected devices, and for mobile applications where bandwidth and battery power are at a premium.” [11]

My researches made me come to an end: this could be a possible solution. In fact, most of the people who designed an app that implements push solution have adopted this protocol. But here there are some disadvantages:

42 Investigating Mobile Solutions for News Spreading

• The app has to force the “persistence” of the connection and this means battery drain (even though it uses a lower amount of battery compared to other solutions).

• The library has a connectionLost callback, but by itself is not responsive enough, particularly for phones where the connection state changes so frequently

• MQTT has been designed for systems deployed in a trusted environment, so we must take into account that we should implement an authentication among the communicating peer, also assuring the message confidentiality.

The previous key issues made me skip this protocol. Then I deepened the Deacon Project.

The Deacon Project This is an open source project (http://deacon.daverea.com/) developed to create a proper client/server solution to run our push service using the Comet paradigm with the Meteor server. The good point is that this project works with all the Android releases known, but the central problem is still that the long polling (or Comet programming) brings additional overhead and few latency issues. Moreover, at September 2012, there’s not a full release of the service yet and the community support is quite limited, so I had to pass this “hand” too.

Designing a project using the XMPP architecture has been avoided too because of his instant messaging nature and also because it requires the messages (payloads) to be in XML format. Eventually, according to an empiric study, the implementation of on an XMPP solution (with an heartbeat each 5 minutes) brings to a 37% reduction in battery life, even though this represents the worst case.

An additional architectural solution considered is the one that makes use of the WebSocket protocol.

43 Investigating Mobile Solutions for News Spreading

Websocket The WebSocket protocol enables two-way communication between a user agent running untrusted code running in a controlled environment to a remote host that has opted-in to communications from that code. The security model used for this is the origin-based security model commonly used by web browsers. The protocol consists of an initial handshake followed by basic message framing, layered over TCP. The goal of this technology is to provide a mechanism for browser-based applications that need two-way communication with servers that does not rely on opening multiple HTTP connections (for instance., using XMLHttpRequest or