Download Providers, Binding and Using Services, Broadcast Receivers, File

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
Providers, Services,
Broadcast Receivers, File
System, Network, Async
Tasks
1 January 2017
Lecture 8
1 Jan 2017
SE 435: Development in the Android Environment
1
Topics for Today
• Content Providers
– Manifest Element and Permissions
• Services
– Role
– Binding and Using
– Application Manifest Element
• Broadcast Receiver
– Broadcasts
• File System
– Structure
– Functions
• Network Access
• AsyncTask
• Sources:
– developer.android.com
1 Jan 2017
SE 435: Development in the Android Environment
2
Controlling Access
• Option 1: Configure global read and write access for the
content provider
– One permission to read, one to write
– One permission for both
• Option 2: Configure read and write access for particular
paths in the content provider
– One permission to read, one to write
– One permission for both
• Option 3: Grant read and write on a URI basis
– URI based read or write – granted by intent
– Revoked automatically or manually
1 Jan 2017
SE 435: Development in the Android Environment
3
Provider Element Structure
1 Jan 2017
SE 435: Development in the Android Environment
4
Provider Element Structure 1/2
•
Defines the provider in the Manifest
Attributes
• authorities: list of authorities, can be ;
delimited
• enabled: whether the provider can be
accessed
• exported: can other apps call or use the
provider
• grantUriPermissions: if Option 3 is
allowed
• icon, label
• initOrder: lets content providers in the app
be initiated in a particular series
– Higher number  sooner
1 Jan 2017
SE 435: Development in the Android Environment
5
Provider Element Structure
• multiprocess: normally provider
runs in host app’s process
– Setting to true gives everyone who uses
the resolver its own copy, saving on IPC
• name: class name
• permission: read and write
permission
– Use readPermission or
writePermission for separate
rules, they override
• process: process name
• syncable: whether data is to
synchronized with web server
1 Jan 2017
SE 435: Development in the Android Environment
6
Grant Uri Permission Structure
• Allows the provider to give fine grained rules about granting
URI permissions
• If you put false in the parent element, you can put exceptions
here
• Must choose one of the three options
– pathPattern allows for wildcards like *
1 Jan 2017
SE 435: Development in the Android Environment
7
Path Permission Structure
• Grant permissions on specific paths in the provider
– Overrides parent
• Can allow search suggestions from the paths given
• Read or write permissions override the permission element
1 Jan 2017
SE 435: Development in the Android Environment
8
So Far
• Content Providers
– Manifest Element and Permissions
• Services
– Role
– Binding and Using
– Application Manifest Element
• Broadcast Receiver
– Broadcasts
• File System
– Structure
– Functions
• Network Access
• AsyncTask
1 Jan 2017
SE 435: Development in the Android Environment
9
Service Overview
• Services: Code objects
which perform tasks for
others
– “Threads with their own
lifecycle”
• If a task needs to run in
the background during an
Activity  Use a thread
• If a task needs to live past
the component which
started it or be available
to others  Use a service.
1 Jan 2017
• Services can be
initialized:
– Started by another
component (ex. Activity)
– Bound by another
component (ex. Activity)
• Service starts in the same
thread/process as the one
which started/bound it
– So a Service with heavy
work should spawn worker
threads
SE 435: Development in the Android Environment
10
Initializing a Service: Starting
Started Service: a call to
startService() with an intent
– Communication is just via the initial
intent
1. Service is launched
2. Service runs until it decides it’s
finished (stopSelf()) or another
component stops it
(stopService())
• Android OS kills services under low
memory conditions only
1 Jan 2017
SE 435: Development in the Android Environment
11
Initializing a Service: Starting
• Service can be started many times
– IntentService subclass: Prevents
more than one use at a time
– Service subclass: Multiple users, so
multi-threading and synchronization
• Stopping gets complicated
– If you enforce FIFO, can wait until all
calls have finished using startId to
guard stopSelf()
1 Jan 2017
SE 435: Development in the Android Environment
12
Initializing a Service: Binding
Bound Service: Connected to a
component for its lifetime
– Lifetime limited by binding component
• Bound services can communicate
with binding component
– Interprocess Communication (IPC)
makes it interactive
– Requires writing an IBinder
interface or an AIDL file to detail
methods and return values
1 Jan 2017
SE 435: Development in the Android Environment
13
Initializing a Service: Binding
• Bind using bindService()
– Callback is onBind()
• Unbind using unbindService()
– Callback is onUnbind()
• Service is killed when all call
unbindService()
– No need for stopSelf()
1 Jan 2017
SE 435: Development in the Android Environment
14
Binding vs. Starting
1 Jan 2017
SE 435: Development in the Android Environment
15
Services and Apps
Services can offer both binding
and starting
• Stopping is complex: it runs
until stopSelf() and all have
unbound
• Offer both if you want the
Service to live on its own, but
also offer a way to update or
check progress
Services can be background or
foreground
• Usually background  lower
priority so they don’t interfere
• Foreground services  user is
aware of it, should offer
an interface
– Use notifications or Toasts
1 Jan 2017
SE 435: Development in the Android Environment
16
So Far
• Content Providers
– Manifest Element and Permissions
• Services
– Role
– Binding and Using
– Application Manifest Element
• Broadcast Receiver
– Broadcasts
• File System
– Structure
– Functions
• Network Access
• AsyncTask
1 Jan 2017
SE 435: Development in the Android Environment
17
Services Element Structure
• Used to declare the
service’s properties
Attributes (new only):
• isolatedProcess: if
true, the service runs in
its own process,
isolated from all others
– Can then only be
accessed by starting and
binding
• permission: needed
to start or bind to it
1 Jan 2017
SE 435: Development in the Android Environment
18
So Far
• Content Providers
– Manifest Element and Permissions
• Services
– Role
– Binding and Using
– Application Manifest Element
• Broadcast Receiver
– Broadcasts
• File System
– Structure
– Functions
• Network Access
• AsyncTask
1 Jan 2017
SE 435: Development in the Android Environment
19
Broadcast Receiver Overview
• Broadcast Receiver: Allow an
app to receive updates from
others
– Registered in Application
Manifest
– Declared/removed in code
• Broadcasts: An app wants to
inform others of an event
– Should be a background
process, user doesn’t need to
know
• Created for the broadcast and
then killed
– Can’t do asynchronous or long
stuff
– Can’t open dialogs or bind, but
can start services and put
notifications
1 Jan 2017
SE 435: Development in the Android Environment
20
About Broadcasts
•
A Broadcast sends an intent to:
•
– Every other app interested
(publish/subscribe)
•
Add a permission
– Other components of the same app
(local)
– One specific app (as of Ice Cream
– No feedback
•
Broadcast Receiver expresses
interest in broadcasts to Android
OS
In order Broadcast: Interested apps
one by one, ordered by priority
– Receiver can abort the continuation
– Sender can get feedback: code, data
string, Bundle of extras
Sandwich)
•
General Broadcast: All interested
apps, no order
•
Sticky Broadcast: Sent and then
delivered to any new broadcast
receivers later
– Declares intent filters
– Intent filter specifies: action, category,
and data
– Can add permission
– Intent arrives at the onReceive()
callback
– Can define its own priority
1 Jan 2017
SE 435: Development in the Android Environment
21
Broadcasts and Security
• Broadcasts can be sent to any other app (Security?
Privacy?)
• Broadcast Receivers can receive from any other app
– Filters don’t prevent garbage, direct broadcasts
• Mitigation:
1. Use permissions to limit who can send/receive
2. For in-app broadcasts, use LocalBroadcastManager class –
broadcast doesn’t leave the app
3. Statically define the broadcast receiver as unavailable to others:
set android:exported to false in Manifest
1 Jan 2017
SE 435: Development in the Android Environment
22
Receiver Element Structure
• Used to statically
declare broadcast
receiver
– Can also be declared
in code
• No new attributes
1 Jan 2017
SE 435: Development in the Android Environment
23
So Far
• Content Providers
– Manifest Element and Permissions
• Services
– Role
– Binding and Using
– Application Manifest Element
• Broadcast Receiver
– Broadcasts
• File System
– Structure
– Functions
• Network Access
• AsyncTask
1 Jan 2017
SE 435: Development in the Android Environment
24
File System
Internal storage:
ext file system
1 Jan 2017
SE 435: Development in the Android Environment
25
Key Directory: /data/data/
• Holds a directory for each app based on its package
name
• All files, databases, resources stored here
• Not accessible to other apps
– Can change path permissions using file API
1 Jan 2017
SE 435: Development in the Android Environment
26
/data/data Files Example
1 Jan 2017
SE 435: Development in the Android Environment
27
Key Directory: /sdcard/
1 Jan 2017
SE 435: Development in the Android Environment
28
1 Jan 2017
SE 435: Development in the Android Environment
29
Key Directory: /sdcard/
• External storage: managed in a different file system than internal
storage
– FAT32 file system (or others)
– No management of permissions on the data
– Some devices emulate it
• WRITE_EXTERNAL_STORAGE to write
• READ_EXTERNAL_STORAGE to read as of Android 4.1
• /Android/data/packageName
–
–
–
–
Original directory for external storage
When app removed, its directory is deleted
No protection from others
From API 19 and up (4.4 KitKat), apps can write and read here without read
or write permission
1 Jan 2017
SE 435: Development in the Android Environment
30
External Storage Example
1 Jan 2017
SE 435: Development in the Android Environment
31
External Storage Example
1 Jan 2017
SE 435: Development in the Android Environment
32
Files Details
Internal Storage
External Storage
•
• getExternalStorageState ()
getFilesDir()
–
•
openFileOutput()
–
•
Gets a cache directory for temporary files
May be deleted without warning if low on
space
Shortcut to create a new temporary file
boolean setReadable ( boolean
readable, boolean ownerOnly )
–
•
–
Get a public directory which can be
shared with others (music, pictures,
videos)
• getExternalFilesDir()
–
Get your directory under
/Android/data/packageName
Allow others to read a file
• boolean setWritable (
boolean writable, boolean
ownerOnly)
–
Check if SD card is available
MEDIA_MOUNTED is ok
• getExternalStoragePublicDir
ectory()
createTempFile()
–
•
–
–
Shortcut to open a new internal file
getCacheDir()
–
–
•
Gets the directory for private files
• getExternalStorageDirectory
()
–
Gets the root of the external file system
Allow others to write a file
setExecutable too
1 Jan 2017
SE 435: Development in the Android Environment
33
File IO Methods
1 Jan 2017
SE 435: Development in the Android Environment
34
File IO Methods
• canRead(), canWrite(), canExecute()
– See what you can do
• isDirectory(), isFile()
– A directory is also treated as a file
• getName(), getPath(), getParent()
– See where you are
• For directories:
– list(), listFiles() – see what’s here
– mkDir(), mkDirs() – create this directory (mkDirs() creates
hierarchy)
• For files:
– getLength(), toUri()
– FileReader class to read, usually wrapped in BufferedReader:
BufferedReader buf = new BufferedReader(new
FileReader("file1.txt"));
1 Jan 2017
SE 435: Development in the Android Environment
35
So Far
• Content Providers
– Manifest Element and Permissions
• Services
– Role
– Binding and Using
– Application Manifest Element
• Broadcast Receiver
– Broadcasts
• File System
– Structure
– Functions
• Network Access
• AsyncTask
1 Jan 2017
SE 435: Development in the Android Environment
36
Network Access
• Key permission: android.permission.INTERNET
• Device may have multiple network access methods,
retrieve with
NetworkInterface.getNetworkInterfaces()
– Can get the interface name using getName()
– Can get the IP addresses associated with the interface using
Enumeration<InetAddress> getInetAddresses()
• InetAddress represents either IPv4 or IPv6, so you can
examine them
1 Jan 2017
SE 435: Development in the Android Environment
37
IP Address Listing
ArrayAdapter<String> ada = new ArrayAdapter<String>(this,
R.layout.ipaddresstv);
List<NetworkInterface> ni =
Collections.list(NetworkInterface.getNetworkInterfaces());
// see what we have here
for (NetworkInterface inter : ni) {
// get the IP addresses here
List<InetAddress> addresses =
Collections.list(inter.getInetAddresses());
// add all addresses
for (InetAddress add : addresses) {
ada.add(add.toString().substring(1));
}
}
1 Jan 2017
SE 435: Development in the Android Environment
38
R.layout.ipaddresstv
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textSize="20sp"
android:id="@+id/etSingleIP" >
</TextView>
1 Jan 2017
SE 435: Development in the Android Environment
39
Example IPs
1 Jan 2017
SE 435: Development in the Android Environment
40
Network Sockets
Client Side
Server Side
InetAddress ip =
Inet4Address.getByName(p[0]);
int port =
Integer.parseInt(p[0]);
int port =
Integer.parseInt(p[1]);
Socket sock = new Socket(ip,
port);
1 Jan 2017
InetAddress inet =
InetAddress.getByName(p[1]);
backlog
ServerSocket sock = new
ServerSocket(port, 50, inet);
while (!isCancelled()){
// get a client
Socket client =
sock.accept();
// do something
client.close();
}
SE 435: Development in the Android Environment
Binding
happens
here.
Could also
do it later.
41
Network Communication
Writing to Socket
Reading from Socket
public OutputStream
getOutputStream()
public InputStream
getInputStream()
• Can wrap in helper objects:
• Can wrap in helper objects:
BufferedWriter bw =
new BufferedWriter(
new OutputStreamWriter(
p[0].
getOutputStream()));
BufferedReader br =
new BufferedReader(
new InputStreamReader(
p[0].
getInputStream()));
1 Jan 2017
SE 435: Development in the Android Environment
42
So Far
• Content Providers
– Manifest Element and Permissions
• Services
– Role
– Binding and Using
– Application Manifest Element
• Broadcast Receiver
– Broadcasts
• File System
– Structure
– Functions
• Network Access
• AsyncTask
1 Jan 2017
SE 435: Development in the Android Environment
43
Thread Issues
Bad Idea
Better Idea
• Do network
communication from GUI
thread
• Use helper threads
–
–
–
–
Create sockets
Bind
Listen for connections
Send and receive data
• Why?
– GUI may get stuck
– Android “strict mode” will
complain
1 Jan 2017
– AsyncTask
• AsyncTask
– Similar to
BackgroundWorker in C#
• Inherit from it and
implement methods:
–
–
–
–
onPreExecute (on UI)
doInBackground (on child)
onProgressUpdate (on UI)
onPostExecute (on UI)
SE 435: Development in the Android Environment
44
AsyncTask Example 1/3
private class NetworkConnectTask extends AsyncTask<String, String,
Socket> {
@Override
protected Socket doInBackground(String... params) {
try {
InetAddress ip = Inet4Address.getByName(params[0]);
int port = Integer.parseInt(params[1]);
Socket sock = new Socket(ip, port);
return sock;
} catch (UnknownHostException e) {
publishProgress("Error: Unknown host: " + e.getMessage());
} catch (IOException e) {
publishProgress("Error: Unable to connect to host: " +
e.getMessage());
} catch (NumberFormatException e) {
publishProgress("Error: Illegal port: " + e.getMessage());
}
return null;
}
1 Jan 2017
SE 435: Development in the Android Environment
45
AsyncTask Example 2/3
@Override
protected void onProgressUpdate(String...
values) {
TextView tvLog = (TextView)
findViewById(R.id.tvLog);
tvLog.append(values[0] + "\n");
}
1 Jan 2017
SE 435: Development in the Android Environment
46
AsyncTask Example 2/3
@Override
protected void onPostExecute(Socket result) {
// see if we got anything
if ( result != null)
{
// store it
sock = result;
}
else {
// the button to connect should be reset
// since we failed
Button bConnect = (Button)
findViewById(R.id.bConnect);
bConnect.setText(string.ConnectButton);
}
}
1 Jan 2017
SE 435: Development in the Android Environment
47
Conclusion
• Content Providers
– Manifest Element and Permissions
• Services
– Role
– Binding and Using
– Application Manifest Element
• Broadcast Receiver
– Broadcasts
• File System
– Structure
– Functions
• Network Access
• AsyncTask
1 Jan 2017
SE 435: Development in the Android Environment
48