Mobile Application Development: by Wahid Qayyum
Mobile Application Development: by Wahid Qayyum
Mobile Application Development: by Wahid Qayyum
Development
by Wahid Qayyum
The Course
• Title
Mobile Application Development
• Code
SE326
• Prerequisites
Object Oriented Programming (CSC321)
• Instructor
Wahid Qayyum
• Email
wahidqayyum@lgu.edu.pk
What you will learn in this course
• Understand fundamentals of Android Development.
• Anatomy of an Android Application.
• Understand complete Lifecycle of an Android Application.
• How to build GUI of an Android Application.
• All types of mobile application’s Layouts.
• Backend Programming of an Android Application.
• Creating project on Android Studio.
• How to create APK and deploy it.
Mobile Computing Family
Mobile Computing is a technology which allows a wireless enabled electronic device to:
Data, voice and video reception, transmission and processing anywhere and anytime.
Main Concepts
Mobile Communication
Mobile Hardware
Mobile Software
Mobile Communication
ROM
Write-Protected flash contains very first code run by the processor
Memory
RAM, low power, double data rate, dynamic RAM.
Storage
Internal Storage, two partitions, one for firmware and other for user apps, files and data.
External Storage, microSD Card.
Mobile Hardware
Display
Primary camera W/WO flash.
Secondary camera W/WO flash.
Battery.
Speakers.
Microphones.
And other components…
Mobile Software
• Start Talking
• Start Talking
• A few games
Featured Mobile Phones
• Camera
• Check Emails
Smart Phones
• Calls, SMS, Games
• Camera
• Use Internet on Mobile Phone
• Check Emails
• Enjoy Music
• Watch Videos
• Use Social Networks
• Maps
• Read Books
• Do almost everything that can be done on a Computer .
Why to develop for Mobile?
• World’s Population
• Is Around
• 7.7 Billion
Why Android Development
What is Android?
Increased Marketing
Reduced cost of
Develoment
Rich Development
Environment
Features of Android
• Beautiful UI
• Connectivity
• Storage
• Media Support
• Messaging
• Web Browser
• Multi-touch
• Multi-tasking
• Resizeable Widgets
• Multi Language
• Wi-Fi Direct
Categories of Android Application
Music Sports Travel
• Content Providers
• Resource Manager
• Notifications Manager
• View System
Applications
This is the top layer. You will write your application to be installed on this layer only.
Examples of such applications are Contacts Books, Browser, Games etc.
Anatomy of an Android Application
• Application components are the essential building blocks of an Android application. These
components are loosely coupled by the application manifest file AndroidManifest.xml that
describes each component of the application and how they interact.
• There are following four main components that can be used within an Android application:
• Activities
• Services
• Broadcast Receivers
• Content Providers
Activities
• They dictate the UI and handle the user interaction to the smart phone screen.
• An activity is implemented as a subclass of Activity class as follows
• public class MainActivity extends Activity
{
}
Services
• They handle background processing associated with an application.
• A service is implemented as a subclass of Service class as follows
• public class MyService extends Service
{
}
Broadcast Receivers
• They handle communication between Android OS and applications.
• A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each
message is broadcasted as an Intent object.
• public class MyReceiver extends BroadcastReceiver
{
public void onReceive (context, intent) {
}
}
Content Providers
• They handle data and database management issues.
• A content provider is implemented as a subclass of ContentProvider class and must
implement a standard set of APIs that enable other applications to perform transactions.
• public class MyContentProvider extends ContentProvider
{
public void onCreate() {
}
}
Additional Components
• Fragment Represents a portion of user interface in an Activity.
• View UI elements that are drawn on-screen including buttons, lists forms etc.
• Layout View hierarchies that control screen format and appearance of the views.
• Intent Messages wiring components together.
• Resource External elements, such as strings, constants and drawable pictures.
• Manifest Configuration file for the application.
Android Developer Fundamentals V2
41
Contents
● Android Studio
● Creating "Hello World" app in Android Studio
● Basic app development workflow with Android Studio
● Running apps on virtual and physical devices
42
Prerequisites
43
Android Studio
44
What is Android Studio?
45
Android Studio interface
1. Toolbar
2. Navigation bar
3. Project pane
4. Editor
5. Tabs for other
panes
46
Installation Overview
47
Creating your
first Android app
48
Start Android Studio
49
Create a project inside Android Studio
50
Name your app
51
Pick activity template
● Good practice:
○ Name main activity
MainActivity
○ Name layout
activity_main
● Use AppCompat
● Generating layout file
is convenient
53
Project folders
54
Gradle build system
○ project
○ module
○ settings
55
Run your app
1. Run
2. Select virtual
or physical
device
3. OK
56 56
Create a virtual device
Use emulators to test app on different versions of Android and form factors.
57
Configure virtual device
1. Choose hardware
2. Select Android version
3. Finalize
58
Run on a virtual device
59
Run on a physical device
Windows drivers:
● OEM USB Drivers
60
Get feedback as your app runs
61
Adding logging to your app
62
The Logcat pane
63
Logging statement
import android.util.Log;
64
Learn more
65
Learn even more
66
What's Next?
67
END
68
Android Developer Fundamentals V2
Lesson 1
70
Contents
71
Views
72
Everything you see is a view
Views
73
What is a view?
74
Examples of view subclasses
Button CheckBox
EditText RadioButton
Slider Switch
75
View attributes
76
Create views and layouts
77
Android Studio layout editor
78
View defined in XML
<TextView
android:id="@+id/show_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/myBackgroundColor"
android:text="@string/count_initial_value"
android:textColor="@color/colorPrimary"
android:textSize="@dimen/count_text_size"
android:textStyle="bold"
/>
79
View attributes in XML
android:<property_name>="<property_value>"
Example: android:layout_width="match_parent"
android:<property_name>="@<resource_type>/resource_id"
Example: android:text="@string/button_label_next"
android:<property_name>="@+id/view_id"
Example: android:id="@+id/show_count"
80
Create View in Java code
context
In an Activity:
81
What is the context?
82
Custom views
● Over 100 (!) different types of views available from the Android system, all children of the View class
● If necessary, create custom views by subclassing existing views or the View class
83
ViewGroup and
View hierarchy
84
ViewGroup contains "child" views
● ConstraintLayout: Positions UI elements using constraint connections to other elements and to the
layout edges
● ScrollView: Contains one element and enables scrolling
● RecyclerView: Contains a list of elements and enables scrolling by adding and removing elements
dynamically
85
ViewGroups for layouts
Layouts
● are specific types of ViewGroups (subclasses of ViewGroup)
● contain child views
● can be in a row, column, grid, table, absolute
86
Common Layout Classes
87
Common Layout Classes
88
Class hierarchy vs. layout hierarchy
89
Hierarchy of viewgroups and views
90
View hierarchy and screen layout
91
View hierarchy in the layout editor
92
Layout created in XML
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
... />
<TextView
... />
<Button
... />
</LinearLayout
93
Layout created in Java Activity code
linearL.addView(myText);
setContentView(linearL);
94
Set width and height in Java code
LinearLayout.LayoutParams layoutParams =
new Linear.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_CONTENT);
myView.setLayoutParams(layoutParams);
95
Best practices for view hierarchies
96
The layout editor
and Constraint
Layout
97
The layout editor with ConstraintLayout
98
What is ConstraintLayout?
99
Layout editor main toolbar
10
ConstraintLayout toolbar in layout editor
10
Autoconnect
10
ConstraintLayout handles
1. Resizing handle
2. Constraint line and handle
3. Constraint handle
4. Baseline handle
10
Align elements by baseline
10
Attributes pane
10
Attributes pane view inspector
10
Layout_width and layout_height
10
Set attributes
4. Click at top or View more attributes at bottom to see and change more attributes
10
Set attributes example: TextView
10
Preview layouts
11
Create layout variant for landscape
11
Create layout variant for tablet
11
Event Handling
11
Events
11
Event Handlers
11
Attach in XML and implement in Java
11
Alternative: Set click handler in Java
11
Resources and
measurements
11
Resources
11
Where are the resources in your project?
12
Refer to resources in code
● Layout:
R.layout.activity_main
setContentView(R.layout.activity_main);
● View:
R.id.recyclerview
rv = (RecyclerView) findViewById(R.id.recyclerview);
● String:
In Java: R.string.title
In XML: android:text="@string/title"
12
Measurements
12
Learn more
12
Learn more
Views:
● View class documentation
● device independent pixels
● Button class documentation
● TextView class documentation
Layouts:
● developer.android.com Layouts
● Common Layout Objects
12
Learn even more
Resources: Other:
● Android resources ● Android Studio documentation
● Color class definition ● Image Asset Studio
● R.color resources ● UI Overview
● Supporting Different Densities ● Vocabulary words and concepts glos
● Color Hex Color Codes sary
● Model-View-Presenter
(MVP) architecture pattern
● Architectural patterns
12
What's Next?
12
END
12
Android Developer Fundamentals V2
Activities and
Intents
Lesson 2
12
Contents
● Activities
● Defining an Activity
● Starting a new Activity with an Intent
● Passing data between activities with extras
● Navigating between activities
13
Activities
(high-level view)
13
What is an Activity?
13
What does an Activity do?
13
Examples of activities
13
Apps and activities
13
Layouts and Activities
13
Implementing
Activities
13
Implement new activities
○ extends AppCompatActivity
3. Connect Activity with Layout
13
1. Define layout in XML
13
2. Define Activity Java class
14
3. Connect activity with layout
14
4. Declare activity in Android manifest
<activity android:name=".MainActivity">
14
4. Declare main activity in manifest
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
14
Intents
14
What is an intent?
An Intent is an object used to request an action from another app component via the Android system.
Intent Action
Android
System
14
What can intents do?
● Start an Activity
14
Explicit and implicit intents
Explicit Intent
● Starts a specific Activity
○ Request tea with milk delivered by Nikita
○ Main activity starts the ViewShoppingCart Activity
Implicit Intent
● Asks system to find an Activity that can handle this request
○ Find an open store that sells green tea
○ Clicking Share opens a chooser with a list of apps
14
Starting
Activities
14
Start an Activity with an explicit intent
1. Create an Intent
○ startActivity(intent);
14
Start an Activity with implicit intent
To ask Android to find an Activity to handle your request, use an implicit Intent
1. Create an Intent
○ startActivity(intent);
15
Implicit Intents - Examples
15
Sending and
Receiving Data
15
Two types of sending data with intents
15
Sending and retrieving data
15
Putting a URI as intent data
15
Put information into intent extras
15
Get data from intents
● getData();
⇒ Uri locationUri = intent.getData();
● int getIntExtra (String name, int defaultValue)
⇒ int level = intent.getIntExtra("level", 0);
● Bundle bundle = intent.getExtras();
⇒ Get all the data at once as a bundle.
● See documentation for all
15
Returning data to the starting activity
16
startActivityForResult()
startActivityForResult(intent, requestCode);
● Starts Activity (intent), assigns it identifier (requestCode)
● Returns data via Intent extras
● When done, pop stack, return to previous Activity, and execute
onActivityResult() callback to process returned data
● Use requestCode to identify which Activity has "returned"
16
1. startActivityForResult() Example
16
2. Return data and finish second activity
// Create an intent
Intent replyIntent = new Intent();
16
3. Implement onActivityResult()
16
Navigation
16
Activity stack
● When a new Activity is started, the previous Activity is stopped and pushed on the Activity
back stack
● Last-in-first-out-stack—when the current Activity ends, or the user presses the Back button, it is
popped from the stack and the previous Activity resumes
16
Activity Stack
16
Two forms of navigation
16
Back navigation
16
Up navigation
<activity
android:name=".ShowDinnerActivity"
android:parentActivityName=".MainActivity" >
</activity>
17
Learn more
17
Learn more
17
What's Next?
17
END
17
Android Developer Fundamentals V2
Activities and
Intents
Lesson 2
17
Contents
● Activity lifecycle
● Activity lifecycle callbacks
● Activity instance state
● Saving and restoring Activity state
17
Activity lifecycle
17
What is the Activity Lifecycle?
More formally:
● A directed graph of all the states an Activity can be in,
and the callbacks associated with transitioning from
each state to the next one
17
What is the Activity Lifecycle?
18
Activity states and app visibility
18
Activity lifecycle
callbacks
18
Callbacks and when they are called
18
Activity states and callbacks graph
18
Implementing and overriding callbacks
18
onCreate() –> Created
● Called when the Activity is first created, for example when user taps launcher icon
● Does all static setup: create views, bind data to lists, ...
● Only called once during an activity's lifetime
● Takes a Bundle with Activity's previously frozen state, if there was one
● Created state is always followed by onStart()
18
onCreate(Bundle savedInstanceState)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The activity is being created.
}
18
onStart() –> Started
18
onStart()
@Override
protected void onStart() {
super.onStart();
// The activity is about to become visible.
}
18
onRestart() –> Started
19
onRestart()
@Override
protected void onRestart() {
super.onRestart();
// The activity is between stopped and started.
}
19
onResume() –> Resumed/Running
19
onResume()
@Override
protected void onResume() {
super.onResume();
// The activity has become visible
// it is now "resumed"
}
19
onPause() –> Paused
19
onPause()
@Override
protected void onPause() {
super.onPause();
// Another activity is taking focus
// this activity is about to be "paused"
}
19
onStop() –> Stopped
19
onStop()
@Override
protected void onStop() {
super.onStop();
// The activity is no longer visible
// it is now "stopped"
}
19
onDestroy() –> Destroyed
19
onDestroy()
@Override
protected void onDestroy() {
super.onDestroy();
// The activity is about to be destroyed.
}
19
Activity instance
state
20
When does config change?
Configuration changes invalidate the current layout or other resources in your activity when the user:
● Rotates the device
● Chooses different system language, so locale changes
● Enters multi-window mode (from Android 7)
20
What happens on config change?
20
Activity instance state
20
Saving and
restoring Activity
state
20
What the system saves
20
Saving instance state
20
onSaveInstanceState(Bundle outState)
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Add information for saving HelloToast counter
// to the to the outState bundle
outState.putString("count",
String.valueOf(mShowCount.getText()));
}
20
Restoring instance state
20
Restoring in onCreate()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mShowCount = findViewById(R.id.show_count);
if (savedInstanceState != null) {
String count = savedInstanceState.getString("count");
if (mShowCount != null)
mShowCount.setText(count);
}
}
20
onRestoreInstanceState(Bundle state)
@Override
public void onRestoreInstanceState (Bundle mySavedState) {
super.onRestoreInstanceState(mySavedState);
if (mySavedState != null) {
String count = mySavedState.getString("count");
if (count != null)
mShowCount.setText(count);
}
}
21
Instance state and app restart
When you stop and restart a new app session, the Activity instance
states are lost and your activities will revert to their default
appearance
If you need to save user data between app sessions, use shared
preferences or a database.
21
Learn more
21
What's Next?
21
END
21
Android Developer Fundamentals V2
Activities and
Intents
Lesson 2
21
Contents
● Intent—recap
● Implicit Intent overview
● Sending an implicit Intent
● Receiving an implicit Intent
21
Recap: Intent
21
What is an Intent?
An Intent is:
● Description of an operation to be performed
● Messaging object used to request an action from another app component via the Android system.
Intent Action
Android
System
21
What can an Intent do?
22
Explicit vs. implicit Intent
Implicit Intent — Asks system to find an Activity class with a registered handler that can handle this request
22
Implicit Intent
overview
22
What you do with an implicit Intent
● Start an Activity in another app by describing an action you intend to perform, such as "share an
article", "view a map", or "take a picture"
● Specify an action and optionally provide data with which to perform the action
● Don't specify the target Activity class, just the intended action
22
What system does with implicit Intent
● Android runtime matches the implicit intent request with registered intent handlers
● If there are multiple matches, an App Chooser will open to let the user decide
22
How does implicit Intent work?
22
App Chooser
22
Sending an
implicit Intent
22
Sending an implicit Intent
User has pressed Call button — start Activity that can make
a call (no data is passed in or returned)
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
22
Sending an implicit Intent with data URI
23
Providing the data as URI
● Uri.parse("tel:8005551234")
● Uri.parse("geo:0,0?q=brooklyn%20bridge%2C%20brooklyn%2C%20ny")
● Uri.parse("http://www.android.com");
Uri documentation
23
Implicit Intent examples
2. Put extras
String query = edittext.getText().toString();
intent.putExtra(SearchManager.QUERY, query));
23
Sending an implicit Intent with type and category
23
Sending an implicit Intent with type and category
3. Start the Activity
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(myIntent,ACTIVITY_REQUEST_CREATE_FILE);
}
23
Common actions for an implicit Intent
23
Apps that handle common actions
23
Receiving an
Implicit Intent
23
Register your app to receive an Intent
24
Intent filter in AndroidManifest.xml
<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
24
Intent filters: action and category
24
Intent filters: data
24
An Activity can have multiple filters
<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
...
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE"/>
...
</intent-filter>
</activity> An Activity can have several filters
24
A filter can have multiple actions & data
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<action android:name="android.intent.action.SEND_MULTIPLE"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="image/*"/>
<data android:mimeType="video/*"/>
</intent-filter>
24
Learn more
24
Learn more
24
What's Next?
24
END
24
Android Fragments
Fragments
• Prior to fragment introduction, we had a limitation because we can show only a single
activity on the screen at one given point in time. So we were not able to divide device
screen and control different parts separately. But with the introduction of fragment we got
more flexibility and removed the limitation of having a single activity on the screen at a
time. Now we can have a single activity but each activity can comprise of multiple
fragments which will have their own layout, events and complete life cycle.
Fragments
• You create fragments by extending Fragment class and You can insert a fragment into
your activity layout by declaring the fragment in the activity's layout file, as
a <fragment> element.
Fragments for a Handset or Mobile
Note: On a handset-sized screen, there's not enough room for both fragments, so Activity A includes only the fragment for the list of articles, and
when the user selects an article, it starts Activity B, which includes the second fragment to read the article.
Fragments for a Tablet
Note: An application can embed two fragments in Activity A, while running on a tablet-sized device.
Fragment Life Cycle
• Android fragments have their own life cycle very similar to an android activity. This
section briefs different stages of its life cycle.
Fragment Methods (Cont…)
• onAttach()
• onStart()
This method is called once the fragment gets visible.
• onResume()
Fragment becomes active.
• onPause()
The system calls this method as the first indication that the user is
leaving the fragment.
• onStop()
Fragment Methods
• onDestroyView()
Fragment view will destroy after call this method.
• onDestroy()
This method is called when final clean up of the fragment state.
• onDetach()
The fragment instance is disassociated with an activity.
Types of Fragments
• This example will explain you how to create your own Single Frame
Fragment. We will create two fragments and one of them will be used
when device is in landscape mode and another fragment will be used in
case of portrait mode. Follow the following steps to create Single Frame
Fragment.
Step 1: MainActivity.java
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.os.Bundle;
import android.app.Activity;
package com.example.fragmentdemo;
• Following is the content of LM_Fragement.java file
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
package com.example.fragmentdemo;
• Following is the content of PM_Fragement.java file
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
</LinearLayout>
Step 7: strings.xml
• Following<resources>
will be the content of res/values/strings.xml file
<string name="app_name">FragmentDemo</string>
<string name="landscape_message">This is Landscape Fragment</string>
<string name="portrait_message">This is Portrait Fragment</string>
</resources>
Output: Emulator Window