Android Unit 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 251

Android Developer Fundamentals

Storing Data

Lesson 9

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 1
4.0 International License
9.0 Storing Data

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 2
4.0 International License
Storage
Options

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 3
4.0 International License
Storing data

● Shared Preferences—Private primitive data in key-value pairs


● Internal Storage—Private data on device memory
● External Storage—Public data on device or external storage
● SQLite Databases—Structured data in a private database
● Content Providers—Store privately and make available publicly

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 4
4.0 International License
Storing data beyond Android

● Network Connection—On the web with your own server


● Cloud Backup—Back up app and user data in the cloud
● Firebase Realtime Database—Store and sync data with
NoSQL cloud database across clients in realtime

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 5
4.0 International License
Files

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 6
4.0 International License
Android File System

● External storage -- Public directories


● Internal storage -- Private directories for just your app

Apps can browse the directory structure


Structure and operations similar to Linux and java.io

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 7
4.0 International License
Internal storage
● Always available
● Uses device's filesystem
● Only your app can access files, unless explicitly set to be
readable or writable
● On app uninstall, system removes all app's files from
internal storage

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 8
4.0 International License
External storage

● Not always available, can be removed


● Uses device's file system or physically external storage like
SD card
● World-readable, so any app can read
● On uninstall, system does not remove files private to app

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 9
4.0 International License
When to use internal/external storage
Internal is best when
● you want to be sure that neither the user nor other apps
can access your files
External is best for files that
● don't require access restrictions and for
● you want to share with other apps
● you allow the user to access with a computer

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 10
4.0 International License
Save user's file in shared storage

● Save new files that the user acquires through your app to
a public directory where other apps can access them and
the user can easily copy them from the device
● Save external files in public directories

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 11
4.0 International License
Internal Storage

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 12
4.0 International License
Internal Storage

● Uses private directories just for your app


● App always has permission to read/write
● Permanent storage directory—getFilesDir()
● Temporary storage directory—getCacheDir()

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 13
4.0 International License
Creating a file

File file = new File(


context.getFilesDir(), filename);

Use standard java.io file operators or streams


to interact with files

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 14
4.0 International License
External
Storage

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 15
4.0 International License
External Storage
● On device or SD card
● Set permissions in Android Manifest
○ Write permission includes read permission

<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 16
4.0 International License
Always check availability of storage

public boolean isExternalStorageWritable() {


String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 17
4.0 International License
Example external public directories
● DIRECTORY_ALARMS and DIRECTORY_RINGTONES
For audio files to use as alarms and ringtones
● DIRECTORY_DOCUMENTS
For documents that have been created by the user
● DIRECTORY_DOWNLOADS
For files that have been downloaded by the user

developer.android.com/reference/android/os/Environment.html
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 18
4.0 International License
Accessing public external directories
1. Get a path getExternalStoragePublicDirectory()
2. Create file

File path = Environment.getExternalStoragePublicDirectory(


Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 19
4.0 International License
How much storage left?
● If there is not enough space, throws IOException
● If you know the size of the file, check against space
○ getFreeSpace()
○ getTotalSpace().
● If you do not know how much space is needed
○ try/catch IOException

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 20
4.0 International License
Delete files no longer needed

● External storage
myFile.delete();

● Internal storage
myContext.deleteFile(fileName);

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 21
4.0 International License
Do not delete the user's files!
When the user uninstalls your app, your app's private storage
directory and all its contents are deleted
Do not use private storage for content that belongs to the user!
For example
● Photos captured or edited with your app
● Music the user has purchased with your app

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 22
4.0 International License
What is Shared Preferences?

● Read and write small amounts of primitive data as


key/value pairs to a file on the device storage
● SharedPreference class provides APIs for reading, writing,
and managing this data
● Save data in onPause()
restore in onCreate()
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 23
4.0 International License
Shared Preferences AND
and Saved
SavedInstance
InstanceState
State

● Small number of key/value pairs


● Data is private to the application

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 24
4.0 International License
Shared Preferences vs. Saved Instance State

● Persist data across user sessions, ● Preserves state data across


even if app is killed and restarted, activity instances in same user
or device is rebooted session
● Data that should be remembered
● Data that should not be
across sessions, such as a user's
remembered across sessions,
preferred settings or their game
such as the currently selected
score
tab or current state of activity.
● Common use is to store user
● Common use is to recreate state
preferences
after the device has been rotated

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 25
4.0 International License
Creating Shared Preferences

● Need only one Shared Preferences file per app


● Name it with package name of your app—unique and easy
to associate with app
● MODE argument for getSharedPreferences() is for
backwards compatibility—use only MODE_PRIVATE to be
secure
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 26
4.0 International License
getSharedPreferences()

private String sharedPrefFile =


"com.example.android.hellosharedprefs";
mPreferences =
getSharedPreferences(sharedPrefFile,
MODE_PRIVATE);

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 27
4.0 International License
Saving Shared Preferences

● SharedPreferences.Editor interface
● Takes care of all file operations
● put methods overwrite if key exists
● apply() saves asynchronously and safely

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 28
4.0 International License
SharedPreferences.Editor
@Override
protected void onPause() {
super.onPause();
SharedPreferences.Editor preferencesEditor =
mPreferences.edit();
preferencesEditor.putInt("count", mCount);
preferencesEditor.putInt("color", mCurrentColor);
preferencesEditor.apply();
}
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 29
4.0 International License
Restoring Shared Preferences

● Restore in onCreate() in Activity


● Get methods take two arguments—the key, and the default
value if the key cannot be found
● Use default argument so you do not have to test whether
the preference exists in the file

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 30
4.0 International License
Getting data in onCreate()
mPreferences = getSharedPreferences(sharedPrefFile, MODE_PRIVATE);
if (savedInstanceState != null) {
mCount = mPreferences.getInt("count", 1);
mShowCount.setText(String.format("%s", mCount));

mCurrentColor = mPreferences.getInt("color", mCurrentColor);


mShowCount.setBackgroundColor(mCurrentColor);

mNewText = mPreferences.getString("text", "");


} else { … }

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 31
4.0 International License
Clearing

● Call clear() on the SharedPreferences.Editor and apply


changes

● You can combine calls to put and clear. However, when


you apply(), clear() is always done first, regardless of
order!
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 32
4.0 International License
clear()

SharedPreferences.Editor preferencesEditor =
mPreferences.edit();
preferencesEditor.clear();
preferencesEditor.apply();

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 33
4.0 International License
Listening to
Changes

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 34
4.0 International License
Listening to changes
● Implement interface
SharedPreference.OnSharedPreferenceChangeListener
● Register listener with
registerOnSharedPreferenceChangeListener()
● Register and unregister listener in onResume() and
onPause()
● Implement on onSharedPreferenceChanged() callback
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 35
4.0 International License
Interface and callback
public class SettingsActivity extends AppCompatActivity
implements OnSharedPreferenceChangeListener { ...

public void onSharedPreferenceChanged(


SharedPreferences sharedPreferences, String key) {
if (key.equals(MY_KEY)) {
// Do something
}
}
}

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 36
4.0 International License
Creating and registering listener

SharedPreferences.OnSharedPreferenceChangeListener listener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(
SharedPreferences prefs, String key) {
// Implement listener here
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 37
4.0 International License
You need a STRONG reference to the listener

● When registering the listener the preference manager does


not store a strong reference to the listener
● You must store a strong reference to the listener, or it will
be susceptible to garbage collection
● Keep a reference to the listener in the instance data of an
object that will exist as long as you need the listener

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 38
4.0 International License
10.2 SQLite Database

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 39
4.0 International License
Contents

● SQLite database 1. Data model


● Cursors 2. Subclass Open Helper
● Content Values 3. Query
● Implementing SQLite 4. Insert, Delete, Update, Count
● Backups 5. Instantiate Open Helper
6. Work with database

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 40
4.0 International License
SQLite
Database

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 41
4.0 International License
Using SQLite database
● Versatile and straightforward to implement
● Structured data that you need to store persistently
● Access, search, and change data frequently
● Primary storage for user or app data
● Cache and make available data fetched from the cloud
● Data can be represented as rows and columns
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 42
4.0 International License
Components of SQLite database

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 43
4.0 International License
SQLiteOpenHelper
SQLite database represented as an SQLiteDatabase object
all interactions with database through SQLiteOpenHelper
● Executes your requests
● Manages your database
● Separates data and interaction from app
● Keeps complex apps manageable
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 44
4.0 International License
Cursors

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 45
4.0 International License
Cursors
● Data type commonly used for results of queries
● Pointer into a row of structured data ...
● … think of it as an array of rows
● Cursor class provides methods for moving cursor and
getting data
● SQLiteDatabase always presents results as Cursor

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 46
4.0 International License
Cursor subclasses

● SQLiteCursor exposes results from a query on a


SQLiteDatabase

● MatrixCursor is a mutable cursor implementation backed


by an array of Objects that automatically expands internal
capacity as needed

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 47
4.0 International License
Cursor common operations
● getCount()—number of rows in cursor
● getColumnNames()—string array with column names
● getPosition()—current position of cursor
● getString(int column), getInt(int column), ...
● moveToFirst(), moveToNext(), ...
● close() releases all resources and invalidates cursor
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 48
4.0 International License
Processing Cursors
// Store results of query in a cursor
Cursor cursor = db.rawQuery(...);
try {
while (cursor.moveToNext()) {
// Do something with data
}
} finally {
cursor.close();
}

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 49
4.0 International License
Content Values

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 50
4.0 International License
ContentValues
● An instance of ContentValues
○ Represents one table row
○ Stores data as key-value pairs
○ Key is the name of the column
○ Value is the value for the field

● Used to pass row data between methods

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 51
4.0 International License
ContentValues

ContentValues values = new ContentValues();

// Inserts one row.


// Use a loop to insert multiple rows.
values.put(KEY_WORD, "Android");
values.put(KEY_DEFINITION, "Mobile operating system.");

db.insert(WORD_LIST_TABLE, null, values);

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 52
4.0 International License
Implementing
SQLite

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 53
4.0 International License
You always need to ...
1. Create data model
2. Subclass SQLiteOpenHelper
a. Create constants for tables
b. onCreate()—create SQLiteDatabase with tables
c. onUpgrade(), and optional methods
d. Implement query(), insert(), delete(), update(), count()
3. In MainActivity, create instance of SQLiteOpenHelper
4. Call methods of SQLiteOpenHelper to work with database
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 54
4.0 International License
Data Model

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 55
4.0 International License
Data model
● Class with getters and setters
● One "item" of data (for database, one record or one row)

public class WordItem {


private int mId;
private String mWord;
private String mDefinition;
...
}

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 56
4.0 International License
Subclass
SQLiteOpenHelper

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 57
4.0 International License
Subclass SQLiteOpenHelper

public class WordListOpenHelper extends SQLiteOpenHelper {

public WordListOpenHelper(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d(TAG, "Construct WordListOpenHelper");
}
}
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 58
4.0 International License
Declare constants for tables
private static final int DATABASE_VERSION = 1;
// Has to be 1 first time or app will crash.
private static final String DATABASE_NAME = "wordlist";
private static final String WORD_LIST_TABLE = "word_entries";

// Column names...
public static final String KEY_ID = "_id";
public static final String KEY_WORD = "word";

// ... and a string array of columns.


private static final String[] COLUMNS = {KEY_ID, KEY_WORD};
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 59
4.0 International License
Define query for creating database
● You need a query to create the database
● Customarily defined as a string constant

private static final String WORD_LIST_TABLE_CREATE =


"CREATE TABLE " + WORD_LIST_TABLE + " (" +
KEY_ID + " INTEGER PRIMARY KEY, " +
// will auto-increment if no value passed
KEY_WORD + " TEXT );";

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 60
4.0 International License
onCreate()

@Override
public void onCreate(SQLiteDatabase db) { // Creates new database
// Create the tables
db.execSQL(WORD_LIST_TABLE_CREATE);
// Add initial data
...
}

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 61
4.0 International License
onUpgrade()
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
// SAVE USER DATA FIRST!!!
Log.w(WordListOpenHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + WORD_LIST_TABLE);
onCreate(db);
}

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 62
4.0 International License
Optional methods

● onDowngrade()—default rejects downgrade


● onConfigure()—called before onCreate(). Only call methods
that configure the parameters of the database connection
● onOpen()

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 63
4.0 International License
Database
Operations

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 64
4.0 International License
Database operations
● query()
● insert()
● update()
● delete()

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 65
4.0 International License
Query
Method

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 66
4.0 International License
Executing queries

● implement query() method in open helper class


● query() can take and return any data type that UI needs
● Only support queries that your app needs
● Use database convenience methods for insert, delete, and
update

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 67
4.0 International License
Database methods for executing queries

● SQLiteDatabase.rawQuery()
Use when data is under your control and supplied only
by your app

● SQLiteDatabase.query()
Use for all other queries
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 68
4.0 International License
SQLiteDatabase.rawQuery() format

rawQuery(String sql, String[] selectionArgs)

● First parameter is SQLite query string


● Second parameter contains the arguments
● Only use if your data is supplied by app and under your full
control
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 69
4.0 International License
SQLiteDatabase.rawQuery() example

String query = "SELECT * FROM " + WORD_LIST_TABLE +


" ORDER BY " + KEY_WORD + " ASC " +
"LIMIT " + position + ",1";

cursor = mReadableDB.rawQuery(queryString, null);

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 70
4.0 International License
Insert, Delete,
Update, Count

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 71
4.0 International License
insert() format
long insert(String table, String nullColumnHack,
ContentValues values)

● First argument is the table name.


● Second argument is a String nullColumnHack.
○ Workaround that allows you to insert empty rows
○ Use null
● Third argument must be a ContentValues with values for the row
● Returns the id of the newly inserted item

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 72
4.0 International License
insert() example

newId = mWritableDB.insert(
WORD_LIST_TABLE,
null,
values);

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 73
4.0 International License
delete() format
int delete (String table,
String whereClause, String[] whereArgs)

● First argument is table name


● Second argument is WHERE clause
● Third argument are arguments to WHERE clause

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 74
4.0 International License
delete() example

deleted = mWritableDB.delete(
WORD_LIST_TABLE,
KEY_ID + " =? ",
new String[]{String.valueOf(id)});

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 75
4.0 International License
update() format
int update(String table, ContentValues values,
String whereClause, String[] whereArgs)

● First argument is table name


● Second argument must be ContentValues with new values for the row
● Third argument is WHERE clause
● Fourth argument are the arguments to the WHERE clause

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 76
4.0 International License
update() example

ContentValues values = new ContentValues();


values.put(KEY_WORD, word);

mNumberOfRowsUpdated = mWritableDB.update(
WORD_LIST_TABLE,
values, // new values to insert
KEY_ID + " = ?",
new String[]{String.valueOf(id)});

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 77
4.0 International License
Always!

● Always put database operations in try-catch blocks

● Always validate user input and SQL queries

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 78
4.0 International License
Instantiate
OpenHelper

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 79
4.0 International License
Create an instance of your OpenHelper

● In MainActivity onCreate()

mDB = new WordListOpenHelper(this);

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 80
4.0 International License
Architecture with SQLite database

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 81
4.0 International License
11.1 Content Providers
Share data with other apps

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 82
4.0 International License
Contents

● What is a ContentProvider
● App with Content Provider Architecture
● Implementation
○ Contract
○ ContentProvider
○ Manifest Permissions
○ Content Resolver

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 83
4.0 International License
What is a
Content
Provider

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 84
4.0 International License
What is a Content Provider?

● A content provider is a component fetches data that the


app requests from a repository
● The app doesn't need to know where or how the data is
stored, formatted, or accessed

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 85
4.0 International License
What is a Content Resolver?
● A content resolver is a component that your app uses to
send requests to a content provider

● Requests consist of a content URI and an SQL-like query


● The ContentResolver object provides query(), insert(),
update(), and delete() methods

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 86
4.0 International License
How do they work together?
Activity / Adapter 1. Activity/Adapter uses
ContentResolver to query
ContentResolver
ContentProvider
2. ContentProvider gets data
ContentProvider
3. ContentResolver returns data as
Cursor
Data 4. Activity/Adapter uses data
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 87
4.0 International License
What is it good for?

● Securely make data available to other apps


● Manage access permissions to app data

● Store data or develop backend independently from UI


● Standardized way of accessing data
● Required to work with CursorLoaders

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 88
4.0 International License
Many apps can use one content provider
App that manages hat App that sells red hats
inventory Content Resolver
Content Resolver "Get red hats"

Hat Store Content App that sells fancy hats


Provider
Content Resolver
"Get fancy hats"

Hat inventory data

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 89
4.0 International License
App with
Content
Provider

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 90
4.0 International License
Components of a Content Provider App

Let's look at each of these...

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 91
4.0 International License
Data Repository

● Data, commonly in SQLite


Database but can be any
backend
● OpenHelper if you use SQLite
database

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 92
4.0 International License
Contract
Public class that exposes information about the content
provider to other apps

Contract specifies
● URIs to query data
● Table structure of data
● MIME type of returned data
● Constants
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 93
4.0 International License
Content Provider

● Public secure interface


● Permissions control access
● Subclass of ContentProvider
● query(), insert(), delete(),
update() API

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 94
4.0 International License
Content Resolver

● Send requests to content


provider and return response

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 95
4.0 International License
Permissions

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 96
4.0 International License
Permissions

You have already used permissions in some of your apps:


● Permission to connect to the Internet
● Permission to use data from a Content Provider

A basic Android application has no permissions so that it


cannot do anything that adversely impacts the user
experience or data on the device
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 97
4.0 International License
When to use permissions
App must get permission to do anything that
● Uses data or resources that the app did not create
● Uses network, hardware, features that do not belong to it
● Affects the behavior of the device
● Affects the behaviour of other apps

If it isn't yours, get permission!


This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 98
4.0 International License
How apps declare permissions they need
List permissions in the manifest
● <uses-permission>

<manifest ...>
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 99
4.0 International License
Example permissions
ACCESS_COARSE_LOCATION RECEIVE_SMS

ACCESS_FINE_LOCATION CAMERA

ACCESS_NETWORK_STATE RECORD_AUDIO

ACCESS_WIFI_STATE MODIFY_AUDIO_SETTINGS

GET_ACCOUNTS ADD_VOICEMAIL

See more at
https://developer.android.com/reference/android/Manifest.permission.html

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 100
4.0 International License
More examples
● BLUETOOTH
Connect to paired bluetooth devices.
● BODY_SENSORS
Access data from sensors that the user uses to measure what is happening
inside user's body, such as heart rate.
● USE_FINGERPRINT
Use fingerprint hardware.

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 101
4.0 International License
Normal and dangerous permissions
● Normal permissions do not directly risk the user's privacy
Example: Set the time zone
Android automatically grants normal permissions.

● Dangerous permissions give access to user's private data


Example: Read the user's contacts
Android asks user to explicitly grant dangerous permissions

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 102
4.0 International License
How users grant permission

For apps created before Marshmallow


● Users grant permission before
installing

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 103
4.0 International License
How Users grant permission

Marshmallow onwards
● Installation doesn't ask user to give
permissions
● App must get runtime permission

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 104
4.0 International License
How users revoke permission
● Before Marshmallow
Uninstall app!

● Marshmallow onwards
Revoke individual permissions
Settings > apps > permissions

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 105
4.0 International License
Differences in permission models
Before Marshmallow
● If app is running, it can assume that user granted
permissions during installation
After Marshmallow
● App needs to get permission at runtime
● Must check if it still has permission every time
● User can revoke permissions at any time
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 106
4.0 International License
Framework versus support library

● Android framework 6.0 (API level 23) + provides


permission methods
● Better to use Android Support Library

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 107
4.0 International License
Support library permission methods

Support library permission methods check Android version


● If runtime permissions model is supported,
requests the appropriate permission from the user
● Otherwise, checks if the permission was granted at
install time

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 108
4.0 International License
Best practices for permissions
● Ask for the least amount of
permissions that you need
● Don't overwhelm the user
● Consider using an Intent instead—
For example, send an Intent to use
the camera

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 109
4.0 International License
Learn more about permissions
● List of permissions defined in Android:
developer.android.com/reference/android/Manifest.permission.html

● Permissions in Android:
developer.android.com/guide/topics/security/permissions.html

● Best practices:
developer.android.com/training/permissions/best-practices.html

● Blog entry about runtime permissions:


android-developers.blogspot.com/2015/08/ building-better-apps-with-
runtime.html
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 110
4.0 International License
App Performance

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 111
4.0 International License
What is app performance?

● Speed
● Responsiveness
● Smoothness
● Consistency
● Resource-efficiency

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 112
4.0 International License
The Main thread must be fast
● Hardware updates screen every 16 milliseconds
● UI thread has 16 ms to do all its work
● If it takes too long, app stutters or hangs
WAI
T

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 113
4.0 International License
Improving performance

● Be systematic
○ Gather information
○ Gain insight
○ Take action

● Iterate
● Use tools
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 114
4.0 International License
Profile GPU Rendering tool

1. On your mobile device, go to Settings > Developer Options


2. In Monitoring section, select Profile GPU Rendering.
3. In Profile GPU Rendering popup, choose On screen as bars
4. Go to the app that you want to profile
5. See the bars at the bottom of the screen

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 115
4.0 International License
Interpret the bars

● One bar represents one screen rendered


● If a bar goes above the green line, it took > 16 ms to render
● Many bars above the line, or heavy spiking indicate
problems
● User will see stuttering or inconsistent responsiveness
● Analyze the bar and fix problems
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 116
4.0 International License
Android Studio > Android Monitor

Memory CPU GPU Network

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 117
4.0 International License
Don't make users wait
● Load data in background
● Pre-fetch data
● Move work off the UI thread
● Optimize UI—draw less and faster
● Eliminate overdraw and optimize view hierarchy

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 118
4.0 International License
Don't waste user's resources
● WiFi and mobile radio use lots of battery
○ Batch requests
○ Schedule to run when phone is being charged

● Large images consume lots of memory


○ Use smallest images possible
○ Always use compressed image formats. Use WebP when possible

● Getting and putting data on the internet uses up data plans


○ When possible download data when on WiFi

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 119
4.0 International License
Security Best Practices

This
Thiswork
workisislicensed
licensedunder
undera aCreative
Creative
Android Developer Fundamentals Storing Data Commons
CommonsAttribution-NonCommercial
Attribution-NonCommercial 120
4.0
4.0International
InternationalLicense
License
Android's got you covered (mostly)

● Android has built-in security features


● Significantly reduces the frequency and impact of
application security issues
● You can typically build apps with default system and file
permissions

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 121
4.0 International License
Your app's responsibility

● Keep user's private data safe


● Do not leak secret things
● Treat user's data with integrity
● Keep your own app and data safe

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 122
4.0 International License
Handling user data
● Minimize access to sensitive or personal user data
● Do not store or transmit user data if possible
● But if you must, consider using a hash or non-reversible
form of the data
For example, use hash of an email address as a primary
key, so you do not store or transmit the email address

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 123
4.0 International License
Comply with Personal Data Policies

If your app accesses personal information like passwords or


usernames, it might need a privacy policy explaining how it
uses and stores user data

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 124
4.0 International License
Be careful what you log

● Android logs are a shared resource, and are available to


an application with the READ_LOGS permission
● Inappropriate logging of user information could leak user
data to other applications

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 125
4.0 International License
Encrypt sensitive data
● Encrypt local files that contain sensitive data
● Store the key so it is not accessible by the app
For example, use a KeyStore protected with a user password
stored off the device

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 126
4.0 International License
External storage
Do not store sensitive information on external storage
● Files created on external storage, such as SD Cards, are
globally readable and writable
● External storage can be removed by the user
● External storage can be modified by any application
● Validate input on data from external storage
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 127
4.0 International License
IP Networking
● Networking on Android is similar to other Linux environments
● Minimize network transactions that transmit private data
● Use HTTPS over HTTP wherever it's supported on the server
● Mobile devices often connect on networks that are not
secured, such as public Wi-Fi hotspots
● You can implement authenticated, encrypted socket-level
communication using the SSLSocket class
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 128
4.0 International License
Learn more about security in Android
● Security tips:
developer.android.com/training/articles/security-tips.html

● Saving files:
developer.android.com/training/basics/data-storage/files.html

● Sharing files:
developer.android.com/training/secure-file-sharing/index.html

● Full disk encryption:


source.android.com/security/encryption/
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 129
4.0 International License
14.1 Firebase and
Monetization

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 130
4.0 International License
Contents
● Firebase
● Make money from your app

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 131
4.0 International License
Firebase

This
Thiswork
workisislicensed
licensedunder
undera aCreative
Creative
Android Developer Fundamentals Storing Data Commons
CommonsAttribution-NonCommercial
Attribution-NonCommercial 132
4.0
4.0International
InternationalLicense
License
What is Firebase?

Firebase is a platform that provides tools to help you


● develop your app
● grow your user base
● earn money from your app

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 133
4.0 International License
Tools for all platforms
Firebase features
are available for
● Android
● iOS
● Web

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 134
4.0 International License
Firebase console

Firebase Console
is a web front end
for managing your
Firebase projects

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 135
4.0 International License
Using Firebase
1. Connect your app to your Firebase project
2. Enable Firebase features in the console
3. Add code to your app (where needed)

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 136
4.0 International License
Get started
with Firebase

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 137
4.0 International License
Firebase console
firebase.google.com

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 138
4.0 International License
Create new project

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 139
4.0 International License
Connect your app to the Firebase
project
Add your Android app to
your Firebase project

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 140
4.0 International License
Firebase config file
● Firebase creates a config file for your app
● It contains all the information
your app needs to integrate
with the Firebase project
● google-services.json file

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 141
4.0 International License
Add config file to your project
● Open your app in Android Studio
● Drag and drop google-
services.json to the app module

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 142
4.0 International License
Update code dependencies in your app
● The Google services plugin for Gradle in your project
loads google-services.json
● Modify your build.gradle files to use the plugin

Follow the instructions in


the Firebase wizard to
update code dependencies

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 143
4.0 International License
Update build.gradle
● Project-level build.gradle: Get exact
buildscript { number from
dependencies { Firebase wizard
// Add this line
classpath 'com.google.gms:google-services:n.n.n'

● App-level build.gradle…
// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 144
4.0 International License
Firebase
Analytics

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 145
4.0 International License
Firebase Analytics
● Unlimited free reporting
● Audience segmentation
Define custom audiences based
on device data, custom events,
or user properties

firebase.google.com/docs/analytics/
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 146
4.0 International License
Firebase Analytics: default reports
Get reports without
adding code
● geographic
● demographic
● engagement
● revenue
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 147
4.0 International License
Firebase Analytics: custom reports

Add code to log events in your app to get more reports

● Predefined events such as:


user adds an item to their cart
● Custom events such as:
user achieves a level in a game

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 148
4.0 International License
In your app
● In your app project, add dependency in app/build.gradle:
compile 'com.google.firebase:firebase-analytics:n.n.n'

● No need to write code for default reports


● Write code for custom events if you want them

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 149
4.0 International License
Firebase
Notifications

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 150
4.0 International License
Firebase notifications

In the Notifications lesson, you


learned how your app can send
notifications to the user.
The Firebase Console lets you send
notifications to your users.

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 151
4.0 International License
Firebase Cloud Messaging sends the msg

● You write notification


messages in the
Firebase Console

● Firebase Cloud Messaging delivers the


notifications to the target audience

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 152
4.0 International License
Send message
Write your
message in the
Firebase console

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 153
4.0 International License
Firebase
Database

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 154
4.0 International License
Storing and sharing data
You have already learned your app can
● save data in an SQLite database on the device
● use a ContentProvider to share data with other apps
How do you enable different users using different devices, to
share and update data?
● Use Firebase Database
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 155
4.0 International License
Firebase Realtime database
Store and sync data with the
Firebase cloud database
Data is synced across all clients,
and remains available when your
app goes offline
firebase.google.com/docs/database/

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 156
4.0 International License
Connected apps share data

● Firebase Realtime Database is hosted


in the cloud
● Data is stored as JSON
● Data is synchronized in realtime to
every connected client.

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 157
4.0 International License
View and edit data in Firebase Console

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 158
4.0 International License
In your app
● In your app project, add dependency in app/build.gradle:
compile 'com.google.firebase:firebase-database:n.n.n'

● In your app source code, put data in the database,


and get data from the database (API Reference)
Example:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference(path);
myRef.setValue("New value");
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 159
4.0 International License
Firebase Cloud
Test Lab

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 160
4.0 International License
Firebase Cloud Test Lab
Test your app on real
devices in a Google
data center

firebase.google.com/docs/test-lab/

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 161
4.0 International License
Run your tests in the console

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 162
4.0 International License
Choose the devices to test your app on
Set test targets:
● Devices
● API levels
● Orientations
● Locales

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 163
4.0 International License
Get test results

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 164
4.0 International License
And more...

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 165
4.0 International License
More Firebase tools

● Firebase storage —Store images, audio, video, or other


user-generated content.
● Store terabytes of data!
● Authentication—Enable users to sign in to your app
● Get crash reports

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 166
4.0 International License
… and even more!

● App indexing -- enable Google search to include results


from your app
● Dynamic links -- deep links into an app that work whether
or not users have installed the app yet.
● App Invites -- allow users to invite others to your app
● AdMob -- we'll talk about that next
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 167
4.0 International License
Learn more about Firebase

● Firebase
● Firebase Testing Lab
● Getting started with Firebase for Android
● Firebase in a weekend online course
www.udacity.com/course/ud0352

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 168
4.0 International License
Learn more contd...
● Firebase console
console.firebase.google.com/

● Firebase developer documentation


firebase.google.com/docs/

● Firebase codelab Highly recommended!

codelabs.developers.google.com/codelabs/firebase-android

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 169
4.0 International License
Video Resources
● Introducing Firebase:
https://www.youtube.com/watch?v=O17OWyx08Cg

● Playlist of intro videos to Firebase features


http://goo.gl/qo4Frq

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 170
4.0 International License
Make Money
from your apps

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 171
4.0 International License
Ways to monetize apps in Google Play

● Premium model—users pay to download app


● Freemium model
○ downloading app is free
○ users pay for upgrades or in-app purchases
● Subscriptions—users pay recurring fee for app
● Ads—app is free but displays ads

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 172
4.0 International License
Premium apps
● Charge users to download your app
● Set prices in the Developer Console
● Good model for apps that address
a market niche
● BUT users often won't download an
app if they have to pay for it

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 173
4.0 International License
Freemium Apps
Offer a free download with
● limited features
● full features for a limited time
Let users upgrade to full, unlimited
app with an in-app purchase

developer.android.com/google/play/billing/index.html
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 174
4.0 International License
In-app purchases
Use In-app purchases to sell extra features
● New features
● Additional content
● Skins
● New levels, powers, attacks...

developer.android.com/distribute/monetize/freemium.html

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 175
4.0 International License
Subscriptions

● Subscriptions let users use apps


or features for a recurring monthly
or annual fee
● Offer a free trial subscription to
allow users to explore your app

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 176
4.0 International License
Run ads using AdMob

● Runs ads in your app to earn revenue


● 650,000 + apps use AdMob
● $1 billion+ paid to developers in the
last 2 years

developer.android.com/distribute/monetize/ads.html
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 177
4.0 International License
Sign up for AdMob in Firebase Console

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 178
4.0 International License
Learn more about monetizing your app

● Earn
● Monetizing with Ads
● In-App Purchases
● In-App Billing

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 179
4.0 International License
What's next?
This course does not have a practical for Firebase and AdMob
Get hands on experience by taking these online courses:
● Firebase in a Weekend online course
www.udacity.com/course/ud0352

● Firebase codelab
codelabs.developers.google.com/codelabs/firebase-android

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 180
4.0 International License
15.1 Prepare and Publish
Your App!

This
Thiswork
workisislicensed
licensedunder
undera aCreative
Creative
Android Developer Fundamentals Storing Data Commons
CommonsAttribution-NonCommercial
Attribution-NonCommercial 181
4.0
4.0International
InternationalLicense
License
Contents

● Prepare your app for release


● Publish!

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 182
4.0 International License
Steps for publishing your app

● Prepare app for release


● Generate signed APK
● Upload to Google Play
● Run alpha and beta tests
● Publish to the world

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 183
4.0 International License
What is an APK?
● Android Application Package file → .apk file
● It's like the executable
● Each Android application is compiled and packaged in a
single file that includes all the app's code, resources,
assets, and manifest file
● You need an APK to publish on Google Play

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 184
4.0 International License
Share your app during development

Ways to distribute your app


● Zip it up
● Share the source code
● Publish to github
● Make an APK

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 185
4.0 International License
Share with friends and family

Use alpha and beta tests


to share your app with
friends and family

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 186
4.0 International License
Share your production app
Publish on Google Play
● Make an APK
● Upload to Google Play
● Run alpha and beta tests
● Publish!

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 187
4.0 International License
Prepare Your
App for Release

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 188
4.0 International License
Prepare your app for release
● Test, test, test!
● Add an icon
● Make sure your app has the correct filters
● Choose an Application ID
● Specify API levels targets
● Clean up your app
● Generate a signed APK for release
developer.android.com/studio/publish/preparing.html
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 189
4.0 International License
Test, test, test!

First, make sure your app works correctly...


● Test your app on different devices and screen size
● Test your app on older devices
Use support library for backwards compatibility
● Test, test, test!

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 190
4.0 International License
Test on devices in a data center

Test on real devices in a


data center using the
Firebase Cloud Test Lab

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 191
4.0 International License
Add launcher app icon

The launcher icon appears


in
● Google Play

On the device
● Home screen
● Manage Applications
● My Downloads This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 192
4.0 International License
Google Play filters search results

Google Play search results only show apps that are


compatible with the user's device.
If an app uses a camera, Google Play only shows the apps to
devices that have a camera.

developer.android.com/google/play/filters.html

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 193
4.0 International License
Types of filters
● Hardware features
● API level
● Manifest settings such as
○ <supports-screens>
○ <uses-feature>
● Countries (selected during APK upload)
developer.android.com/google/play/filters.html

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 194
4.0 International License
Choose your Application ID

● Application ID defines your application's identity


● Must be unique across all apps from everyone!
● If you change App ID and re-publish
○ The app becomes a different application
○ Users of the previous app cannot update to the new app

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 195
4.0 International License
Application ID versus package name
● Initial Application ID is set to the package
● You can change Application ID in build.gradle
independently of package name

tools.android.com/tech-docs/new-build-system/applicationid-vs-packagename

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 196
4.0 International License
Specify Application ID in build.gradle
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "android.mydomain.com.myappid"
...
}
...
Initial Application ID is
}
same as package in
Android manifest
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 197
4.0 International License
Set min and target API level

● minSdkVersion — minimum version of the Android


platform that the app runs on

● targetSdkVersion — API level that the app is designed for

API levels: developer.android.com/guide/topics/manifest/uses-sdk-


element.html#ApiLevels
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 198
4.0 International License
Android versions
Codename Version Release Date API Level

Honeycomb 3.0 - 3.2.6 Feb 2011 11 - 13

Ice Cream 4.0 - 4.0.4 Oct 2011 14 - 15


Sandwich

Jelly Bean 4.1 - 4.3.1 July 2012 16 - 18

KitKat 4.4 - 4.4.4 Oct 2013 19 - 20

Lollipop 5.0 - 5.1.1 Nov 2014 21 - 22

Marshmallow 6.0 - 6.0.1 Oct 2015 23

Nougat 7.0 Sept 2016 24


There were earlier versions before Feb 2011.
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 199
4.0 International License
Clean up your app

● Remove logging statements


● Disable debugging
● Clean up your project directories
● Update URLs for servers and services
● Reduce APK size

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 200
4.0 International License
Why does APK size matter?

The size of your APK affects:


● how fast your app loads
● how much memory it uses
● how much power it consumes

developer.android.com/topic/performance/reduce-apk-size.html

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 201
4.0 International License
Why reduce APK size?

Users might abandon "large" apps, particularly:


● in areas with unreliable 2G and 3G networks
● on devices that work on pay-by-the-byte plans

developer.android.com/topic/performance/reduce-apk-size.html

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 202
4.0 International License
Reducing APK size
● Remove unused resources
● Reuse resources
● Minimize resource use from libraries
● Reduce native and Java code
● Reduce space needs for images
developer.android.com/topic/performance/reduce-apk-size.html

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 203
4.0 International License
Reduce image sizes
● Reduce animation frames
● Use Drawable objects
● Crunch PNG files
● Use lowest quality and size JPEG files that look good
● Use WebP File Format
● Use vector graphics
developer.android.com/topic/performance/reduce-apk-size.html

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 204
4.0 International License
Clean up project folders

● Clean up project folders and files


● Stray or orphaned files can prevent your application from
compiling and cause it to behave unpredictably

developer.android.com/studio/projects/index.html#ApplicationProjects

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 205
4.0 International License
Clean up jni, lib, and src folders

● src: source files for your app (.java and .aidl files)
NO jar files
● lib: third-party or private library files, including prebuilt
shared and static libraries (such as .so files)
● jni: source files associated with the Android NDK, such as
.c, .cpp, .h, and .mk files

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 206
4.0 International License
Clean up assets, resources, and tests

● Remove unused private or proprietary data files


For example, delete unused drawable files, layout files, and
values files from res/ folder
● Review the assets and res/raw directories for raw asset
files and static files to update or remove
● Remove unused test directories

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 207
4.0 International License
Generate APK

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 208
4.0 International License
Generate signed APK for release

● Android apps must be digitally signed before users can


install them
● Use Android Studio to generate and sign your APK

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 209
4.0 International License
Digital certificates
A public-key certificate contains:
● the public key of a public/private key pair,
● other metadata identifying the owner of the key
such as name and location
The owner of the certificate holds the private key.

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 210
4.0 International License
Public and private key for app
● When Android Studio signs the app, it creates the public
certificate and the private key.
● It attaches the public certificate to the APK.
● You must securely store the private key in a keystore

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 211
4.0 International License
Why you need to sign your app
The public-key certificate serves as as a "fingerprint" that
uniquely associates the APK to you and your corresponding
private key.
This helps Android ensure that any future updates to your
APK are authentic and come from the original author.

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 212
4.0 International License
Publish to Google Play

This
Thiswork
workisislicensed
licensedunder
undera aCreative
Creative
Android Developer Fundamentals Storing Data Commons
CommonsAttribution-NonCommercial
Attribution-NonCommercial 213
4.0
4.0International
InternationalLicense
License
Publish your app!
Publish your Android apps on
Google Play
Users can
● search
● download
● review

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 214
4.0 International License
Users can review!

● Make sure your app is ready


before publishing to the world!
● People will give you bad reviews if
they are unhappy with it
● The more they like it, the more
they will want more features!
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 215
4.0 International License
Steps to publish
● Create an account on Google Play developer console
● Create an entry for your app
● Add the required assets and information
● Run alpha and beta tests
● Run pre-launch reports
● Publish to the world!
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 216
4.0 International License
Google Play
Developer
Console

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 217
4.0 International License
Sign up for Google Play

1. Go to play.google.com/apps/publish/
2. Accept agreement
3. Pay the registration fee
4. Enter your details

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 218
4.0 International License
Google Play Developer Console

play.google.com/apps/publish/
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 219
4.0 International License
Enter your details

● Name
● Address
● Website
● Phone
● Email
preferences
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 220
4.0 International License
You're in!

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 221
4.0 International License
Add an application

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 222
4.0 International License
Add an application
● Upload APK
or
● Prepare Store Listing

To run alpha and beta tests,


upload the APK
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 223
4.0 International License
Alpha and Beta
Tests

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 224
4.0 International License
Run alpha and beta tests
Run alpha and beta tests in Google Play developer console

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 225
4.0 International License
Choose file to upload

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 226
4.0 International License
Why run alpha and beta tests?

● Test your app before public release to help find and fix
any technical or user experience issues
● Get the bugs out before you release your app to the world!
● Feedback from your test users does not affect your app’s
public rating

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 227
4.0 International License
Share with testers before publishing
● Alpha test during development
Use alpha tests for early experimental versions of your app
that might contain incomplete or unstable functionality
● Beta test with limited number of real users
Use beta tests for apps that should be complete and stable

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 228
4.0 International License
Alpha and beta tests

During alpha and beta tests


● Your app is not listed in Google Play
● Testers must have a link to get it
● Testers cannot give reviews in Google Play

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 229
4.0 International License
Closed beta
People have to be invited to join closed alpha and beta tests
● Closed beta using email addresses
○ use lists of individual email addresses which you can add
individually or upload as a .csv file

● Closed beta with Google+ community or Google Group


You can move closed betas to an open beta while
maintaining your existing testers
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 230
4.0 International License
Open beta

● Anyone with the link can join


● Can scale to a larger group
● You can limit max number of testers

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 231
4.0 International License
Get feedback
● Closed tests:
Provide a way for users to give feedback on your app, such
as by email, website, or a message forum
● Open tests:
Your testers can give private feedback in Google Play Store
support.google.com/googleplay/android-developer/answer/
138230#browse_reviews
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 232
4.0 International License
Get private feedback for open betas

● For open tests (alpha or beta) program, you can see and
reply to user feedback in the Developer Console
● Alpha and beta feedback from users is only visible to you
and cannot be seen in the Google Play store

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 233
4.0 International License
Pre-launch
Report Test before you publish

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 234
4.0 International License
Opt in for pre-launch reporting
● Pre-launch reports identify crashes, display issues, and
security vulnerabilities
● During pre-launch check, test devices automatically
launch and crawl your app for several minutes
● The crawl performs basic actions every few seconds on
your app, such as typing, tapping, and swiping
support.google.com/googleplay/android-developer/answer/7002270
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 235
4.0 International License
Example pre-launch report

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 236
4.0 International License
Example pre-launch report

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 237
4.0 International License
Running pre-launch reports

● Opt-in to pre-launch reports in the console


● Then when you upload or
publish an alpha or beta APK,
the pre-launch test runs
automatically

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 238
4.0 International License
Criteria
for
Publishing

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 239
4.0 International License
Only publish high quality apps
Your app must meet core app quality requirements
● Visual design and user interaction
● Functionality
● Performance and stability
Android users expect high-quality apps!
developer.android.com/distribute/essentials/quality/core.html

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 240
4.0 International License
Comply with Google Play policies

Google Play policies ensure that


all apps on Google Play provide a
safe experience for everyone

play.google.com/about/developer-content-policy/
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 241
4.0 International License
Restricted Content
● Sexually Explicit Content
● Child Endangerment
● Violence
● Bullying & Harassment
● Hate Speech
● Sensitive Events
● Gambling
● Illegal Activities
play.google.com/about/restricted-content
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 242
4.0 International License
Publish to the
world!

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 243
4.0 International License
Upload your APK to Production

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 244
4.0 International License
Check what's missing
● add a high-res icon
● add a feature graphic
● add 2 non-Android TV screenshots
● select a category
Google Play tells you
● select a content rating what is missing
● target at least one country
● enter a privacy policy URL
● make your app free or set a price for it
● declare if your app contains ads
● add a required content rating This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 245
4.0 International License
Google checks your app

● Automatic and manual checking


● Your app can be rejected for violating any requirement
● If you get rejected, fix the problem and try again

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 246
4.0 International License
Learn more

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 247
4.0 International License
Learn more about prepping your app
● Review the launch checklist
● Core app quality checklist
developer.android.com/distribute/essentials/quality/core.html

● Handling user data


play.google.com/about/privacy-security/user-data/

● Design for tablets and handsets


developer.android.com/guide/practices/tablets-and-handsets.html

● Min, max, and target API levels


developer.android.com/guide/topics/manifest/uses-sdk-element.html
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 248
4.0 International License
Learn more about prepping your app
● Preparing for release
https://developer.android.com/studio/publish/preparing.html

● Google Play filters


developer.android.com/google/play/filters.html

● Reduce app size


developer.android.com/topic/performance/reduce-apk-size.html

● Sign your app


developer.android.com/studio/publish/app-signing.html
This work is licensed under a Creative
Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 249
4.0 International License
Learn more about publishing your app

Google Play Developer Console:


● Go to the console:
play.google.com/apps/publish/

● Dev guide:
developer.android.com/distribute/googleplay/developer-console.html

● Help center:
support.google.com/googleplay/android-developer/#topic=3450769

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 250
4.0 International License
Learn more about publishing your app
● Get started publishing
developer.android.com/distribute/googleplay/start.html

● Alpha and Beta testing


Dev guide:
developer.android.com/distribute/engage/beta.html
Help center:
support.google.com/googleplay/android-developer/answer/3131213

This work is licensed under a Creative


Android Developer Fundamentals Storing Data Commons Attribution-NonCommercial 251
4.0 International License

You might also like