investigating mobile solutions for news spreadingdessert.ddns.net/tesi/tesi_pasquale...

110
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

Upload: others

Post on 28-Feb-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

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

III

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 Open Handset Alliance 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

Investigating Mobile Solutions for News Spreading

IV

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

Investigating Mobile Solutions for News Spreading

5

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

Investigating Mobile Solutions for News Spreading

6

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

Investigating Mobile Solutions for News Spreading

7

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,

Investigating Mobile Solutions for News Spreading

8

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.

Investigating Mobile Solutions for News Spreading

9

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

Investigating Mobile Solutions for News Spreading

10

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.

Investigating Mobile Solutions for News Spreading

11

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

Investigating Mobile Solutions for News Spreading

12

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

Investigating Mobile Solutions for News Spreading

13

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

Investigating Mobile Solutions for News Spreading

14

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.

Investigating Mobile Solutions for News Spreading

15

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.

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).

Figure 1.2 – Fanpage Facebook application

Investigating Mobile Solutions for News Spreading

16

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).

Figure 1.3 – Fanpage website

Investigating Mobile Solutions for News Spreading

17

In 2012 it sees an increasing of his popularity till the achievement of an average of more

than 500k readers.

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.

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

Figure 1.4 – Fanpage statistics: Audiweb and Google Analitycs

Figure 1.5 – Fanpage fan growth

Investigating Mobile Solutions for News Spreading

18

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.

Hopefully there will be, in the next future, a further platform in which the “Fanpage

philosophy” can be spread: Android.

Figure 1.6 – Fanpage on Google+

Figure 1.7 – Fanpage on Twitter

Investigating Mobile Solutions for News Spreading

19

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 Linux 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.

Investigating Mobile Solutions for News Spreading

20

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.

Figure 2.1 - The Android stack

Investigating Mobile Solutions for News Spreading

21

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 Bionic, 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

Investigating Mobile Solutions for News Spreading

22

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.

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.

Figure 2.2 - Java vs Dalvik

Investigating Mobile Solutions for News Spreading

23

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.

Investigating Mobile Solutions for News Spreading

24

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

Investigating Mobile Solutions for News Spreading

25

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

Investigating Mobile Solutions for News Spreading

26

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.

Investigating Mobile Solutions for News Spreading

27

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.

Investigating Mobile Solutions for News Spreading

28

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).

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.

Figure 2.4 - Service life cycle

Investigating Mobile Solutions for News Spreading

29

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.

Figure 2.5 - Content provider

Investigating Mobile Solutions for News Spreading

30

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

Investigating Mobile Solutions for News Spreading

31

(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:

Investigating Mobile Solutions for News Spreading

32

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-

Investigating Mobile Solutions for News Spreading

33

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.

Investigating Mobile Solutions for News Spreading

34

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 <table> element, and

Table Row is similar to the <tr> 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

Investigating Mobile Solutions for News Spreading

35

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.

Investigating Mobile Solutions for News Spreading

36

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.

Investigating Mobile Solutions for News Spreading

37

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

Investigating Mobile Solutions for News Spreading

38

• 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

1

The user starts the app

The page containing the list of news is opened

The introduction page will appear

User signed in with his Facebook account

The user is taken to the page containing the list of news

Available network connectivity

2

The user starts the app

The sign in page is opened

The introduction page will appear

User is not signed in with his Facebook account

The user is taken to the sign in page

Investigating Mobile Solutions for News Spreading

39

Available network connectivity

3

The user starts the app

The error page is opened

The introduction page will appear

User signed in with his Facebook account

The app will notice the absence of network connectivity

Unavailable network connectivity

The user is taken to the error page that will display an appropriate error message

4

User signed in with the Facebook account

The page containing the full single news is

opened

A message is sent to the device by the Fanpage server

Available network connectivity

The app turns the message into a notification

The user press on the received Fanpage notification

The click on the notification brings to the page containing the full single news

5

User NOT signed in with the Facebook account

Nothing happens

A message is sent to the device by the Fanpage server

Available network connectivity

The device does not show anything because the user is not signed in

The Fanpage server pushes a message

6

User NOT signed in with the Facebook account

The page containing the list of news is opened

The Fanpage app opens the Facebook app form

Available network connectivity

The Facebook platform confirms the provided credentials

Investigating Mobile Solutions for News Spreading

40

The app user presses the login button in the sing in page

The user is taken to the page containing the list of news

The user provides correct Facebook credentials

The Facebook app is installed in the device

7

User NOT signed in with the Facebook account

The page with the list of news is opened

The Fanpage app opens the form of the Facebook website

Available network connectivity

The Facebook platform confirms the provided credentials

The app user presses the login button in the sing in page

The user is taken to the page containing the list of news

The user provides correct Facebook credentials

The Facebook app is NOT installed in the device

8

The user is in the page that shows the list of news The page containing the

full single news is opened

The user is taken to the page containing the full single news

The user click on a news provided by the page

The app notify to Fanpage that the news has been opened

Figure 3.1 - Fanpage use cases

Investigating Mobile Solutions for News Spreading

41

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)

Investigating Mobile Solutions for News Spreading

42

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:

Investigating Mobile Solutions for News Spreading

43

• 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.

Investigating Mobile Solutions for News Spreading

44

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 <iframe>s and long

polling).[12]

What comes up is that here everything is asynchronous, the "response" to an event from

the app does not come immediately and may not be the next event from the server. At the

same way, the app can send several requests without waiting or blocking for the response.

Basically the WebSocket choice would have been optimal for computer desktop solutions:

it requires just one connection, transmits only payload data (no http headers after

connection has established but only two byte for framing) so that it brings a strong

network traffic and latency reduction and there is no need to hammer the server with

Figure 3.2 – Event driven architecture

Investigating Mobile Solutions for News Spreading

45

unnecessary requests since it notifies the client of new messages.

But, even though the WebSocket solution is not limited to browser applications, at the

moment its use is far to be optimized for mobile apps. Therefore, the first obvious

consequence is that having the socket opened all time requires a battery effort that our app

cannot afford. Also, like in the MQTT case, we must consider some solutions to

uninterruptedly check the persistent connection status since we know that Android task

killer is allowed to turn the app (and tasks) off; but this have again a strong impact over

the battery life.

Eventually, I had to move beyond.

One more service I took into consideration is Urban Airship.

Urban Airship

Urban Airship is the closer service to Apple’s Push Notification. We must include their

library in our app and send messages to their web service, which then handles delivering

the messages to user devices.

Urban Airship is one of the most interesting services since it starts to use a “cloud”

service. What is the big disadvantage here is that it requires that the user installs the

AirMail app onto his device so that this app maintains a connection to their servers: the

idea to force potential end-users to install an app that has nothing to do with the Fanpage

app doesn’t seem to be idyllic for the user-experience, so I avoided also this solution. For

this reason I switched to one of the most advanced service: Xtify.

Xtify

It is a 3rd party push service with some features like geo-notifications, timed alerts,

statistics, etc. There are several APIs for creating and configuring notifications, pushing,

and getting information.

Xtify supported C2DM and since 8 August 2012 GCM too.

The problem is that you can use this service only under payment (Xtify is a commercial

service), so this choice has been removed.

Investigating Mobile Solutions for News Spreading

46

Eventually, at the beginning 2012, I realized that the best option would have to implement

the Google C2DM, even assuming the risk it was just a Beta version.

C2DM (Cloud-to-Device Messaging)

Overview

C2DM provides a way for data to get to the application without the usual HTTP. Our

server can send a message to C2DM servers, which will then "push" the message to the

device and the app. This is done through a persistent TCP socket between the device and

the C2DM servers. This connection is highly optimized to minimize bandwidth and

battery consumption. Now these messages are typically very small, so often it is up to

your application to retrieve additional data - which could very well go back to using

HTTP. Background services on Android can makes this very simple to do.

Figure 3.3 – C2DM architecture

Investigating Mobile Solutions for News Spreading

47

Once the C2DM service receives the message it can choose to raise a notification on the

device. But this service is not only recommended to notifications. Publishing a notification

is just one of the several things that the app can do with the message received from

C2DM. What is most interesting about C2DM is that leads us into another type of

application architecture not built around HTTP.

Primary characteristics

It allows third-party application servers to send lightweight messages to their Android

applications. The messaging service is not designed for sending a lot of user content via

the messages. Rather, it should be used to tell the application that there is new data on the

server, so that the application can fetch it.

• C2DM makes no guarantees about delivery or the order of messages. So, for

example, while you might use this feature to tell an instant messaging application

that the user has new messages, you probably would not use it to pass the actual

messages.

• An application on an Android device doesn’t need to be running to receive

messages. The system will wake up the application via Intent broadcast when the

message arrives, as long as the application is set up with the proper broadcast

receiver and permissions.

• It does not provide any built-in user interface or other handling for message data.

C2DM simply passes raw message data received straight to the application, which

has full control of how to handle it. For example, the application might post a

notification, display a custom user interface, or silently sync data.

• It requires devices running Android 2.2 or higher that also have the Market

application installed. However, you are not limited to deploying your applications

through Market.

• It uses an existing connection for Google services. This requires users to set up

their Google account on their mobile devices.

Investigating Mobile Solutions for News Spreading

48

Architectural Overview

C2DM is divided into these categories:

1. Components

The physical entities that play a role in C2DM.

o Mobile Device

o Third-Party Application Server

o C2DM Servers

2. Credentials

The IDs and tokens that are used in different stages of C2DM to ensure that all parties

have been authenticated, and that the message is going to the correct place.

o Sender ID

o Application ID

o Registration ID

o Google User Account

o Sender Auth Token

Lifecycle Flow

Here are the primary processes involved in cloud-to-device messaging:

• Enabling C2DM. An Android application running on a mobile device registers to

receive messages.

• Sending a message. A third-party application server sends messages to the device.

• Receiving a message. An Android application receives a message from a C2DM

server.

Investigating Mobile Solutions for News Spreading

49

Limitations

C2DM imposes the following limitations:

• The message size limit is 1024 bytes.

• Google limits the number of messages a sender sends in aggregate, and the number

of messages a sender sends to a specific device

Requirements

• C2MD is available as of Android 2.2 and requires that Google Play application is

installed on the device.

• To use C2DM on the Android simulator you also need to use a Google device with

API 8 or higher and to register with a Google account on the emulator via the

Settings.

Figure 3.4 – C2DM lifecycle flow

Investigating Mobile Solutions for News Spreading

50

The C2DM, even considering all the limitations, has proved to be the solution that in a

better way fits the requirements of the Fanpage app.

Sadly, this service has been deprecated at the end of June, so I had to migrate the project I

started to the brand new, and more appealing, Google Cloud Messaging for Android.

GCM (Google Cloud Messaging)

Overview

Google Cloud Messaging for Android (GCM) is a service that helps developers to send

data from servers to their Android applications on Android devices. This could be a

lightweight message telling the Android application that there is new data to be fetched

from the server (for instance, a movie uploaded by a friend), or it could be a message

containing up to 4kb of payload data (so apps like instant messaging can consume the

message directly). The GCM service handles all aspects of queuing of messages and

delivery to the target Android application running on the target device.

GCM is completely free no matter how big your messaging needs are, and there are no

quotas.

Primary characteristics

• It allows 3rd-party application servers to send messages to their Android

applications.

• GCM makes no guarantees about delivery or the order of messages.

• An Android application on an Android device doesn't need to be running to receive

messages. The system will wake up the Android application via Intent broadcast

when the message arrives, as long as the application is set up with the proper

broadcast receiver and permissions.

• It does not provide any built-in user interface or other handling for message data.

GCM simply passes raw message data received straight to the Android application,

Investigating Mobile Solutions for News Spreading

51

which has full control of how to handle it. For example, the application might post

a notification, display a custom user interface, or silently sync data.

• It requires devices running Android 2.2 or higher that also have the Google Play

Store application installed, or an emulator running Android 2.2 with Google APIs.

However, you are not limited to deploying your Android applications through

Google Play Store.

• It uses an existing connection for Google services. For pre-3.0 devices, this

requires users to set up their Google account on their mobile devices. A Google

account is not a requirement on devices running Android 4.0.4 or higher.

GCM vs C2DM: what is changed

• Google Play Store application installed, or an emulator running Android 2.2 with

Google APIs.

• A Google account is not a requirement on devices running Android 4.0.4 or higher.

• Apps can use "messages with payload" to deliver messages of up to 4 Kb. This

would be useful in a chat application, for example. To use this feature, simply omit

the collapse_key parameter and messages will not be collapsed. GCM will store up

to 100 messages. If you exceed that number, all messages will be discarded but

you will receive a special message. If an application receives this message, it needs

to sync with the server.

• To use the GCM service, you need to obtain a Simple API Key from Google APIs

console page. Note that GCM only accepts Simple API Key—using ClientLogin or

OAuth2 tokens will not work.

• In C2DM, the Sender ID is an email address. In GCM, the Sender ID is a project

ID that you acquire from the API console.

• GCM HTTP requests support JSON format in addition to plain text.

• In GCM you can send the same message to multiple devices simultaneously. For

example, a sports app wanting to deliver a score update to fans can now send the

message to up to 1000 registration IDs in the same request (requires JSON).

Investigating Mobile Solutions for News Spreading

52

• Multiple parties can send messages to the same app with one common registration

ID

Architectural Overview

GCM is divided into these categories:

1. Components

The physical entities that play a role in GCM.

2. Credentials

The IDs and tokens that are used in different stages of GCM to ensure that all parties

have been authenticated, and that the message is going to the correct place.

Figure 3.5 – GCM components and credentials

Investigating Mobile Solutions for News Spreading

53

Lifecycle Flow

Here are the primary processes involved in cloud-to-device messaging:

1. Enabling GCM. An Android application running on a mobile device registers to

receive messages.

2. Sending a message. A 3rd-party application server sends messages to the device.

3. Receiving a message. An Android application receives a message from a GCM

server.

Figure 3.6 – GCM lifecycle flow

Investigating Mobile Solutions for News Spreading

54

1. Enabling GCM

This is the sequence of events that occurs when an Android application running on a

mobile device registers to receive messages:

1.1 The first time the Android application needs to use the messaging service, it fires off

a registration Intent to a GCM server.

This registration Intent (com.google.android.c2dm.intent.REGISTER) includes the

sender ID, and the Android application ID.

Note: Because there is no lifecycle method that is called when the application is run

for the first time, the registration intent should be sent on onCreate(), but only if the

application is not registered yet.

1.2 If the registration is successful, the GCM server broadcasts a

com.google.android.c2dm.intent.REGISTRATION intent which gives the Android

application a registration ID.

The Android application should store this ID for later use (for instance, to check on

onCreate() if it is already registered). Note that Google may periodically refresh the

registration ID, so you should design your Android application with the

understanding that the com.google.android.c2dm.intent.REGISTRATION intent

may be called multiple times. Your Android application needs to be able to respond

accordingly.

1.3 To complete the registration, the Android application sends the registration ID to the

application server. The application server typically stores the registration ID in a

database.

Investigating Mobile Solutions for News Spreading

55

The registration ID lasts until the Android application explicitly unregisters itself, or

until Google refreshes the registration ID for your Android application.

Note: When users uninstall an application, it is not automatically unregistered on

GCM. It is only unregistered when the GCM server tries to send a message to the

device and the device answers that the application is uninstalled or it does not have a

broadcast receiver configured to receive com.google.android.c2dm.intent.RECEIVE

intents. At that point, you server should mark the device as unregistered (the server

will receive a NotRegistered error).

Note that it might take a few minutes for the registration ID to be completed

removed from the GCM server. So if the 3rd party server sends a message during

this time, it will get a valid message ID, even though the message will not be

delivered to the device.

2. Sending a Message

For an application server to send a message to an Android application, the following

things must be in place:

• The Android application has a registration ID that allows it to receive messages for

a particular device.

• The 3rd-party application server has stored the registration ID.

• An API key. This is something that the developer must have already set up on the

application server for the Android application (for more discussion, see Role of the

3rd-party Application Server). Now it will get used to send messages to the device.

Investigating Mobile Solutions for News Spreading

56

Here is the sequence of events that occurs when the application server sends a message:

2.1 The application server sends a message to GCM servers.

2.2 Google enqueues and stores the message in case the device is offline.

2.3 When the device is online, Google sends the message to the device.

2.4 On the device, the system broadcasts the message to the specified Android

application via Intent broadcast with proper permissions, so that only the targeted

Android application gets the message. This wakes the Android application up. The

Android application does not need to be running beforehand to receive the message.

2.5 The Android application processes the message. If the Android application is doing

non-trivial processing, you may want to grab a PowerManager.WakeLock and do

any processing in a Service.

An Android application can unregister GCM if it no longer wants to receive messages.

3. Receiving a Message

This is the sequence of events that occurs when an Android application installed on a

mobile device receives a message:

3.1 The system receives the incoming message and extracts the raw key/value pairs from

the message payload, if any.

3.2 The system passes the key/value pairs to the targeted Android application in a

com.google.android.c2dm.intent.RECEIVE Intent as a set of extras.

3.3 The Android application extracts the raw data from the

com.google.android.c2dm.intent.RECEIVE Intent by key and processes the data.

Investigating Mobile Solutions for News Spreading

57

Chapter 4 Design and implementation of the prototype

In the first section of the chapter I will briefly describe which considerations has been

done during the period I have been working to the project, from the first month begun with

the initial discussion about the app specs at the Ciaopeople headquarters till when the last

line of code of the Fanpage prototype has been written. Eventually I sum up the critical

app needs to satisfy.

Then, in the next section, I will in detail explain which components perform the tasks

required by the customer, highlighting the variables that come into play, the prerequisites

to satisfy to make some activities work and finally focusing on the different behaviours

that could occur in connection with the status of the pair user-app.

Last but not least, some sequence diagrams will show the interaction between the thorough

components.

4.1 Preliminary considerations

The app design has been not easy (but, instead, challenging): as described in the chapter 3,

the technology and the services outside the app has been changing constantly.

First of all, at the end of June, the Android Cloud to Device Messaging Framework has

been deprecated, so the first issue was to migrate the app to the new Google Cloud

Messaging for Android: fortunately the Android developer page offers a convincing guide,

Investigating Mobile Solutions for News Spreading

58

while the documentation regarding some examples of use of the new service, already poor

with the C2DM, was almost totally absent.

Besides this aspect, the requirements draft, when I started to work at the prototype, was

probably not exhaustive: at the beginning of the development, there were several people

that had different (sometimes far) interests and needs so it was not always easy channel all

of them.

Furthermore, Ciaopeople developers, during the last year, have been writing its own API

and I have been in the middle of this innovation. For instance, one of the first requirements

was that the “click” on the news in the main page would have opened a web page but now,

with the beta of the API operant, the click must open a new page, built parsing a JSON

message retrieved through the API itself.

Therefore, with new API taking shape, everything was much clearer so that the prototype

(and the requirements) did not change anymore.

Since the first day, on the other hand, it was obvious that one of the most important

aspects to take into account would have been the preservation of a high “user experience“.

For this reason the prototype does not contain many buttons, it is simple and you can start

to read news just after you have been correctly signed in.

In conclusion, after having overcome the first uncertain period, I adopted a top down

approach to describe the overall system. Starting from the requirements provided, by the

main “root” has been obtained three core “leaves”: the client, the application server and

third-party servers (Fanpage servers, Facebook servers and GCM servers).

Basically, the communication between the three components depends by the circumstance.

Here there are some possible scenarios:

• Registration to Google Cloud Messaging

• Sign in through the Facebook platform

• Receiving the push message

• Fetching new content from the Fanpage server

In the same way, the following figures (fig. 4.1-4.4) show the related communication

schema:

Investigating Mobile Solutions for News Spreading

59

Figure 4.1 – Registration to Google Cloud Messaging

Figure 4.2 – Sign in through the Facebook platform

Investigating Mobile Solutions for News Spreading

60

Figure 4.3 – Receiving the push message

Figure 4.4 – Fetching new content from the Fanpage server

Investigating Mobile Solutions for News Spreading

61

Once this first raw analysis was completed, I deepened the client “leaf”: in the following

picture, this component has been decomposed in connection with the functionalities it has

to satisfy. In the figure 4.5 it is shown how these functions are shared among the classes.

The client must communicate with the Fanpage servers using an intermediate application

server. The first aim of the application server is to receive HTTP requests from the client

and to run its own scripts in order to connect with the Fanpage servers; the HTTP requests

to the Fanpage servers are made adopting the cURL format, in agreement with the

Fanpage API.

In the same way, the Json_handler class has the key goal to do the “interface” chore

between the application server and the client: the correlated objects, therefore, are

instantiated when an activity has to make HTTP requests.

This class has one method, retrieveJSON(String URL), that when invoked requires only an

URL as parameter: this URL is set (in the activity that calls the method) with the address

Figure 4.5 – Client functionality-activity mapping

Investigating Mobile Solutions for News Spreading

62

of the PHP script (which lies on the application server) that will finally accomplish the job

demanded by the activity (the figure 4.6 shows the different PHP scripts that can be called

and the connected aim).

The data type returned by the method is a JSONObject. A JSONObject is an unordered

collection of name/value pairs. Its external form is a string wrapped in curly braces with

colons between the names and values, and commas between the values and names.[16]

For instance, when the NewsList activity wants to retrieve the list of news (from Fanpage

servers) to display, the getList.php is invoked and the response is something like this:

{"code":100,"data":[

{"type":0,"contentId":65457,"channel":"socialmedia","postId":107327,"title":"FIAT, dallo Stato

7,6 miliardi","description":"Sabato faccia a faccia Monti -

Marchionne","url":"http://www.fanpage.biz/filter-content-

api/","text":"BLABLABLA","postDate":"2012-09-

16T04:06:55Z","state":5,"fbShares":0,"visits":0,"tags":[]},

{"type":0,"contentId":65456,"channel":"socialmedia","postId":107326,"title":"Esordio in Europa

League per il Napoli","description":"Insigne e Vargas in

campo","url":"http://www.fanpage.biz/prova-ymv/","text":"BLABLABLA","postDate":"2012-09-

16T10:07:35Z","state":5,"fbShares":0,"visits":0,"tags":[]}]}

The JSON data usually has square brackets and curly brackets. The difference is that the

first ones represent starting of a JSONArray node whereas curly brackets represent the

beginning of a JSONObject node.

To access to the JSONObject fields, we must parse it: the getJSONArray(String key)

method is called to get the value associated with the key (“data”, in the previous example).

Then, we go through the JSONObject nodes belonging to the array (using the

getJSONObject(int index) method of the JSONArray class), in order to retrieve the field

we are interested in: eventually, for each node, we invoke the getString(String key) to get

the title and the description by the corresponding fields. These fields will be used to create

Investigating Mobile Solutions for News Spreading

63

the final list of news.

APPLICATION  SERVER  

CALL   /ExtendToken.php?access_token="+access_token+"&app_id="+app_id+"&deviceId="+deviceId+"&registrationId="+registrationId  

CLASS   Login  

GOAL   It  is  used  to  prolong  the  Facebook  auth_token  

   

CALL   /getArticle.php?contentId="+contentId+"&token="+token  

CLASS   GCM_MessageReceivedActivity  

GOAL   It  is  used  to  retrieve  the  article's  title  and  text,  used  to  create  the  ItemNews  page  

   

CALL   /RegistrationAppId.php  

CLASS   GCM_Registration  

GOAL   It  is  used  to  notify  Fanpage  servers  of  the  occurred  installation  of  a  new  Fanpage  app  

   

CALL   /putArticle.php?contentId="+contentId+"&token="+extendedToken;  

CLASS   ItemNews  

GOAL   It  is  used  to  notify  Fanpage  servers  of  the  happened  reading  

   

CALL   getList.php?token="+token  

CLASS   NewsList  

GOAL   It  is  used  to  retrieve  the  list  of  news  that  will  be  shown  to  the  user    

Figure 4.6 – Requests to the application server

Besides this duty, the application server has two more different responsibilities: the first

one is to establish a connection with a MySQL database in order to send several requests

(but now it has been deprecated); the second one is to push the message to the device.

In fact, for testing purposes, will be the application server itself to push the messages to

the GCM servers while in the final release of the app the application server will be

triggered by the Fanpage server (to notify it of a news ready to be pushed). In the same

way, the app, in order to fetch the content, will pass through the application server that

will accomplish the job contacting the Fanpage server.

To sum it up, the application server has one mission: be the “bridge” between the mobile

app and the Fanpage servers: in this way, we have a full separation of the functionalities.

In a similar manner, the client has to interact with the Google servers to handle the

Investigating Mobile Solutions for News Spreading

64

“Registration” and the “Receive” intents fired by the GCM server: two broadcast receivers

take care of these tasks, retrieving the variables related to the intent itself.

Along with the overall definitions of the sub-units of the system, in the following months I

analysed the main aspects that the Fanpage app should have dealt with:

1. The registration to Google Cloud Messaging

2. The push handling

3. The Facebook login

4.2 Main Activities

In the next section, we will deepen some of the components that have a central role in the

development of the app that is the ones that accomplish the critical phases we have

highlighted in the previous section.

4.2.1 The registration to GCM

The activity that performs the first task (Registration to Google Cloud Messaging) is the

GCM_Registration activity, which extends (like every activity) the BaseActivity activity.

Figure 4.7 – BaseActivity and GCM_Registration activities

Investigating Mobile Solutions for News Spreading

65

Before registrating the app to the cloud we saw that there were two preliminary steps to

complete:

A. Retrieve a sender ID

B. Obtain an API key.

A. To retrieve the sender ID you have to create a Google API project:

Open the Google APIs Console page.

If you haven't created an API project yet, this page will prompt you to do so:

Click Create project. Your browser URL will change to something like:

Take note of the value after #project: (4815162342 in this example). This is your project

ID, and it will be used later on as the GCM sender ID.

Figure 4.8 – Prompt from Google API Console page

Figure 4.9 – URL related to the project created

Investigating Mobile Solutions for News Spreading

66

B. On the other hand, to obtain an API key:

In the main Google APIs Console page, select API Access. You will see a screen

that resembles the following:

Click Create new Server key. Either a server key or a browser key should work.

The advantage to using a server key is that it allows you to whitelist IP addresses.

The following screen appears:

Figure 4.10 – API Access page

Figure 4.11 – New Server Key screen

Investigating Mobile Solutions for News Spreading

67

Click Create:

Take note of the API key value (YourKeyWillBeShownHere) in this example, as it will

be used later on.

At the end of this preliminary phase, the GCM_Registration class finally comes onstage.

This activity is fired by the Intro activity just in one case, according to the flag

“isRegisteredToGCM” retrieved from the SharedPreferences: if the flag is set to false

(that means that the app is not registered yet to the GCM service), the GCM_Registration

activity is fired; otherwise, in connection with the flag “isLoggedInFB”, the Intro activity

can start either the Login activity or the NewsList activity.

The first operation made by GCM_Registration activity is the check of the network

connectivity. Therefore, in the onCreate() method, we call the isOnline() method

(inherited from the BaseActivity) that makes uses of the ConnectivityManager class and

its getActiveNetworkInfo() method. If there is not active data network, the activity starts

the Error activity that will inform the user that without connectivity the registration phase

cannot be completed. Instead, in the opposite case, two more methods are called:

retrieveAndroidAppId() and registrationToGCM().

The first method retrieves the “app id” and the “app secret” (two parameters used in the

Figure 4.12 – API Access page with the returned API Key

Investigating Mobile Solutions for News Spreading

68

Login activity, result of a HTTP POST request to the Fanpage servers) and saves them in

the SharedPreferences.

The second method registers the app to the Google service, using the “sender ID” we got

when we signed up for GCM. Then GCM servers will awake the

GCM_registrationReceiver (one of our two broadcast receivers): if the registration is

successful, the registration ID and the device ID are stored in the SharedPreferences, for a

later use; otherwise, if an error occurred, the broadcast receiver handles the error, starting

the Error page with the appropriate message of error.

4.2.2 The push handling

The activity that handles the pushed messages from the GCM servers is

GCM_MessageReceivedActivity, which is called by the broadcast receiver

GCM_MessageReceiver.

Figure 4.14 – GCM_MessageReceiver broadcast receiver and the GCM_MessageReceivedActivity activity

Figure 4.13 - GCM_registrationReceiver broadcast receiver

Investigating Mobile Solutions for News Spreading

69

But before let’s see how this receiver can be woken.

As we mentioned in the 4.1 paragraph, in order to receive pushed news from the Fanpage

servers, I had to implement a simple application server for the testing phase, to be sure the

GCM service would work properly; because of this, the application server has to be set

with two key parameter: the “Authentication Token” (the API key we got on the Google

APIs Console page, to authenticate itself with the GCM servers) and the “registration ID”.

In the first release, this application server was made to push a message with the payload

containing an URL, a title and a short description of the news. The client, once received it

after few seconds, would have created a notification showing the Fanpage icon in the

notification bar, with the text and the description appearing after a scroll down done over

the notification bar. The click on the notification would open the app and create a web

page from the provided URL.

On the contrary, in the last release, when the application server gets fired, it sets the

payload with a JSON message (so that the notifications can be built starting from scratch

while the page will be built later) retrieved by the HTTP GET request to the Fanpage

servers. Eventually, with all the parameters of the HTTP body and header set, the

application server issues a POST request to the GCM servers.

There are two possible outcomes when the application server tries to push a message: the

message is processed successfully or the GCM server rejects the request.

In the best case, the HTTP response has a 200 status, and so the GCM delivers the

message to the device.

In the worst case, the HTTP response contains a non 200 status code.

As we discussed before, this implementation will be certainly different in the following

release of the prototype: in this phase, indeed, it was not yet necessary to implement the

full integration of the application server with the Fanpage server. But in the future it must

be taken into account how the Fanpage server will trigger the application server.

Anyway, in the current version of the prototype, when a message is delivered it will be

duty of the GCM_MessageReceiver broadcast receiver to catch the message from the

Investigating Mobile Solutions for News Spreading

70

com.google.android.c2dm.intent.RECEIVE intent broadcasted.

Then, within the onReceive() method, two more methods are called:

parseJsonArticle(payload) and createNotification(context, payload).

The first method parses the payload, extracting the “contentId” and the “title” fields.

The second method creates the notification that will pop up on the screen, showing the

Fanpage icon and the title of the news: when the user will press on it, the

GCM_MessageReceivedActivity gets called, and the “contentId” will be passed to it.

The “contentId” is used, together with the “extendedToken” (we will deepen it later), to

pull the news corresponding to the “contentId” itself by an HTTP GET request to the

Fanpage servers. This request will return a JSON object that will be parsed to extract the

“title” and the “text” fields.

Eventually these parameters are then put in a bundle, and the ItemNews activity is called:

it will make use of the bundle itself to build a complete news page.

4.2.3 The Facebook login

One of the requirements of the app is that the user of the Fanpage app has to be

compulsorily a Facebook user. Another one is that the app must implement the Facebook

Single Sign-On service.

To go along with these needs, I had to integrate the two worlds, Facebook and Android.

The Facebook developer page offers the steps to take:

Figure 4.15 - ItemNews activity

Investigating Mobile Solutions for News Spreading

71

Getting started

1. Register your Android App with Facebook

To begin integrating with the Facebook Platform, I had to create a new app on

Facebook and enter the app's basic information.

.

2. Download and install the SDKs and Tools

Prepare your project

3. Create New Facebook SDK Project

I needed to create a new Android project for the Facebook SDK source which can

be reference from the Fanpage app. This is only required once.

4. Add reference to the Facebook SDK

Create a new Android project for the Fanpage app and add a reference to the

Facebook SDK project.

Figure 4.16 – Setting page of a Facebook application

Investigating Mobile Solutions for News Spreading

72

5. Add your app's signature to the Facebook App Settings

Facebook requires an additional layer of security for mobile apps in the form of an

application signature. You need to put the Fanpage application signature into the

Facebook app settings.

6. Enable Single Sign-On for your App

Single Sign-On allows user to authorize your app without typing their Facebook

username and password. This is accomplished by sharing intent with the Facebook

app. If the user has already installed and authorized the Facebook app, your app

can leverage the Facebook app authentication via Single Sign On.

a. Modify AndroidManifest.xml for the Network calls

b. Single-Sign-On (SSO)

SSO lets users sign into Fanpage app using their Facebook identity. If they are

already signed into the Facebook Android app on their device they do not have

to even type a username and password. Further, because they are signing to the

Fanpage app with their Facebook identity, you have access to their profile

information and social graph.

c. Install the Facebook Android App

d. To help with debugging the Fanpage app in the Android emulator, a binary

image of the Facebook Android app it’s provided: you can install it with the

adb tool in the Android SDK.

e. Build and run the project

f. More permissions

By default, the user is asked to authorize the app to access basic information

that is available publicly or by default on Facebook. If your app needs more

than this basic information to function, you must request specific permissions

from the user. This is accomplished by passing String[] of permissions to the

authorize method.

Investigating Mobile Solutions for News Spreading

73

g. Save your access token

• The access token is saved using SharedPreferences in the onComplete()

method

• The saved access token is fetched from persistent storage and set as the

facebook object's access token via facebook.setAccessToken()

• facebook.authorize() is called only if the session is invalid. (checked by

calling the facebook.isSessionValid()).

7. Enable user to Log Out of your App

When the user wants to stop using Facebook integration with your app, you can

call the logout method to clear the app state and make a server request to invalidate

the current access_token.

8. Extending the access token

With the deprecation of offline_access, you need to extend your access_token

every time a user opens your app. [12]

Once accomplished this initial phase, I realized that it was crucial to channel all the

Facebook logic into one class so the Login activity has been implemented according to

this remark.

Figure 4.17 – The Login activity

Investigating Mobile Solutions for News Spreading

74

This activity is called by the Intro activity in two cases:

• the “isLoggedInFB” variable is set to false and the “isRegisteredToGCM” variable

is set to true: this combination means that the user is not yet signed in Facebook (at

least, not signed from the Fanpage app: there’s no way to check if the user has

signed itself by the Facebook app) and the app is registered to the GCM service.

• the “isRegisteredToGCM” variable is set to false, so there will be a registration

phase (hopefully successful!) before the arrival to the Login page.

The Login page shows a simple button to access to the NewsList page. The “click” can

open two scenarios:

• in the first one the user will be asked of his Facebook credentials (because he

didn’t already sign in by the Facebook app or because there’s not Facebook app

that means no SSO implementation);

• in the second one the Facebook credentials are retrieved (because the user is

already logged by the Facebook app).

In case the log in phase is successful, the user is taken to the NewsList page, otherwise the

Facebook platform will inform that the credentials provided are wrong (so the user won’t

be able to access to the NewsList page) and he will stay in the Login page.

In the Login activity has been implemented two different layouts for each status (signed

in/ signed out):

• the “isLoggedInFB” flag becomes true (when you press the Login button), than the

Login button is turned invisible while the Logout button visible. At the top of the

page, a header with the Fanpage logo appears. When the layout is ready, the

activity starts the NewsList activity that fills the body of the page with the news.

• the “isLoggedInFB” flag is false (it is set when the Logout button is pressed in the

NewsList page), than the opposite behaviour occurs.

Furthermore, the Login activity contains a method, getProfileInfo(), that uses the Graph

API to access to the logged user information: once retrieved, they are stored in the

SharedPreferences. These elements are used in the NewsList activity to show the name of

the logged user in the header.

Investigating Mobile Solutions for News Spreading

75

The getExtendedToken() method is called (at the end of a successful login) to satisfy one

more requirements: the prolong of the Facebook “access_token”. That’s how this method

comes in handy: it takes all the variables necessaries and “POST” them to the Fanpage

servers which gives back a new token that lasts some years more.

Last note: most of the events occur in the onResume() method (like calling

getProfileInfo(), change of layout and so on) and just when the “isLoggedInFB“ flag is set

to true. This choice has been done because when you press the Login button (and then you

sign in), you don’t go straight to the NewsList activity but, on the contrary, the Android

OS make you first come back to the Login activity, so the onResume() is called and

finally, if the sign in was successful, the NewsList activity is fired. This behaviour is

different when the device doesn’t host the Facebook app so that the SSO feature won’t

work. We will see, in the next section, that I had to force the onResume() call to channel

the different reaction of the Fanpage app to the login provided with the Facebook website.

4.3 The Fanpage app: a global overview

In this section we are going to deepen the three macro phases studied in the section 4.2

from the point of view of the interacting processes operating between the involved

components. In particular, we will refer to some of the use cases already described in the

chapter 3 section 2, paying attention to the different scenarios that we should face and, in

addition to this, taking into account a few more situations, this time related to the

registration phase.

4.3.1 The registration to GCM

Description:

The Fanpage app must register itself to the Google Cloud Messaging service when the

user installs the app into the device for the first time.

Investigating Mobile Solutions for News Spreading

76

Subjects involved:

Activity: Intro, GCM_Registration, Login

Broadcast receiver: GCM_registrationReceiver

Class: JSON_handler

The GCM servers

Application server

Fanpage servers

Case 1:

Preconditions:

User not signed in with his Facebook account

App registered to GCM

Available network connectivity

The user starts the app

Postcondition:

The Login activity is fired

Basic Course of Events:

The Intro activity checks if there’s avalaiable network connectivity

The Intro activity checks if the app is registered to GCM and if the user is logged

to Facebook

The Intro activity starts the Login activity

Investigating Mobile Solutions for News Spreading

77

Note. If the user is, on the contrary, already logged in Facebook, than the sequence

diagram will become this:

Figure 4.18 - Registration to GCM sequence diagram, case 1

Figure 4.19 - Registration to GCM sequence diagram, case 1 bis

Investigating Mobile Solutions for News Spreading

78

Case 2:

Preconditions:

User not signed with his Facebook account

App NOT registered to GCM

Network connectivity available

Registration to GCM successfull

Postcondition:

The app is registered to GCM and Login activity is started.

Basic Course of Events:

The user starts the app

The Intro activity checks if there’s avalaiable network connectivity

The Intro activity checks if the app is registered to GCM and if the user is logged

to Facebook

The Intro activity starts the GCM_Registration activity

GCM_Registration makes an HTTP POST request to the Fanpage servers to

retrieve the Android App ID

GCM_Registration registers the app to the GCM service firing a

com.google.android.c2dm.intent.REGISTER intent

The GCM_registrationReceiver checks that no error occurred in the registration

phase

The GCM_registrationReceiver starts the Login activity

Investigating Mobile Solutions for News Spreading

79

Case 3:

Preconditions:

User signed/unsigned with a Facebook account

App NOT registered to GCM

Network connectivity available

At the first time the registration to GCM is NOT successfull while on the second

time it is successfull

Postcondition:

The app is registered to GCM and Login activity is started.

Basic Course of Events:

The user starts the app

The Intro activity checks if there’s avalaiable network connectivity

The Intro activity checks if the app is registered to GCM and if the user is logged

to Facebook

The Intro activity starts the GCM_Registration activity

Figure 4.20 - Registration to GCM sequence diagram, case 2

Investigating Mobile Solutions for News Spreading

80

GCM_Registration makes an HTTP POST request to the Fanpage servers to

retrieve the Android App ID

GCM_Registration registers the app to the GCM service firing a

com.google.android.c2dm.intent.REGISTER intent

The GCM_registrationReceiver checks that an error occurred in the registration

phase

The GCM_registrationReceiver fires the GCM_Registration activity after an

increased delay

GCM_Registration try to register the app to the GCM service

The GCM_registrationReceiver checks that no error occurred in the registration

phase

The GCM_registrationReceiver starts the Login activity

Figure 4.21 - Registration to GCM sequence diagram, case 3

Investigating Mobile Solutions for News Spreading

81

4.3.2 The push handling

Description:

The Fanpage app must handle the pushed messages in JSON format by the Fanpage

servers.

Subjects involved:

Activity: GCM_MessageReceiverActivity, ItemNews

Broadcast receiver: GCM_MessageReceiver

Class: JSON_handler

The GCM servers

Application server

Fanpage servers

Case 1:

Preconditions:

User signed in with the Facebook account

App registered to GCM

Available network connectivity

The user presses on the received Fanpage notification

Postcondition:

The ItemNews activity is fired

Basic Course of Events:

The Fanpage servers trigger the application server

The application server push the message to the GCM servers.

The GCM servers forward the message to the addressed Fanpage app

The GCM_MessageReceiver retrieves the payload since the user is signed in,

Investigating Mobile Solutions for News Spreading

82

parses it and creates a notification of received message

The clicked notification fires the GCM_MessageReceivedActivity

The GCM_MessageReceivedActivity makes an HTTP GET request to the Fanpage

servers (through our application server) to pull the article connected to the

contentID

The GCM_MessageReceivedActivity parses the JSON message and starts the

ItemNews activity

The ItemNews activity builds the news page

Figure 4.22 - Push handling sequence diagram, case 1

Investigating Mobile Solutions for News Spreading

83

Note. If the user is not signed in, than this will be the scenario:

The GCM_MessageReceiver checks, indeed, the variable connected to the sign-in status.

This variables has been stored in SharedPreferencies, and set to “false” when the user has

log out from the app.

4.3.3 The Facebook login

Description:

The Fanpage app must show a Login page in which the user can sign into the app, clicking

the Login button. The sign must be completed providing Facebook credentials.

Subjects involved:

Activity: Login, NewsList

Class: JSON_handler

The GCM servers

Application server

Fanpage servers

Figure 4.23 - Push handling sequence diagram, case 1 bis

Investigating Mobile Solutions for News Spreading

84

Case 1:

Preconditions:

User NOT signed in with the Facebook account

App registered to GCM

Available network connectivity

The app user presses the Login button in the Login page

The user provides correct Facebook credentials

Postcondition:

The NewsList activity is fired

Basic Course of Events:

The user arrives to the Login page

The setup() method is called

The isOnline() method is called

The loginToFacebook() method is called

The user filles the Facebook form to sign in

The variables associated to the new incoming status are changed (“isLoggedInFB”

is set to true)

The getExtendedToken() is called to retrieve from the Fanpage servers the new and

extended Facebook access_token.

The onResume() method gets called after Facebook servers have validated the

credentials provided.

The layout status is changed in order to host an header, the logout botton and the

list of news in the new page.

The NewsList activity is started.

Investigating Mobile Solutions for News Spreading

85

Note. If the SSO does not work on the device (in most cases, it’s due to the absence of

the Facebook app installed on the device itself), the sequence diagram will slightly

change.

In this case, we see that the onResume() is called inside the loginToFacebook()

method because some of the “logic” is set in that onResume() method (as already

Figure 4.24 – Facebook login sequence diagram, case 1

Figure 4.25 – Facebook login sequence diagram, case 1 bis

Investigating Mobile Solutions for News Spreading

86

explained in the previous section). We explicitly call the method since, this time, the

sign in will be done through the Facebook web page (while in the SSO we pass

through the Facebook app). This means that the Login activity will not go in an

“pause” state but instead it will stay in the onCreate() method.

Investigating Mobile Solutions for News Spreading

87

Chapter 5 The Fanpage app: code and use examples

In this chapter we are going to test the Fanpage prototype.

In the first paragraph will be presented the classes that realize the investigated aspects

discussed in the chapter 4: the registration to GCM, the push handling and the Facebook

login.

In the second paragraph, we will dress the part of the end-user, in fact some hypothetical

situations already studied will be this time displayed on the Android emulator (please do

not pay too much attention to the graphic features of the app: it is not the object of my

thesis!).

5.1 The code

With this chapter we will reveal the main classes that are behind the operating methods of

the client:

BaseActivity

GCM_Registration

GCM_registrationReceiver

GCM_MessageReceiver

GCM_MessageReceivedActivity

Login

Investigating Mobile Solutions for News Spreading

88

5.1.1 The registration to GCM

The classes that basically perform the registration job are the GCM_Registration and the

GCM_registrationReceiver but here will post also the code of the BaseActivity, a class

that will be inherited by all the activities of the prototype.

5.1.1.1 The BaseActivity class package  com.example.fanpageapp;    import  com.facebook.android.AsyncFacebookRunner;  import  com.facebook.android.Facebook;  import  android.app.Activity;  import  android.content.Context;  import  android.content.SharedPreferences;  import  android.net.ConnectivityManager;  import  android.net.NetworkInfo;  import  android.util.Log;    public  class  BaseActivity  extends  Activity{         static  final  String  TAG_TITLE  =  "title";     static  final  String  TAG_DESCRIPTION  =  "description";     static  final  String  TAG_CONTENTID  =  "contentId";     static  final  String  TAG_TEXT  =  "text";     static  final  String  TAG_DATA  =  "data";     static  final  String  FACEBOOK_APP_ID  =  "XXXXXXXXXXXXX";     final  String  ANDROID_PROJECT_ID  =  "XXXXXXXXX";         public  SharedPreferences  mPrefs;     public  String  prefName  =  "myFanpagePrefs";     static  Facebook  facebook  =  new  Facebook(FACEBOOK_APP_ID);     AsyncFacebookRunner  mAsyncRunner  =  new  AsyncFacebookRunner(facebook);         public  void  saveStringIntoPrefs(String  key,  String  value)  {       mPrefs  =  getSharedPreferences(prefName,  0);       SharedPreferences.Editor  editor  =  mPrefs.edit();                     editor.putString(key,value);                       editor.commit();}           public  void  saveLongIntoPrefs(String  key,  long  value)  {       mPrefs  =  getSharedPreferences(prefName,  0);       SharedPreferences.Editor  editor  =  mPrefs.edit();                       editor.putLong(key,value);                   editor.commit();     }         public  void  saveBooleanIntoPrefs(String  key,  boolean  value)  {       mPrefs  =  getSharedPreferences(prefName,  0);       SharedPreferences.Editor  editor  =  mPrefs.edit();                       editor.putBoolean(key,value);                     editor.commit();     }         public  boolean  isOnline()  {               Context  context  =  this.getApplicationContext();  

ConnectivityManager  cm  =  (ConnectivityManager)  context.getSystemService(Context.CONNECTIVITY_SERVICE);  

    NetworkInfo  ni  =  cm.getActiveNetworkInfo();       if  (ni  ==  null)  {  return  false;  }         else  {  return  true;  }         }      }  

Investigating Mobile Solutions for News Spreading

89

5.1.1.2 The GCM_Registration class package  com.example.fanpageapp;    import  java.io.BufferedReader;  import  java.io.IOException;  import  java.io.InputStreamReader;    import  org.apache.http.HttpResponse;  import  org.apache.http.client.ClientProtocolException;  import  org.apache.http.client.HttpClient;  import  org.apache.http.client.methods.HttpPost;  import  org.apache.http.impl.client.DefaultHttpClient;  import  org.json.JSONException;  import  org.json.JSONObject;    import  android.app.Activity;  import  android.app.PendingIntent;  import  android.content.Context;  import  android.content.Intent;  import  android.content.SharedPreferences;  import  android.net.ConnectivityManager;  import  android.net.NetworkInfo;  import  android.os.Bundle;  import  android.provider.Settings.Secure;  import  android.util.Log;    public  class  GCM_Registration  extends  BaseActivity  {         Context  context;     private  String  registrationId  =  null;         @Override     protected  void  onCreate(Bundle  savedInstanceState)  {       super.onCreate(savedInstanceState);         context  =  getBaseContext();       mPrefs  =  getSharedPreferences(prefName,  0);               if  (!isOnline())  {           Intent  i  =  new  Intent("com.example.fanpageapp.ERROR");         startActivity(i);       }         else  {           if  (mPrefs.getLong("delay",  1000)  >  1000)  resetDelay();           retrieveAndroidAppId();           registrationToGCM();                 }         }         private  void  retrieveAndroidAppId()  {       JsonUtility  jParser  =  new  JsonUtility();       try  {         JSONObject  Jobj=  jParser.retrieveJSON("http://10.0.2.2:8888/gcm/RegistrationAppId.php");         JSONObject  MyJo  =  Jobj.getJSONObject("data");         String  app_id  =  MyJo.getString("app_id");         String  app_secret  =  MyJo.getString("app_secret");         saveStringIntoPrefs("app_id",app_id);             saveStringIntoPrefs("app_secret",app_secret);       }  catch  (ClientProtocolException  e)  {         e.printStackTrace();       }  catch  (IOException  e)  {         e.printStackTrace();       }  catch  (JSONException  e)  {         e.printStackTrace();       }     }       private  void  registrationToGCM()  {             Intent  intent  =  new  Intent("com.google.android.c2dm.intent.REGISTER");       intent.putExtra("app",PendingIntent.getBroadcast(getBaseContext(),  0,  new  Intent(),  0));  

Investigating Mobile Solutions for News Spreading

90

    intent.putExtra("sender",  ANDROID_PROJECT_ID);       startService(intent);         }     public  void  retrieveRegistrationIdGCM()  {       registrationId  =  mPrefs.getString("registrationId",  null);       }            public  void  resetDelay()  {        saveLongIntoPrefs("delay",1000);      }       @Override     protected  void  onResume()  {       super.onResume();       if  (  (!mPrefs.getBoolean("isRegisteredToGCM",  false)  )  &&  (mPrefs.getLong("delay",  1000)  >  1000)  )    {           registrationToGCM();         }     }    }  

5.1.1.3 The GCM_registrationReceiver class package  com.example.fanpageapp;    import  java.io.BufferedReader;  import  java.io.IOException;  import  java.io.InputStreamReader;  import  java.util.ArrayList;  import  java.util.List;    import  org.apache.http.HttpResponse;  import  org.apache.http.NameValuePair;  import  org.apache.http.client.HttpClient;  import  org.apache.http.client.entity.UrlEncodedFormEntity;  import  org.apache.http.client.methods.HttpPost;  import  org.apache.http.impl.client.DefaultHttpClient;  import  org.apache.http.message.BasicNameValuePair;    import  android.content.BroadcastReceiver;  import  android.content.Context;  import  android.content.Intent;  import  android.content.SharedPreferences;  import  android.content.SharedPreferences.Editor;  import  android.preference.PreferenceManager;  import  android.provider.Settings.Secure;  import  android.util.Log;  public  class  GCM_registrationReceiver  extends  BroadcastReceiver  {         public  SharedPreferences  mPrefs;     public  String  prefName  =  "myFanpagePrefs";     Context  myContext;         @Override     public  void  onReceive(Context  context,  Intent  intent)  {               mPrefs  =  context.getSharedPreferences(prefName,  0);       String  action  =  intent.getAction();       if  ("com.google.android.c2dm.intent.REGISTRATION".equals(action))  {         myContext  =  context;         Log.w("GCM_REGISTRATIONRECEIVER",  "onReceive()_Received  registration  ID");               String  registrationId  =  intent.getStringExtra("registration_id");               String  error  =  intent.getStringExtra("error");         .         if  (error  ==  null)  {             String  deviceId  =  Secure.getString(context.getContentResolver(),  Secure.ANDROID_ID);           saveRegistrationId(context,  registrationId,  deviceId);               mPrefs  =  context.getSharedPreferences(prefName,  0);           SharedPreferences.Editor  editor  =  mPrefs.edit();                           editor.putBoolean("isRegisteredToGCM",true);  

Investigating Mobile Solutions for News Spreading

91

                        editor.putBoolean("isLoggedInFB",  false);                           editor.putBoolean("wantToLogoutFromFB",  false);                           editor.commit();                       Intent  goToLoginActivity  =  new  Intent(context,  Login.class);               goToLoginActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                               context.startActivity(goToLoginActivity);             }           else  if  ("SERVICE_NOT_AVAILABLE".equals(error))  {               mPrefs  =  context.getSharedPreferences(prefName,  0);           int  delay  =  (mPrefs.getInt("delay",  1000)  *  2);           if  (delay  >=  4000)  {             Intent  goToErrorActivity  =  new  Intent(myContext,  Error.class);                 goToErrorActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);               goToErrorActivity.putExtra("errore",  "SERVICE_NOT_AVAILABLE");                             myContext.startActivity(goToErrorActivity);                             }           SharedPreferences.Editor  editor  =  mPrefs.edit();                 editor.putInt("delay",delay);                         editor.commit();                                     Thread  reTry  =  new  Thread()  {             @Override             public  void  run()  {               try  {                 sleep(delay);                     }  catch(InterruptedException  e)  {                 e.printStackTrace();               }  finally  {                 Intent  goToRegisterAgain                   =  new  Intent(myContext,  GCM_Registration.class);                                     goToRegisterAgain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                                     myContext.startActivity(goToRegisterAgain);                 }               }             };             reTry.start();                        }         else  if  ("ACCOUNT_MISSING".equals(error))  {           Intent  goToErrorActivity  =  new  Intent(myContext,  Error.class);               goToErrorActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);             goToErrorActivity.putExtra("errore",  "ACCOUNT_MISSING");                           myContext.startActivity(goToErrorActivity);                        }         else  if  ("AUTHENTICATION_FAILED".equals(error))  {           Intent  goToErrorActivity  =  new  Intent(myContext,  Error.class);               goToErrorActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);             goToErrorActivity.putExtra("errore",  "AUTHENTICATION_FAILED");                           myContext.startActivity(goToErrorActivity);                        }           else  if  ("INVALID_SENDER".equals(error))  {           Intent  goToErrorActivity  =  new  Intent(myContext,  Error.class);               goToErrorActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);             goToErrorActivity.putExtra("errore",  "INVALID_SENDER");                           myContext.startActivity(goToErrorActivity);                        }           else  if  ("PHONE_REGISTRATION_ERROR".equals(error))  {           Intent  goToErrorActivity  =  new  Intent(myContext,  Error.class);               goToErrorActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);             goToErrorActivity.putExtra("errore",  "PHONE_REGISTRATION_ERROR");                           myContext.startActivity(goToErrorActivity);                                        }           else  if  ("INVALID_PARAMETERS".equals(error))  {           Intent  goToErrorActivity  =  new  Intent(myContext,  Error.class);               goToErrorActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);             goToErrorActivity.putExtra("errore",  "INVALID_PARAMETERS");                           myContext.startActivity(goToErrorActivity);                                        }         }     }           private  void  saveRegistrationId(Context  context,  String  registrationId,  String  deviceId)  {       SharedPreferences.Editor  editor  =  mPrefs.edit();  

Investigating Mobile Solutions for News Spreading

92

    editor.putString("registrationId",  registrationId);       editor.putString("deviceId",  deviceId);       editor.commit();     }        }      

5.1.2 The push handling

The classes that take care of the pushed messages are the GCM_MessageReceiver and the

GCM_MessageReceivedActivity

5.1.2.1 The GCM_MessageReceiver class

package  com.example.fanpageapp;    import  java.io.IOException;    import  org.apache.http.client.ClientProtocolException;  import  org.json.JSONArray;  import  org.json.JSONException;  import  org.json.JSONObject;    import  android.app.Notification;  import  android.app.NotificationManager;  import  android.app.PendingIntent;  import  android.content.BroadcastReceiver;  import  android.content.Context;  import  android.content.Intent;  import  android.content.SharedPreferences;  import  android.util.Log;    public  class  GCM_MessageReceiver  extends  BroadcastReceiver  {     JSONObject  json;     String  contentId;     String  title;     public  SharedPreferences  mPrefs;     public  String  prefName  =  "myFanpagePrefs";         @Override     public  void  onReceive(Context  context,  Intent  intent)  {       mPrefs  =  context.getSharedPreferences(prefName,  0);       String  action  =  intent.getAction();             if  ("com.google.android.c2dm.intent.RECEIVE".equals(action)&&(mPrefs.getBoolean("isLoggedInFB",  true)))  {                 String  payload  =  intent.getStringExtra("payload");         parseJsonArticle(payload);         createNotification(context,  payload);       }     }       private  void  parseJsonArticle(String  payload)  {             try  {         json  =  new  JSONObject(payload);         JSONArray  articles  =  json.getJSONArray("data");         JSONObject  article  =  articles.getJSONObject(0);         contentId  =  article.getString("contentId");         title  =  article.getString("title");       }  catch  (JSONException  e)  {         e.printStackTrace();       }  

Investigating Mobile Solutions for News Spreading

93

        }     public  void  createNotification(Context  context,  String  payload)  {       NotificationManager  notificationManager  =  (NotificationManager)  context           .getSystemService(Context.NOTIFICATION_SERVICE);       Notification  notification  =  new  Notification(R.drawable.iconfanpage,           "News  da  Fanpage",  System.currentTimeMillis());       notification.flags  |=  Notification.FLAG_AUTO_CANCEL;       Intent  intent  =  new  Intent(context,  GCM_MessageReceivedActivity.class);           intent.putExtra("contentId",  contentId);       PendingIntent  pendingIntent  =  PendingIntent.getActivity(context,  0,           intent,  PendingIntent.FLAG_CANCEL_CURRENT);         notification.setLatestEventInfo(context,  "fanpage",           title,  pendingIntent);       notificationManager.notify(0,  notification);       }    }  

5.1.2.2 The GCM_MessageReceivedActivity class package  com.example.fanpageapp;    import  java.io.IOException;    import  org.apache.http.client.ClientProtocolException;  import  org.json.JSONArray;  import  org.json.JSONException;  import  org.json.JSONObject;    import  android.content.Intent;  import  android.os.Bundle;  import  android.util.Log;    public  class  GCM_MessageReceivedActivity  extends  BaseActivity  {                 public  void  onCreate(Bundle  savedInstanceState)  {             mPrefs  =  getSharedPreferences(prefName,  0);         JSONArray  articles;               super.onCreate(savedInstanceState);         Bundle  extras  =  getIntent().getExtras();       if  (extras  !=  null)  {         String  contentId  =  extras.getString(TAG_CONTENTID);         String  token  =  mPrefs.getString("app_id",  null);         String  url  =  "http://10.0.2.2:8888/gcm/getArticle.php?contentId="+contentId+"&token="+token;               try  {           JsonUtility  jParser  =  new  JsonUtility();           JSONObject  jsonArticleFanpage  =  jParser.retrieveJSON(url);           articles  =  jsonArticleFanpage.getJSONArray(TAG_DATA);             JSONObject  articolo  =  articles.getJSONObject(0);           String  title  =  articolo.getString(TAG_TITLE);           String  text  =    articolo.getString(TAG_TEXT);           Intent  goToItemView  =  new  Intent(getApplicationContext(),  ItemNews.class);                                 Bundle  bundle  =  new  Bundle();                                                             bundle.putString(TAG_TITLE,  title);                   bundle.putString(TAG_TEXT,  text);                                   bundle.putString(TAG_CONTENTID,  contentId);                                   goToItemNews.putExtras(bundle);                                                               startActivity(goToItemNews);         }  catch  (ClientProtocolException  e)  {           e.printStackTrace();         }  catch  (IOException  e)  {           e.printStackTrace();         }  catch  (JSONException  e)  {           e.printStackTrace();         }       }     }  

Investigating Mobile Solutions for News Spreading

94

      @Override     protected  void  onPause()  {       super.onPause();       finish();     }  

}

5.1.3 The Facebook login

The class that will take-charge of the sign in phase is the Login activity.

5.1.3.1 The Login class

package  com.example.fanpageapp;    import  java.io.FileNotFoundException;  import  java.io.IOException;  import  java.net.MalformedURLException;    import  org.apache.http.client.ClientProtocolException;  import  org.json.JSONException;  import  org.json.JSONObject;    import  android.app.Activity;  import  android.content.Context;  import  android.content.Intent;  import  android.content.SharedPreferences;  import  android.os.Bundle;  import  android.util.Log;  import  android.view.View;  import  android.widget.Button;  import  android.widget.TextView;    import  com.facebook.android.AsyncFacebookRunner;  import  com.facebook.android.AsyncFacebookRunner.RequestListener;  import  com.facebook.android.DialogError;  import  com.facebook.android.Facebook;  import  com.facebook.android.Facebook.DialogListener;  import  com.facebook.android.FacebookError;    public  class  Login  extends  BaseActivity  implements  View.OnClickListener{         static  View  fbLogInOutLayout  ;     String  statusOnCreate;     String  statusOnResume;       static  Button  fbLogin;     static  Button  fbLogout;     static  Button  fbGetProfile;     TextView  tvLogin;             @Override     protected  void  onCreate(Bundle  savedInstanceState)  {           super.onCreate(savedInstanceState);       mPrefs  =  getSharedPreferences(prefName,  0);       setContentView(R.layout.loginout);             setup();     }       private  void  setup()  {               fbLogInOutLayout  =  (View)  findViewById(R.id.lLogInOut);       fbLogin  =  (Button)  findViewById(R.id.bFBLogin);       fbLogout  =  (Button)  findViewById(R.id.bFBLogout);  

Investigating Mobile Solutions for News Spreading

95

    fbLogout.setVisibility(View.INVISIBLE);       tvLogin  =  (TextView)  findViewById(R.id.tvFBLogin);                       fbLogin.setOnClickListener(this);                       fbLogout.setOnClickListener(this);     }  

    public  void  loginToFacebook()  {                                               String  access_token  =  mPrefs.getString("access_token",  null);                   long  expires  =  mPrefs.getLong("access_expires",  0);                                          if(access_token  !=  null)  {                                 facebook.setAccessToken(access_token);       }                       if(expires  !=  0)  {                         facebook.setAccessExpires(1000000000);                                                 }                               if  (!facebook.isSessionValid())  {                                             facebook.authorize(this,  new  DialogListener()  {                                 @Override                                 public  void  onComplete(Bundle  values)  {                                                                   saveLongIntoPrefs("access_expires",  facebook.getAccessExpires());                                 saveStringIntoPrefs("access_token",  facebook.getAccessToken());                                 saveBooleanIntoPrefs("isLoggedInFB",  true);                 saveBooleanIntoPrefs("wantToLogoutFromFB",  false);                 getExtendedToken();         if(!mPrefs.getBoolean("isSSO",  false))  {                                   onResume();                                };                                                                                               }                                                               @Override                                 public  void  onFacebookError(FacebookError  error)  {}                                       @Override                                 public  void  onError(DialogError  e)  {}                                       @Override                                 public  void  onCancel()  {}                         });                             }       }       @Override     public  void  onActivityResult(int  requestCode,  int  resultCode,  Intent  data)  {       super.onActivityResult(requestCode,  resultCode,  data);       facebook.authorizeCallback(requestCode,  resultCode,  data);     }       public  void  getProfileInfo()  {           mAsyncRunner.request("me",  new  RequestListener()  {                                     @Override                                 public  void  onComplete(String  response,  Object  state)  {                                                       String  json  =  response;                                             try  {                                             JSONObject  profile  =  new  JSONObject(json);                                                   final  String  name  =  profile.getString("name");                                                   runOnUiThread(new  Runnable()  {               @Override               public  void  run()  {                           saveStringIntoPrefs("fb_nome",  name);  

                }               });                                           }  catch  (JSONException  e)  {                                                   e.printStackTrace();                                          }  

Investigating Mobile Solutions for News Spreading

96

                             }                                       @Override                                 public  void  onIOException(IOException  e,  Object  state)  {                                }                                             @Override                                public  void  onFileNotFoundException(FileNotFoundException  e,                                    Object  state)  {                                 }                                               @Override                                 public  void  onMalformedURLException(MalformedURLException  e,                                                                      Object  state)  {                               }                                             @Override                                 public  void  onFacebookError(FacebookError  e,  Object  state)  {                                 }                      });     }         public  void  logoutFromFacebook()  {       String  access_token  =  mPrefs.getString("access_token",  null);       long  access_expires  =  mPrefs.getLong("access_expires",  0);       facebook.setAccessToken(access_token);       facebook.setAccessExpires(access_expires);                       if  (facebook.isSessionValid())  {                     mAsyncRunner.logout(this,  new  RequestListener()  {                           @Override                        public  void  onComplete(String  response,  Object  state)  {                             if  (Boolean.parseBoolean(response)  ==  true)  {                                       runOnUiThread(new  Runnable()  {                 @Override                 public  void  run()  {                   saveBooleanIntoPrefs("isLoggedInFB",  false);                 csaveBooleanIntoPrefs("wantToLogoutFromFB",  false);  

                    changeLayout(false);                 }                 });                                     }                                                       }                                             @Override                          public  void  onIOException(IOException  e,  Object  state)  {}                          @Override                          public  void  onFileNotFoundException(FileNotFoundException  e,  Object  state)  {}                              @Override                          public  void  onMalformedURLException(MalformedURLException  e,  Object  state)  {}           @Override                        public  void  onFacebookError(FacebookError  e,  Object  state)  {}                                    });                     }             }             private  void  getExtendedToken(){       String  access_token  =  mPrefs.getString("access_token",  null);       String  app_id  =  mPrefs.getString("app_id",  null);             String  deviceId  =  mPrefs.getString("deviceId",  null);       String  registrationId  =  mPrefs.getString("registrationId",  null);  

String  url  =  "http://10.0.2.2:8888/gcm/ExtendToken.php?access_token="+access_token+"&app_id="+app_id+"&deviceId="+deviceId+"&registrationId="+registrationId;      JsonUtility  jParser  =  new  JsonUtility();  

    try  {         JSONObject  Jobj=  jParser.retrieveJSON(url);         JSONObject  MyJo  =  Jobj.getJSONObject("data");         String  extendedToken  =  MyJo.getString("token");         saveStringIntoPrefs("extendedToken",extendedToken);    

      }  catch  (ClientProtocolException  e)  {         e.printStackTrace();       }  catch  (IOException  e)  {         e.printStackTrace();       }  catch  (JSONException  e)  {  

Investigating Mobile Solutions for News Spreading

97

      e.printStackTrace();       }     }         public  void  onClick(View  v)  {       switch(v.getId())  {       case  R.id.bFBLogin:         loginToFacebook();         break;         }       private  void  changeLayout(boolean  isLoggedInFB)  {             if  (isLoggedInFB)  {         fbLogin.setVisibility(View.INVISIBLE);         fbLogout.setVisibility(View.VISIBLE);             fbLogInOutLayout.setBackgroundResource(R.drawable.bckfanpagemenu2);       }  else  {         fbLogin.setVisibility(View.VISIBLE);         fbLogout.setVisibility(View.INVISIBLE);             fbLogInOutLayout.setBackgroundResource(R.drawable.bckfanpage);       }     }         @Override     protected  void  onPause()  {           super.onPause();       saveBooleanIntoPrefs("isSSO",  true);     }       @Override     protected  void  onResume()  {       super.onResume();       mPrefs  =  getSharedPreferences(prefName,  0);       mAsyncRunner  =  new  AsyncFacebookRunner(facebook);       if  (mPrefs.getBoolean("isLoggedInFB",  true))  {           getProfileInfo();         try  {           Thread.sleep(2000)  ;         }  catch  (InterruptedException  e)  {           e.printStackTrace();         }         changeLayout(true);          Intent  openNewsList  =  new  Intent("com.example.fanpageapp.NEWSLIST");          startActivity(openNewsList);             }  else  if  (  (  !mPrefs.getBoolean("isLoggedInFB",  false)  )           &&  (  mPrefs.getBoolean("wantToLogoutFromFB",  true)  ))  {           logoutFromFacebook();         }       }           @Override     public  void  onBackPressed()  {       }        }  

5.2 Examples of use

In this section we will finally check how to the Fanpage app appears to a random end-user:

we will have a visual proof of what has been documented in the sequence diagram section

and in particular we will again recross the use cases analysed.

Investigating Mobile Solutions for News Spreading

98

5.2.1 The registration to GCM

Case 1:

Preconditions:

User not signed in with his Facebook account

App registered to GCM

Available network connectivity

The user starts the app

Postcondition:

The Login activity is fired

Main occurring events:

The Intro page shows up

Figure 5.1 – Intro page

Investigating Mobile Solutions for News Spreading

99

The user is taken to the NewsList page

Case 2:

Preconditions:

User not signed with his Facebook account

App NOT registered to GCM

Network connectivity available

Registration to GCM successfull

Postcondition:

The app is registered to GCM and Login activity is started.

Main occurring events:

The Intro page shows up

Figure 5.2 – NewsList page

Investigating Mobile Solutions for News Spreading

100

The user is taken to the Login page

Case 3:

Preconditions:

User signed/unsigned with a Facebook account

App NOT registered to GCM

Network connectivity available

At the first time the registration to GCM is NOT successfull while on the second

time it is successfull

Postcondition:

The app is registered to GCM and Login activity is started.

Figure 5.3 – Login page

Investigating Mobile Solutions for News Spreading

101

(For the third case there are not interesting snapshot since the missed registration is

managed in background)

5.2.2 The push handling

Case 1:

Preconditions:

User signed in with the Facebook account

App registered to GCM

Available network connectivity

The user presses on the received Fanpage notification

Postcondition:

The ItemNews activity is fired

Main occurring events:

The Fanpage server push a new message for the Fanpage app

The app is receiving the message and therefore creates a notification

Figure 5.4 – The notification arrival

Investigating Mobile Solutions for News Spreading

102

The notification brings to the ItemNews page

5.2.3 The Facebook login

Case 1:

Preconditions:

User NOT signed in with the Facebook account

App registered to GCM

Available network connectivity

The app user presses the Login button in the Login page

The user provides correct Facebook credentials

Postcondition:

The NewsList activity is fired

Figure 5.5 – The ItemNews page

Investigating Mobile Solutions for News Spreading

103

Main occurring events:

The user will be asked by the Facebook app to provide his credentials

The Facebook platform will validate the credentials provided

The confirmed user is taken to the NewsList page

Figure 5.6 – The Facebook sign in (app form on the left and website form on the right)

Investigating Mobile Solutions for News Spreading

104

Conclusions

This thesis had the aim to show all the steps to take in order to implement an Android app

in agreement with the Ciaopeople necessities.

At first, we have put the app development within the actual context, showing that

• The smartphone market is growing (+42% compared to 2011)

• Android is the most spread mobile OS

• There’s a widespread availability of apps based on the cloud computing philosophy

Then, the app demands (requirements and uses cases) has been specified.

Therefore, (after having deepen the Android OS) the first main goal was to find an

architecture that would have fit these needs. We have taken into account three global

solutions (highlighting advantages and disadvantages):

• Pool

• SMS

• Persistent TCP/IP connection

The last approach seemed to be the more convenient, but every option has failed (for the

most part because the persistent connection kills the batteries’ life), except for the Cloud to

Device Messaging framework. This service, even with few limitations, has been

implemented and made it work. Unfortunately it has been deprecated as of June 26, 2012.

Eventually the choice has fallen on the Google Cloud Messaging for Android.

The Google Cloud Messaging service has proved to be the optimal choice for the Fanpage

Investigating Mobile Solutions for News Spreading

105

needs: compared to the C2DM, some key improvements like the chance to send multiple

requests in once, the increased payload capacity and, the most important, the fact that this

service is not anymore a beta release, made me decide for the GCM service; compared to

the other services, it offers an optimized connection between the device and the Google

servers that is why the battery won’t be affected by this “hidden” persistent connection.

After the GCM introduction, the design and implementation of the app became the centre

of interest of my study: initially we have drafted the critical aspects to take care of and

afterwards we defined some sequence diagrams that specify the interactions between the

sub-elements of the app.

Last but not least, the code behind the activities and the receivers of the Facebook app is

disclosed while the testing showed, in addiction to the layout of the app, the correct

working of the GCM.

In conclusion, the testing has revealed that GCM service instantly pushes messages to the

(correct) device (emulator), even though sometimes it “misses” the call; for this reason, I

consider the GCM a best effort delivery service and I won’t use this technology for apps

that manage classified or confidential data. But for the Fanpage app, the missed receipt of

news does not compromise the correct overall working of the app itself.

Investigating Mobile Solutions for News Spreading

106

Future Works

In my opinion, there are three main aspects in which the app should improve.

The first one is connected to the fact that the approach that has been used for the

development of the Fanpage app is completely reliant on the GCM service.

From one point of view, we take advantage of this choice because in this way we delegate

to the Google cloud some part of the pushing design (the delivery of the messages),

benefiting of the optimized connection (that minimizes bandwidth and battery

consumption) already set between the Google Play store and the Google servers.

But on the other hand, the drawback is that we are too strictly tied to this service: if, for

any reasons, the Google service goes down, the app won’t work anymore.

So the first improvement should be done realizing a rescue package: we could implement

a simple polling solution.

The second improvement regards a different side of the project: the usability of the app. I

think that the requirement that specifies that the Fanpage app must work only when online

is limiting (as already discussed, the requirement reflects the Ciaopeople needs of

retrieving every user interaction with the app, interactions that must be recorded and sent

to the Fanpage servers, which will elaborate them in order to outline the user profile): in

my view, the largest audience ever should be allowed to access to the app. Even though

nowadays it is not unusual to find people that have subscribed a mobile phone tariff that

involves free network connectivity, along with this choice every “low end-users” won’t be

Investigating Mobile Solutions for News Spreading

107

able to fully enjoy the app.

Therefore, I do consider essential to make the Fanpage app usable also for offline users.

The last reflection is connected to the future releases of the app.

During some meetings at Ciaopeople headquarters, it has been decided that the first

release of the app cannot be different to the future ones in the way it elaborates and

handles the JSON messages. As you can imagine, if the next releases bring some revisions

(like the change of the field to be parsed or the implementation of new tags connected with

some new features), it may affect the correct functioning of the previous ones (we must

take into account that there can be a large part of user who won’t update the app).

Therefore, the third improvements must be accomplished along with the development of

the Fanpage API.

Investigating Mobile Solutions for News Spreading

108

Bibliography

[1] Ralph E. Hanson, 2012, “mass communication – living in a media world”

[2] Chris.Dannen, 2011, “Beginning.iOS.Apps.with.Facebook.and.Twitter.APIs”

[3] Marko Gargenta, 2011, “Learning Android”

[4] Chris Haseman, 2011, “Creating Android Applications: Develop and Design”

[5] Mark L. Murphy, 2011, “Android Programming Tutorials”

Investigating Mobile Solutions for News Spreading

109

Sitography

[6] http://www.directessays.com/viewpaper/40217.html

[7] http://csrc.nist.gov/groups/SNS/cloudcomputing/

[8] http://www.cbsnews.com/stories/2010/04/21/tech/main6418458.shtml, Retrieved on

September 16, 2012.

[9] https://developers.facebook.com/docs/reference/apis/

[10] http://www.ciaopeople.it/, Retrieved on October 2, 2012

[11] http://mqtt.org/faq, Retrieved on September 16, 2012.

[12] http://tools.ietf.org/html/rfc6455

[13] https://developers.google.com/android/c2dm/, Retrieved on September 16, 2012.

[14] http://developer.android.com/guide/google/gcm/gcm.html, Retrieved on September

16, 2012.

[15] http://developer.android.com/guide/google/gcm/gs.html, Retrieved on September

16, 2012.

[16] http://www.json.org/javadoc/org/json/JSONObject.html, Retrieved on October 2,

2012

[17] http://www.json.org/javadoc/org/json/JSONArray.html, Retrieved on October 2,

2012

Investigating Mobile Solutions for News Spreading

110