Download Lecture 10: Shared Preferences, Bundles, Permissions, Security

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Shared Preferences,
Bundles, Permissions,
Security
15 January 2017
Lecture 10
15 Jan 2017
SE 435: Development in the Android Environment
1
Topics for Today
• Pending Intents
• Persisting State
– Shared Preferences
– Application Bundle
• Permissions and Security
– Permission Types
– Defining and Using Permissions
– Checking Permissions
• Source: developer.android.com
15 Jan 2017
SE 435: Development in the Android Environment
2
Pending Intents
1.App1 wants to do something later, but may not be active then
– Ex. Do a file sync in fifteen minutes
– Ex. Put a notification for the user to do something in 24 hours
2.App1 creates a pending intent (what it wants to do)
– Should include target (class), action, data, extras, etc.
3.App1 sends the pending intent to AlarmManager
– Pending intent can be sent as an extra in a regular intent
– Sends AlarmManager the time period to wake up and
4.At (around) the correct time, AlarmManager “sends” the pending
intent, executing what App1 wanted
– The intent is treated as if it came from App1
15 Jan 2017
SE 435: Development in the Android Environment
3
Pending Intent Details
public static PendingIntent getActivity
(Context context, int requestCode, Intent
intent, int flags)
• Overloads to allow follow-up, bundles, etc.
• Flags: FLAG_CANCEL_CURRENT,
FLAG_NO_CREATE, FLAG_ONE_SHOT,
FLAG_UPDATE_CURRENT
15 Jan 2017
SE 435: Development in the Android Environment
4
Pending Intents
• Pending intent should specify who the target of the action
is (explicit)
– Security!
• Pending intent can be retrieved by creator
– Search by action, data, type, class (target), category
– Can be modified or canceled
• Android stores the pending intent and lets the recipient
use it later
15 Jan 2017
SE 435: Development in the Android Environment
5
So Far
• Pending Intents
• Persisting State
– Shared Preferences
– Application Bundle
• Permissions and Security
– Permission Types
– Defining and Using Permissions
– Checking Permissions
15 Jan 2017
SE 435: Development in the Android Environment
6
Shared Preferences
• Storage of key-value pairs for the application
– Atomic types: string, string[], int, long, boolean, float
– Meant to keep information about what the user set between runs of
the activity
– Preferences are persisted in a file in the app’s internal directory
– Automatically stored between runs of the application
• Implementation Options
–
–
–
–
–
–
Can create activity specific “preferences” (not shared)
Can create multiple shared preferences files with different names
Can access the default shared preferences file for the application
Shared preferences are available in all activities
Can create a preferences activity to let the user graphically set them
Can allow other apps to read and write the shared preferences file
• Creates a world readable or writable preferences file
• Deprecated as of API 17 (security)
15 Jan 2017
SE 435: Development in the Android Environment
7
Non-Shared Preferences
Saving
Reading
//String SP = “SP”;
// put 5000 in the port number
if we don't already have a
favorite port
SharedPreferences sp =
getPreferences(
MODE_PRIVATE);
// save port and IP for later
SharedPreferences sp =
getPreferences(
MODE_PRIVATE);
// add it
Editor ed = sp.edit();
int port = sp.getInt(SP_PORT,
5000);
ed.putInt(SP_PORT,
Integer.parseInt(
etPort.getText().toString()));
EditText etPort = (EditText)
findViewById(
R.id.etServerPort);
ed.commit();
etPort.setText(String.valueOf(
port));
15 Jan 2017
SE 435: Development in the Android Environment
8
Named Shared Preferences
Saving
Reading
String SP = “SP”;
// put 5000 in the port number
if we don't already have a
favorite port
SharedPreferences sp =
getSharedPreferences(SP,
MODE_PRIVATE);
// save port and IP for later
SharedPreferences sp =
getSharedPreferences(SP,
MODE_PRIVATE);
// add it
Editor ed = sp.edit();
int port = sp.getInt(SP_PORT,
5000);
ed.putInt(SP_PORT,
Integer.parseInt(
etPort.getText().toString()));
EditText etPort = (EditText)
findViewById(
R.id.etServerPort);
ed.commit();
etPort.setText(String.valueOf(
port));
15 Jan 2017
SE 435: Development in the Android Environment
9
Default Shared Preferences
static final String SHOW_IMAGE_PREF =
"SHOW_IMAGE_PREF";
SharedPreferences sp =
PreferenceManager.
getDefaultSharedPreferences(
getApplicationContext());
boolean showImage =
sp.getBoolean(SHOW_IMAGE_PREF, false);
15 Jan 2017
SE 435: Development in the Android Environment
10
Preferences Activity/Fragment
• Centralize settings in one screen
– Define parameters to set which are automatically saved in the
SharedPreferences for the application
• Built of Preference objects:
– Checkbox
– List (supported atomic types)
– EditText (string)
– Custom (inherit from Preference)
– Can send an intent
• Use categories to separate them
• In older versions, use a PreferencesActivity, in newer
ones, host a PreferencesFragment
– Can have nested preferences screens
15 Jan 2017
SE 435: Development in the Android Environment
11
Preferences Activity Example
15 Jan 2017
SE 435: Development in the Android Environment
12
So Far
• Pending Intents
• Persisting State
– Shared Preferences
– Application Bundle
• Permissions and Security
– Permission Types
– Defining and Using Permissions
– Checking Permissions
15 Jan 2017
SE 435: Development in the Android Environment
13
Bundles: Save and Restore
void onSaveInstanceState (Bundle outState)
• Called when the activity is hidden, before or after
onPause()
– Always before onStop()
• Might be skipped if the activity is closing for good or not
killed
– Ex. It ran finish() or returned a result
– Ex. It opened an activity on top, but hasn’t been stopped yet
• Default implementation saves state of all user-modifiable
Views
• Override to do your own things
– Ex. Save TextViews, image states, layout
– Ex. Save drafts, do autosave
15 Jan 2017
SE 435: Development in the Android Environment
14
Bundles: Save and Restore
void onCreate (Bundle savedInstanceState)
• Restore when activity is created
• Gets outState from, restores based on it
• Receives null if activity isn’t restored
– First time opened
– Activity fully closed last time
void onRestoreInstanceState (Bundle
savedInstanceState)
• Restore after the activity has laid itself out
• Called after onStart()
Bundle is given to both of them
15 Jan 2017
SE 435: Development in the Android Environment
15
Persisting Settings and Data
Shared Preferences
Bundle
Goal: Store user defined
preferences for the app
Goal: Store activity state
between open/close
• Shared between activities
• App-wide effects
• Set programmatically or
via Preferences Activity
or Fragment
• Stored in a file in the
app’s internal storage
• Activity specific
• Activity given a chance to
save itself before close
• Activity given a chance to
restore itself onCreate()
15 Jan 2017
SE 435: Development in the Android Environment
16
So Far
• Pending Intents
• Persisting State
– Shared Preferences
– Application Bundle
• Permissions and Security
– Permission Types
– Defining and Using Permissions
– Checking Permissions
15 Jan 2017
SE 435: Development in the Android Environment
17
Security Background
• Android uses a process-centric security model:
– no application, by default, has permission to perform any operations
that would adversely impact other applications, the operating system,
or the user
– Each app has its own user ID
• Security is process based, so Dalvik and native code are the
same
– Native C code is also sandboxed
• Apps must be signed by a private key held by the developer
– Doesn’t need to be issued by a Certificate Authority, self signed is ok
– Used to identify the developer
– Apps signed with same private key can share the same user ID
15 Jan 2017
SE 435: Development in the Android Environment
18
Defining a Permission
• OS remembers which app defined it first
– Signature permissions can only be used by an app signed by the
same developer key as the definer
• App which defines the permission should request it as
well
– Newer versions don’t require
•
15 Jan 2017
SE 435: Development in the Android Environment
19
Predefined Permissions
• Android and system apps
have pre-defined
permissions
• Web Documentation:
– 138 total as of 12 Jan 2017
• On a real device:
– 200 in API 17
– 206 in API 19
– 313 in API 23
• Merging the lists:
– 214 total on API 17
– 238 total on API 19
– 317 total on API 23
• (List of Permissions File)
15 Jan 2017
• Normal: Can be granted to
the app, appear hidden by
default at install time
• Dangerous: Grantable to the
app at install time
• Signature: Only grantable to
apps signed with the same
private key as the one who
defined it
• System: OEM can get
• Development: Grantable to
apps via ADB
– Preinstalled, Pre23, AppOp,
Privileged
SE 435: Development in the Android Environment
20
Using Permissions (Old)
• System APIs are
protected by permissions
– When app tries to run an
API method, it throws a
SecurityException if the
app lacks the permission
• Old model (API ≤ 23):
– App declares all
permissions it needs in
Manifest
– User approves full list at
install time
15 Jan 2017
Old apps on new devices automatically
receive newer permissions
• User must approve the complete list
• App can change this using Manifest
• maxSdkVersion lets a uses-permission be
valid on devices ≤ the API given
Some permissions imply feature requirements
• BLUETOOTH 
android.hardware.bluetooth
•
CAMERA  android.hardware.camera
&
android.hardware.camera.autofocus
•
ACCESS_FINE_LOCATION 
android.hardware.location.gps &
android.hardware.location
•
Full list
SE 435: Development in the Android Environment
21
(Old) Asking for Permission
15 Jan 2017
SE 435: Development in the Android Environment
22
Seeing what you have
15 Jan 2017
SE 435: Development in the Android Environment
23
Requesting Permissions
• Starting in Android 6 (API 23): Runtime Grant/Revoke
• Apps must list normal, dangerous, and signature permissions
in Manifest
– Normal and signature are granted at install time
– Dangerous permissions are not granted
• App must request dangerous permission using
requestPermissions()
– User sees dialog box asking for permission
– User can say yes, no, or don’t ask again
– App can put an explanation box about why it wants it
• Use shouldShowRequestPermissionRationale() to know if you
should
– A yes grants for all permissions in the permission family
• Ex. Yes for Read Contacts counts as yes for Write Contacts
15 Jan 2017
SE 435: Development in the Android Environment
24
Request Permission
15 Jan 2017
SE 435: Development in the Android Environment
25
Managing and Revoking
15 Jan 2017
SE 435: Development in the Android Environment
26
Managing and Revoking
User can revoke individual dangerous
permissions at any time
Check whether you still have a permission
using checkSelfPermission (String
permission)
15 Jan 2017
SE 435: Development in the Android Environment
27
App Components & Permissions
Activity & Service
Broadcast Receiver
• Can declare permission field
in Manifest
• Can declare permission field
in Manifest
• Broadcasts sent by apps which
don’t have the permission
won’t be delivered to the
receiver
• Can be covered by an app
level permission element
• When an app sends the
activity an intent or tries to
start/bind the service, Binder
checks that the caller has the
permission
• Can set a permission on send
• Intents from non-qualifying
apps won’t be delivered
• Can be covered by an app
level permission element
15 Jan 2017
– void sendBroadcast (Intent
intent, String
receiverPermission)
– Only recipients with
receiverPermission will get it
SE 435: Development in the Android Environment
28
App Components & Permissions
Content Provider
URI Permissions
• Can declare in Manifest:
• Grant temporary permission on
a content URI
– permission for read and
write
– readPermission for just
read
– writePermission for just
write
• Binder prevents intents and
content resolution from
apps which don’t have the
permission
– Will get a security exception
– Can be used to keep a
content provider for just
internal use
15 Jan 2017
– Content provider for data and
files
– FileProvider for just files
– Binder tracks and enforces
Grantable via intent
• FLAG_GRANT_READ_URI_PERMI
SSION
• FLAG_GRANT_WRITE_URI_PERM
ISSION
– Delegatable to others
Grantable using API functions
• Can be revoked using API
SE 435: Development in the Android Environment
29
Checking Permissions in Code
• int checkPermission (String permission, int pid,
int uid)
– Checks if a given process id and user id combination have a
permission
– Results: PERMISSION_GRANTED or PERMISSION_DENIED
• int checkCallingPermission (String permission)
– Check if the app which called you has the permission
– Fails if there is no calling app (ex. Launched by launcher)
• int checkCallingOrSelfPermission (String
permission)
– Same as previous, but checks if the calling app has the permission
too (OR)
• Parallel functions for URIs
15 Jan 2017
SE 435: Development in the Android Environment
30
Conclusion
• Pending Intents
• Persisting State
– Shared Preferences
– Application Bundle
• Permissions and Security
– Permission Types
– Defining and Using Permissions
– Checking Permissions
15 Jan 2017
SE 435: Development in the Android Environment
31