Android осень 2013 лекция 4
-
Upload
technopark -
Category
Education
-
view
396 -
download
9
Transcript of Android осень 2013 лекция 4
Сетевое взаимодействие.Ad
apterViews
Лекция №4
Предыдущая лекция
Что такое callable?
Как работает Looper?
Зачем нужен Handler?
Что будет если менять UI из background потока?
Зачем нужен класс AsyncTask?
Что делает метод cancel в AsyncTask?
2
Серверное взаимодействие
3
Server
Сокеты
4
Сокеты
Client Socket
Server
ServerSocket
Polling
5
Server
Long-Polling
6
Server
Push notifications
7
GCM
Server
Long-polling
App
subscribes
regId
System
Варианты взаимодействия
8
HttpUrlConnection Server
HttpContext
HttpClient
HttpRequest
HttpResponse
HttpEntity
HttpEntity
Server
HttpUrlConnection
Lightweight
Один класс
Прост в использовании
Поддержка всего, что нужно
В поздних версиях gzip из коробки, кеширование, авторизация, IPv6 и проч.
Рекомендован Google
Баги
9
HttpUrlConnection
10
HttpUrlConnection connection = null;try {
URL url = new URL("http://example.com");connection = (HttpUrlConnection) url.openConnection();
HttpUrlConnection
11
HttpUrlConnection connection = null;try {
URL url = new URL("http://example.com");connection = (HttpUrlConnection) url.openConnection(); connection.setRequestMethod("GET");connection.setRequestProperty("Accept", "text/plain");
HttpUrlConnection
12
HttpUrlConnection connection = null;try {
URL url = new URL("http://example.com");connection = (HttpUrlConnection) url.openConnection(); connection.setRequestMethod("GET");connection.setRequestProperty("Accept", "text/plain");connection.connect();
HttpUrlConnection
13
HttpUrlConnection connection = null;try {URL url = new URL("http://example.com");connection = (HttpUrlConnection) url.openConnection(); connection.setRequestMethod("GET");connection.setRequestProperty("Accept", "text/plain");connection.connect();int statusCode = connection.getResponseCode();...readTextFromServer();
} catch (Exception e) {e.printStackTrace();
} finally {if (connection != null) {connection.disconnect();
}}
Apache HttpClient
ООП
ООП
Тяжеловесный – не больше одного экземпляра на приложение
Из коробки не поддерживает многопоточность
Больше не поддерживается
14
HttpClient
15
try {HttpGet request = new HttpGet("http://example.com");
HttpClient
16
try {HttpGet request = new HttpGet("http://example.com");request.setHeader("Accept", "text/plain");
HttpClient
17
try {HttpGet request = new HttpGet("http://example.com");request.setHeader("Accept", "text/plain");HttpResponse response = getHttpClient().execute(request);
HttpClient
18
try {HttpGet request = new HttpGet("http://example.com");request.setHeader("Accept", "text/plain");HttpResponse response = getHttpClient().execute(request);int statusCode = response.getStatusLine().getStatusCode();...return EntityUtils.toString(response.getEntity());
} catch (Exception e) {e.printStackTrace();
}
Почувствуйте разницу
19
Server
HttpUrlConnection
HttpUrlConnection
HttpUrlConnection
…
App
Server
HttpContext
HttpClient
HttpRequest
HttpResponse
HttpEntity
HttpEntity
App
Потокобезопасность
20
Thread N
12
HttpClient
SingleClientConnManager
Connection
Потокобезопасность
21
Thread N
12
HttpClient
ThreadSafeClientConnManager
. . .connection 1
connection N
connection 2
1
2
Потокобезопасность
22
static {...HttpParams params = new BasicHttpParams();ConnManagerParams.setMaxTotalConnections(params, 10);ConnManagerParams.setMaxConnectionsPerRoute(params,
new ConnPerRoute() {@Overridepublic int getMaxForRoute(HttpRoute route) {return 5;
}});
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
httpClient = new DefaultHttpClient(cm, params);}
Keep-alive
23
Keep-alive cоединение
Server
Application
request request ... request request
TCP
+ …+… + = traffic
Keep-alive
24
Номер запроса
Время(ms)KeepAlive = false
Время(ms)KeepAlive = true
1 2098 2023
2 2157 1604
3 2037 1698
4 2096 1774
5 1944 1173
6 2055 1573
7 1865 1683
8 2119 1670
9 1986 1666
10 1965 1541
≈2032,2 1700,5
На 16,2% быстрее!
Keep-alive duration
25
𝐭𝟑 > 𝐝
𝐭
𝐭 − 𝐭𝐢𝐦𝐞
𝐝 − 𝐤𝐞𝐞𝐩 𝐚𝐥𝐢𝐯𝐞 𝐝𝐮𝐫𝐚𝐭𝐢𝐨𝐧
request1
request2
request3
request4
TCP
TCP
ServerApp
Keep-alive duration
26
httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
@Overridepublic long getKeepAliveDuration(HttpResponse response,
HttpContext context){return KEEP_ALIVE_DURATION_MILLISECONDS;
}});
Keep-alive prior Froyo
27
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO){System.setProperty("http.keepAlive", "false");
}
GZip
28
...InputStream is = connection.getInputStream();String contentEncoding = connection.getContentEncoding();if ("gzip".equalsIgnoreCase(contentEncoding)) {
is = new GZIPInputStream(connection.getInputStream());}...
...InputStream is = response.getEntity().getContent();Header contentEncoding =
response.getFirstHeader("Content-Encoding");if (contentEncoding != null
&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {is = new GZIPInputStream(is);
}...
GZip
29
Не полагайтесь на Content-Length!
Https
30
CA
Application Server
Signs certificate
Certificate
request
Checks certificate
Random symmetric key
Private key
Public key
Https
KeyChain API на платформах >= 4.0
< 4.0 – создавать локальное хранилище ключей
Доверять всем сертификатам
31
Utilities
32
StrictMode DDMS Network Traffic Tool Rest-client Wireshark
Adapter pattern
33
ListView
34
Терминология
Childs
Position
Id
35
getView()
36
Отсюда получаются данные Здесь оптимизация Здесь вы выстрелите себе в ногу
Recycle Bin
37
Optimization – slow way
38
Optimization – right way
39
Optimization – fast way
40
Optimization
41