Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Android Application Development, Study notes of Mobile Computing

Study notes for Mobile 1, these notes are for Android and not iOS.

Typology: Study notes

2017/2018

Uploaded on 12/03/2018

cladeus
cladeus 🇨🇦

1 document

1 / 25

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Application Components
Application components are the essential building blocks of an Android application.
There are four different types of application components. Each type serves a distinct purpose and
has a distinct lifecycle that defines how the component is created and destroyed.
Activities
Services
Content Providers
Broadcast Receivers
Activities
An activity represents a single screen with a user interface.
An application typically consists of several activities.
Each activity has a default window. The content of the window is a view or a group of
views.
Services
A service is a component that runs in the background to perform long-running operations
or to perform work for remote processes. (A service does not provide a user interface.)
The lifecycle of a service is simpler than that of an activity.
Content Providers
Content providers are interfaces for sharing data between applications.
By default, Android runs each application in its own sandbox.
The content provider provides a storage-independent mechanism for accessing data.
A content resolver in the client application is required to communicate with the content
provider.
Broadcast Receivers
A broadcast receiver is a component that receives and reacts to broadcast announcements
(Intents).
Gino BiamonteAndroid Application DevelopmentDec. 04, 2013
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19

Partial preview of the text

Download Android Application Development and more Study notes Mobile Computing in PDF only on Docsity!

Application Components

  • Application components are the essential building blocks of an Android application.
  • There are four different types of application components. Each type serves a distinct purpose and

has a distinct lifecycle that defines how the component is created and destroyed.

  • Activities
  • Services
  • Content Providers
  • Broadcast Receivers

Activities

  • (^) An activity represents a single screen with a user interface.
  • An application typically consists of several activities.
  • Each activity has a default window. The content of the window is a view or a group of

views.

Services

  • A service is a component that runs in the background to perform long-running operations

or to perform work for remote processes. (A service does not provide a user interface.)

  • The lifecycle of a service is simpler than that of an activity.

Content Providers

  • Content providers are interfaces for sharing data between applications.
  • By default, Android runs each application in its own sandbox.
  • The content provider provides a storage-independent mechanism for accessing data.
  • A content resolver in the client application is required to communicate with the content

provider.

Broadcast Receivers

  • A broadcast receiver is a component that receives and reacts to broadcast announcements

(Intents).

  • Many broadcasts originate in the system code. For example, announcements that the time

zone has changed, that the battery is low, SMS has been received, etc.

  • Applications can also initiate broadcasts. For example, to let other applications know that

some data has been downloaded to the device and is available for them to use.

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.

  • Intent: abstract description of an operation to be performed.
    • Action: The general action to be performed
    • Data: What should be operated on
    • Component: What will perform the action (optional)
  • 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. For example, your activity could send an intent saying it simply wants someone to open up a web page.
    • In that case, any application that is capable of opening a web page could “compete” to complete this action.

Application Components Summary

  • Android application do not have a single entry point (e.g. no main() function).
  • They have essential components that the system can instantiate and run as needed.
  • Four important components
    • Activity: UI component typically corresponding to one screen
    • (^) Service: Background process without UI
    • Broadcast Receiver: Component that responds to broadcast Intents
    • Content Provider: Component that enables applications to share data

Building a Dynamic UI with Fragments

  • To create a dynamic and multi-pane user interface on Android, you need to encapsulate

UI components and activity behaviors into modules that you can swap into and out of your activity.

  • You can create these modules with the Fragment class, which behaves somewhat like a

nested activity that can define its own layout and manage its own lifecycle.

  • When a fragment specifies its own layout, it can be configured in different combinations

with other fragments inside an activity to modify your layout configuration for different screen sizes.

Services

  • A service is an application component that can perform long-running operations in the

background and does not provide a user interface.

  • Another application component can start a service and it will continue to run in the

background even if the user switches to another application.

  • Additionally, a component can bind to a service to interact with it and even perform inter

process communication (IPC).

  • For example, a service might handle network transactions, play music, perform file I/O,

or interact with a content provider, all from the background.

  • A service can essentially take two forms:
    • Started:

■ A service is “started” when an application component (such as an activity) starts it by calling startService().

■ Once started, a service can run in the background indefinitely, even if the component that started it is destroyed.

  • Bound:

■ A service is “bound” when an application component binds to it by calling bindService().

■ A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with inter process communication (IPC).

■ A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

  • Caution:
    • A service runs in the main thread of its hosting process – the service does not create its own thread and does not run in a separate process (unless you specify other). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application’s main thread can remain dedicated to user interaction with your activities.
  • The most important callback methods you should override are:
    • OnStartCommand()

■ The system calls this method when another component, such as an activity, requests that the service be started, by calling startService().

  • onBind()

■ The system calls this method when another component wants to bind with the service by calling bindService().

  • (^) onCreate()

■ The system calls this method when the service is first created.

  • onDestroy()

■ The system calls this method when the service is no longer used and is being destroyed.

Broadcast Receivers

  • Broadcast receivers are Android’s implementation of a system-wide publish / subscribe

mechanism.

  • Storage Options: I
    • Shared Preferences:

■ Shared preferences are private data stored in key value pairs.

  • Internal Storage:

■ Internal storage is a location where you can save files on the device’s internal storage (NAND Flash).

■ By default, files stored in internal storage are private to your application, and other applications cannot access them *neither can the user of the device.)

■ When the user uninstalls the application, the private files are removed.

  • External Storage:

■ Every Android device supports shared external storage that you can use to store files.

■ This can either be the removable storage such as a Secure Digital Card (SD Card) or non-removable internal storage (NAND).

  • Storage Options: II
    • SQLite Database:

■ Android supports the full use of SQLite databases.

■ You can create tables and perform SQL queries against the tables accordingly.

  • Local Cache:

■ If you’d like to cache some data rather than store it persistently, the internal data directory is where you should create the cache.

■ If you store data here and the system gets low on internal storage space, Android may delete these files to reclaim space.

■ You should stay within a reasonable limit of space consumed of around 1MB.

  • Network Connection:

■ This can be any remote data source that you have access to.

■ For example, Flick exposes an API that allows you to store images on its servers.

■ Your application could work with Flickr to store your images.

Permissions

  • Storing data anywhere on the device requires some sort of permission from the user.
  • (^) Android defines a permission scheme meant to protect resources and features on the

device.

  • For example, applications, by default, cannot access the contacts list, make phone calls, and so on to protect the user from malicious applications.
  • When users install applications from the Android market, the application’s manifest file

is inspected for required permissions that the application needs to operate.

  • It is then up to the user to decide whether he would like to install the application.
  • When you need to request permissions, you need to add them to the

AndroidManifest.xml file in your project.

Shared Preferences

  • You can use SharedPreferences to save any primitive data: Booleans, floats, ints, longs,

and strings.

  • This data will persist across user sessions (even if your application is killed).
  • Then close the stream with close()
  • Better use try… catch to handle file i/o exceptions
  • Import java.io.FileInputStream and java.io.FileOutputStream

Processes & Threads

  • Every application runs its own process and all components of the application run in that

process, by default

  • Any slow, blocking operations in an activity should be done in a new thread, to avoid

slowing down the user interface

  • When an application component starts and the application does not have any other

components running, the Android system starts a new Linux process for the application with a single thread of execution.

  • By default, all components of the same application run in the same process and thread

(called the “main” thread).

  • By default, all components of the same application run in the same process and most

applications should not change this.

  • However, if you find that you need to control which process a certain component belongs

to, you can do so in the manifest file.

  • The Android system tries to maintain an application process for as long as possible, but

eventually needs to remove old processes to reclaim memory for new or more important processes.

  • To determine which processes to keep and which to kill, the system places each process

into an “importance hierarchy” based on the components running in the process and the state of those components.

  • Processes with the lowest importance are eliminated first, then those with the next lowest

importance, and so on, as necessary to recover system resources.

  • (^) There are five levels in the importance hierarchy. The following list presents the different

types of processes in order of importance (the first process is most important and is killed last):

  • Foreground Process
  • Visible Process
  • Service Process
  • Background Process
  • Empty Process
  • Foreground Process
    • A process that is required for what the user is currently doing a process is considered to be in the foreground if any of the following conditions are true:

■ It hosts an Activity that the user is interacting with (the Activity’s onResume() method has been called).

■ It hosts a Service that’s bound to the activity that the user is interacting with.

■ It hosts a Service that’s running “in the foreground” – the service has called startForeground().

■ It hosts a Service that’s executing one of its lifecycle callbacks (onCreate (), onStart(), or onDestroy()).

■ It hosts a BroadcastReceiver that’s executing its onReceive() method.

  • (^) Visible Process
    • A process that doesn’t have any foreground components, but still can affect what the user sees on screen.
    • A process is considered to be visible if either of the following conditions are true:

■ It hosts an Activity that is not in the foreground, but is still visible to the user (its onPause() method has been called).

■ It hosts a service that’s bound to a visible (or foreground) activity.

  • Service Process
    • A process that is running a service that has been started with the startService() method and does not fall into either of the two higher categories.
  • Specifically, if everything is happening in the UI thread, performing long operations such

as network access or database queries will block the whole UI.

  • When the thread is blocked, no events can be dispatched, including drawing events.
  • The android UI toolkit is not thread-safe. So, you must not manipulate your UI from a

worker thread – you must do all manipulation to your user interface from the UI thread.

  • Thus, there are simply two rules to Android’s single thread model:
    • Do not block the UI thread
    • Do not access the Android UI toolkit from outside the UI thread
  • Worker Threads
    • Because of the single thread model described above, it’s vital to be the responsiveness of your application’s UI that you do not block the UI thread.
    • If you have operations to perform that are not instantaneous, you should make sure to do them in separate threads (“background” or “worker” threads).

AsyncTask

  • An asynchronous task is defined by a computation that runs on a background thread and

whose result is published on the UI thread.

  • An asynchronous task is defined by 3 generic types, called
    • Params
    • Progress
    • Result
  • And 4 steps called
    • onPreExecute()
    • doInBackground()
  • onProgressUpdate()
  • onPostExecute()
  • To use AsyncTask, you must subclass AsyncTask and:
  • Implement the doInBackground() callback method, which runs in a pool of background threads.
  • To update your UI, you should implement onPostExecute(), which delivers the result from doInBackground() and runs in the UI thread, so you can safely update your UI.
  • You can then run the task by calling execute() from the UI thread.

Internet Resources

  • To check the network status and to connect to the internet, your application manifest

must include the following permissions:

  • <uses-permission android: name = ”android.permission.INTERNET” />
  • <uses-permission android: name = “android.permission.ACCESS_NETWORK_STATE” />
  • Android supports two HTTP clients
  • HttpURLConnection
  • Apache HttpClient

import java.util.Calendar;

import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView;

public class Token_Main_Activity extends Activity implements OnClickListener { // Initializes constants, variables, intents, handlers and views. final int X = 1245; final int Y = 10000;

Intent verify; private Handler handler;

Calendar cal; TextView Passcode, Time; static int passNumber , min , sec ; boolean Running = true ;

@Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout. token_main_layout ); setupVariables(); setupThread(); generatePasscode(); }

// Sets up handlers, intents & views. public void setupVariables() { verify = new Intent( this , Token_Verify. class ); handler = new Handler(); Passcode = (TextView)findViewById(R.id. textView3 ); Time = (TextView)findViewById(R.id. textView4 ); }

// Generates the passcode. public void generatePasscode() { cal = Calendar. getInstance (); min = cal.get(Calendar. MINUTE ); passNumber = min * X + Y; Passcode.setText("" + passNumber ); }

// Starts the Verify activity when clicked. @Override public void onClick(View V) {

switch (V.getId()) { case R.id. bVerify : startActivity(verify); break ; }

}

// Worker thread constantly running in the background, updates seconds & local passcodes. public void setupThread() { Runnable runnable = new Runnable() { @Override public void run() { while (Running) { try { Thread. sleep (1000); } catch (InterruptedException e) { e.printStackTrace(); }

handler.post( new Runnable() { @Override public void run() { cal = Calendar. getInstance (); sec = cal.get(Calendar. SECOND ); Time.setText("" + (60 - sec ));

if ( sec == 0) generatePasscode(); } }); } } };

new Thread(runnable).start(); } }

package token.biamonte.ass4;

import java.io.BufferedReader;

connMgr = (ConnectivityManager)getSystemService (Context. CONNECTIVITY_SERVICE ); accepted = MediaPlayer. create ( this , R.raw. accepted ); rejected = MediaPlayer. create ( this , R.raw. rejected ); passcodeApp = (TextView)findViewById(R.id. tvPassApp ); passcodeServ = (TextView)findViewById(R.id. tvPassServ ); Check = (Button)findViewById(R.id. bFinish ); }

// Obtains the passcode from the server, then compares it to the locally generated passcode. public void checkPasscode() { URL[i] = new getHttp(); URL[i].execute("http://faculty.tru.ca/helmiligi/pass.php"); i++; }

// Checks if the application is connected to the internet. public void checkConnection() { NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

if (networkInfo != null && networkInfo.isConnected()) Toast. makeText ( this , "Network is connected..", Toast. LENGTH_SHORT ).show(); else Toast. makeText ( this , "Network is NOT connected..", Toast. LENGTH_SHORT ).show(); }

// Finishes this activity when clicked. @Override public void onClick(View V) { switch (V.getId()) { case R.id. bFinish : this .finish(); break ; }

}

// getHttp subclass, uses the Apache HttpClient. public class getHttp extends AsyncTask <String, Void, String> {

// Initializes variables. HttpClient httpclient = new DefaultHttpClient(); HttpPost post; HttpResponse response; HttpEntity entity; String url, result; int passcode;

// Downloads files in a worker thread. @Override protected String doInBackground(String... arg0) { url = arg0[0]; post = new HttpPost(url); try { response = httpclient.execute(post); entity = response.getEntity();

if (entity != null ) { InputStream instream = entity.getContent(); result = convertStreamToString(instream); instream.close(); } } catch (Exception e) {}

return result; }

// Converts html / php strings to proper strings, then compares passcodes. @Override