SlideShare a Scribd company logo
1 of 19
Download to read offline
Connecting to the Network

Kewang
Add Permissions

<?xml version="1.0" encoding="utf-8"?>
<manifest>
  ......

  <uses-permission
android:name="android.permission.INTERNET" />
  <uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />

  ......
</manifest>
                          at AndroidManifest.xml

                                                       2
isConnected?

private boolean isConnected() {
  ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo networkInfo =
connMgr.getActiveNetworkInfo();

    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    } else {
        return false;
    }
}
                                                         3
Long IO accessing


 Activity.runOnUiThread(Runnable)
 View.post(Runnable)
 View.postDelayed(Runnable, long)
 Handler
 AsyncTask

                                    4
AsyncTask
private class ProcessingTask extends AsyncTask<String,
Void, String> {
  @Override
  protected String doInBackground(String... params) {
    try {
      return downloadUrl(params[0]);
    } catch (IOException e) {
      return "無法讀取網頁";           worker thread
    }
  }

    @Override
    protected void onPostExecute(String result) {
      txtContent.setText(result);
    }                              main thread
}                                                        5
downloadUrl
private String downloadUrl(String myurl) {
  int len = 500;
  URL url = new URL(myurl);
  HttpURLConnection conn = (HttpURLConnection)
url.openConnection();

    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);

    conn.connect();

    int statusCode = conn.getResponseCode();

    return streamToString(conn.getInputStream(), len);
                                                    6
}
streamToString

private String streamToString(InputStream stream, int
len) {
  Reader reader = new InputStreamReader(stream, "UTF-
8");
  char[] buffer = new char[len];

    reader.read(buffer);

    return new String(buffer);
}

                                                   7
streamToImage



private Bitmap streamToImage(InputStream stream) {
  return BitmapFactory.decodeStream(stream);
}

            GET http://example.com/mitake.png


                                                8
Where is My IP?
private String getIP() {
  for (Enumeration<NetworkInterface> en = NetworkInterface
    .getNetworkInterfaces(); en.hasMoreElements();) {
    NetworkInterface intf = en.nextElement();

        for (Enumeration<InetAddress> enumIpAddr =
          intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
          InetAddress inet = enumIpAddr.nextElement();

            if (!inet.isLoopbackAddress() && inet instanceof Inet4Address) {
              return inet.getHostAddress().toString();
            }
        }
    }

    return "";
}
                                                                        9
HttpClient & HttpURLConnection


  ●   HttpClient
      ● stable
      ● few bugs

      ● large size

  ●   HttpURLConnection
      ● easy to use
      ● gzip-support




                             10
no gzip-support




                  11
gzip-supported




                 12
HttpClient & HttpURLConnection


        org.apache.http.cl java.net.HttpURL
        ient.HttpClient    Connection

2.1, 2.2 a                     r(close method issue)


2.3 and
        r(difficult to maintain) a
higher

                                                 13
prior 2.2 to use HttpURLConnection



private void disableConnectionReuseIfNecessary() {
  if (Integer.parseInt(Build.VERSION.SDK) <
    Build.VERSION_CODES.FROYO) {
    System.setProperty("http.keepAlive", "false");
  }
}




                                               14
2.3 and higher, gzip-support


  getContentLength() is incorrect
  ● disable gzip-support

  ● use getInputStream's length




                                    15
disable gzip-support

HttpURLConnection conn = (HttpURLConnection)
          url.openConnection();

conn.setRequestProperty("Accept-Encoding",
"identity");
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);

conn.connect();


                                               16
use getInputStream's length
private String streamToString(InputStream stream) {
  Reader reader = new InputStreamReader(stream, "UTF-
8");
  StringBuffer sb = new StringBuffer();
  int length = 0;
  char c;

    while ((c = (char) reader.read()) != 65535) {
      length++;
      sb.append(c);
    }

    return sb.toString();
}                                                   17
References


●   http://developer.android.com/training/basics/network-ops/connecting.html
●   http://developer.android.com/reference/java/net/HttpURLConnection.html
●   http://developer.android.com/reference/java/net/URLConnection.html
●   http://developer.android.com/reference/java/net/package-summary.html
●   http://developer.android.com/reference/android/net/ConnectivityManager.html
●   http://developer.android.com/reference/android/net/NetworkInfo.html
●   http://android-developers.blogspot.tw/2011/09/androids-http-clients.html
●   http://android-developers.blogspot.tw/2009/05/painless-threading.html
●   http://www.droidnova.com/get-the-ip-address-of-your-device,304.html
●   https://developers.google.com/speed/articles/gzip


                                                                          18
19

More Related Content

What's hot

Spark Day 2017- Spark 의 과거, 현재, 미래
Spark Day 2017- Spark 의 과거, 현재, 미래Spark Day 2017- Spark 의 과거, 현재, 미래
Spark Day 2017- Spark 의 과거, 현재, 미래Moon Soo Lee
 
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Morocco 2019
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Morocco 201910 Excellent Ways to Secure Your Spring Boot Application - Devoxx Morocco 2019
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Morocco 2019Matt Raible
 
LibreSSL, one year later
LibreSSL, one year laterLibreSSL, one year later
LibreSSL, one year laterGiovanni Bechis
 
Taking advantage of Prometheus relabeling
Taking advantage of Prometheus relabelingTaking advantage of Prometheus relabeling
Taking advantage of Prometheus relabelingJulien Pivotto
 
Intro KaKao MRTE (MySQL Realtime Traffic Emulator)
Intro KaKao MRTE (MySQL Realtime Traffic Emulator)Intro KaKao MRTE (MySQL Realtime Traffic Emulator)
Intro KaKao MRTE (MySQL Realtime Traffic Emulator)I Goo Lee
 
FPV Streaming Server with ffmpeg
FPV Streaming Server with ffmpegFPV Streaming Server with ffmpeg
FPV Streaming Server with ffmpegChan Shik Lim
 
Chatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopChatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopyayaria
 
Python twisted
Python twistedPython twisted
Python twistedMahendra M
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Alexey Fyodorov
 
Vert.X: Microservices Were Never So Easy (Clement Escoffier)
Vert.X: Microservices Were Never So Easy (Clement Escoffier)Vert.X: Microservices Were Never So Easy (Clement Escoffier)
Vert.X: Microservices Were Never So Easy (Clement Escoffier)Red Hat Developers
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programmingAnung Ariwibowo
 

What's hot (20)

Spark Day 2017- Spark 의 과거, 현재, 미래
Spark Day 2017- Spark 의 과거, 현재, 미래Spark Day 2017- Spark 의 과거, 현재, 미래
Spark Day 2017- Spark 의 과거, 현재, 미래
 
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Morocco 2019
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Morocco 201910 Excellent Ways to Secure Your Spring Boot Application - Devoxx Morocco 2019
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Morocco 2019
 
Socket.io v.0.8.3
Socket.io v.0.8.3Socket.io v.0.8.3
Socket.io v.0.8.3
 
LibreSSL, one year later
LibreSSL, one year laterLibreSSL, one year later
LibreSSL, one year later
 
L'odyssée de la log
L'odyssée de la logL'odyssée de la log
L'odyssée de la log
 
Taking advantage of Prometheus relabeling
Taking advantage of Prometheus relabelingTaking advantage of Prometheus relabeling
Taking advantage of Prometheus relabeling
 
Winform
WinformWinform
Winform
 
Codable routing
Codable routingCodable routing
Codable routing
 
Intro KaKao MRTE (MySQL Realtime Traffic Emulator)
Intro KaKao MRTE (MySQL Realtime Traffic Emulator)Intro KaKao MRTE (MySQL Realtime Traffic Emulator)
Intro KaKao MRTE (MySQL Realtime Traffic Emulator)
 
Web sockets
Web socketsWeb sockets
Web sockets
 
FPV Streaming Server with ffmpeg
FPV Streaming Server with ffmpegFPV Streaming Server with ffmpeg
FPV Streaming Server with ffmpeg
 
Shibuya,trac セッション
Shibuya,trac セッションShibuya,trac セッション
Shibuya,trac セッション
 
Chatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopChatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptop
 
AsyncIO To Speed Up Your Crawler
AsyncIO To Speed Up Your CrawlerAsyncIO To Speed Up Your Crawler
AsyncIO To Speed Up Your Crawler
 
Pledge in OpenBSD
Pledge in OpenBSDPledge in OpenBSD
Pledge in OpenBSD
 
Python twisted
Python twistedPython twisted
Python twisted
 
Hack ASP.NET website
Hack ASP.NET websiteHack ASP.NET website
Hack ASP.NET website
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)
 
Vert.X: Microservices Were Never So Easy (Clement Escoffier)
Vert.X: Microservices Were Never So Easy (Clement Escoffier)Vert.X: Microservices Were Never So Easy (Clement Escoffier)
Vert.X: Microservices Were Never So Easy (Clement Escoffier)
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programming
 

Viewers also liked

96年度資訊志工期末報告
96年度資訊志工期末報告96年度資訊志工期末報告
96年度資訊志工期末報告Mu Chun Wang
 
Webduino introduction
Webduino introductionWebduino introduction
Webduino introductionMu Chun Wang
 
97年研發替代役役男轉調作業說明簡報(公告版)
97年研發替代役役男轉調作業說明簡報(公告版)97年研發替代役役男轉調作業說明簡報(公告版)
97年研發替代役役男轉調作業說明簡報(公告版)Mu Chun Wang
 
研發替代役制度簡報
研發替代役制度簡報研發替代役制度簡報
研發替代役制度簡報Mu Chun Wang
 
中和線分流是怎麼回事?
中和線分流是怎麼回事?中和線分流是怎麼回事?
中和線分流是怎麼回事?Mu Chun Wang
 
UMiP推廣手冊V1.1.1
UMiP推廣手冊V1.1.1UMiP推廣手冊V1.1.1
UMiP推廣手冊V1.1.1Mu Chun Wang
 
行動平台上利用Facebook API開發社群應用程式
行動平台上利用Facebook API開發社群應用程式行動平台上利用Facebook API開發社群應用程式
行動平台上利用Facebook API開發社群應用程式Mu Chun Wang
 
1072個研發替代役的日子
1072個研發替代役的日子1072個研發替代役的日子
1072個研發替代役的日子Mu Chun Wang
 
Creating custom views
Creating custom viewsCreating custom views
Creating custom viewsMu Chun Wang
 
Network hardware
Network hardwareNetwork hardware
Network hardwaresnoonan
 
Hedis - GET HBase via Redis
Hedis - GET HBase via RedisHedis - GET HBase via Redis
Hedis - GET HBase via RedisMu Chun Wang
 
104學年度行動裝置程式設計課程說明
104學年度行動裝置程式設計課程說明104學年度行動裝置程式設計課程說明
104學年度行動裝置程式設計課程說明Mu Chun Wang
 
你有想過畢業九年後的你會變什麼樣子嗎?
你有想過畢業九年後的你會變什麼樣子嗎?你有想過畢業九年後的你會變什麼樣子嗎?
你有想過畢業九年後的你會變什麼樣子嗎?Mu Chun Wang
 

Viewers also liked (20)

Slideshare ppt
Slideshare pptSlideshare ppt
Slideshare ppt
 
Navigating the Internet Protocol Transition
Navigating the Internet Protocol TransitionNavigating the Internet Protocol Transition
Navigating the Internet Protocol Transition
 
96年度資訊志工期末報告
96年度資訊志工期末報告96年度資訊志工期末報告
96年度資訊志工期末報告
 
Webduino introduction
Webduino introductionWebduino introduction
Webduino introduction
 
97年研發替代役役男轉調作業說明簡報(公告版)
97年研發替代役役男轉調作業說明簡報(公告版)97年研發替代役役男轉調作業說明簡報(公告版)
97年研發替代役役男轉調作業說明簡報(公告版)
 
研發替代役制度簡報
研發替代役制度簡報研發替代役制度簡報
研發替代役制度簡報
 
中和線分流是怎麼回事?
中和線分流是怎麼回事?中和線分流是怎麼回事?
中和線分流是怎麼回事?
 
豬流感簡介
豬流感簡介豬流感簡介
豬流感簡介
 
版本控制Git
版本控制Git版本控制Git
版本控制Git
 
UMiP推廣手冊V1.1.1
UMiP推廣手冊V1.1.1UMiP推廣手冊V1.1.1
UMiP推廣手冊V1.1.1
 
Parsing XML Data
Parsing XML DataParsing XML Data
Parsing XML Data
 
行動平台上利用Facebook API開發社群應用程式
行動平台上利用Facebook API開發社群應用程式行動平台上利用Facebook API開發社群應用程式
行動平台上利用Facebook API開發社群應用程式
 
1072個研發替代役的日子
1072個研發替代役的日子1072個研發替代役的日子
1072個研發替代役的日子
 
Creating custom views
Creating custom viewsCreating custom views
Creating custom views
 
Network hardware
Network hardwareNetwork hardware
Network hardware
 
Hedis - GET HBase via Redis
Hedis - GET HBase via RedisHedis - GET HBase via Redis
Hedis - GET HBase via Redis
 
104學年度行動裝置程式設計課程說明
104學年度行動裝置程式設計課程說明104學年度行動裝置程式設計課程說明
104學年度行動裝置程式設計課程說明
 
你有想過畢業九年後的你會變什麼樣子嗎?
你有想過畢業九年後的你會變什麼樣子嗎?你有想過畢業九年後的你會變什麼樣子嗎?
你有想過畢業九年後的你會變什麼樣子嗎?
 
greenDAO
greenDAOgreenDAO
greenDAO
 
Lightning Hedis
Lightning HedisLightning Hedis
Lightning Hedis
 

Similar to Connecting to the network

Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaFrank Lyaruu
 
13 networking, mobile services, and authentication
13   networking, mobile services, and authentication13   networking, mobile services, and authentication
13 networking, mobile services, and authenticationWindowsPhoneRocks
 
Lecture 10 Networking on Mobile Devices
Lecture 10 Networking on Mobile DevicesLecture 10 Networking on Mobile Devices
Lecture 10 Networking on Mobile DevicesMaksym Davydov
 
망고100 보드로 놀아보자 19
망고100 보드로 놀아보자 19망고100 보드로 놀아보자 19
망고100 보드로 놀아보자 19종인 전
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScriptQiangning Hong
 
Client server part 12
Client server part 12Client server part 12
Client server part 12fadlihulopi
 
Jersey framework
Jersey frameworkJersey framework
Jersey frameworkknight1128
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasyJBug Italy
 
Testing in android
Testing in androidTesting in android
Testing in androidjtrindade
 
Performance #4 network
Performance #4  networkPerformance #4  network
Performance #4 networkVitali Pekelis
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqelajobandesther
 
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxWeb CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxcelenarouzie
 
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeGDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeKAI CHU CHUNG
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best PracticesYekmer Simsek
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSTechWell
 

Similar to Connecting to the network (20)

Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
 
13 networking, mobile services, and authentication
13   networking, mobile services, and authentication13   networking, mobile services, and authentication
13 networking, mobile services, and authentication
 
Android Networking
Android NetworkingAndroid Networking
Android Networking
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Lecture 10 Networking on Mobile Devices
Lecture 10 Networking on Mobile DevicesLecture 10 Networking on Mobile Devices
Lecture 10 Networking on Mobile Devices
 
망고100 보드로 놀아보자 19
망고100 보드로 놀아보자 19망고100 보드로 놀아보자 19
망고100 보드로 놀아보자 19
 
服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript服务框架: Thrift & PasteScript
服务框架: Thrift & PasteScript
 
Client server part 12
Client server part 12Client server part 12
Client server part 12
 
Jersey framework
Jersey frameworkJersey framework
Jersey framework
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 
Testing in android
Testing in androidTesting in android
Testing in android
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Performance #4 network
Performance #4  networkPerformance #4  network
Performance #4 network
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqela
 
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxWeb CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
 
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeGDG Devfest 2019 - Build go kit microservices at kubernetes with ease
GDG Devfest 2019 - Build go kit microservices at kubernetes with ease
 
Android dev 3
Android dev 3Android dev 3
Android dev 3
 
Java RMI
Java RMIJava RMI
Java RMI
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
 

More from Mu Chun Wang

如何在有限資源下實現十年的後端服務演進
如何在有限資源下實現十年的後端服務演進如何在有限資源下實現十年的後端服務演進
如何在有限資源下實現十年的後端服務演進Mu Chun Wang
 
深入淺出 autocomplete
深入淺出 autocomplete深入淺出 autocomplete
深入淺出 autocompleteMu Chun Wang
 
你畢業後要任職的軟體業到底都在做些什麼事
你畢業後要任職的軟體業到底都在做些什麼事你畢業後要任職的軟體業到底都在做些什麼事
你畢業後要任職的軟體業到底都在做些什麼事Mu Chun Wang
 
網路服務就是一連串搜尋的集合體
網路服務就是一連串搜尋的集合體網路服務就是一連串搜尋的集合體
網路服務就是一連串搜尋的集合體Mu Chun Wang
 
老司機帶你上手 PostgreSQL 關聯式資料庫系統
老司機帶你上手 PostgreSQL 關聯式資料庫系統老司機帶你上手 PostgreSQL 關聯式資料庫系統
老司機帶你上手 PostgreSQL 關聯式資料庫系統Mu Chun Wang
 
使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能
使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能
使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能Mu Chun Wang
 
Funliday 新創生活甘苦談
Funliday 新創生活甘苦談Funliday 新創生活甘苦談
Funliday 新創生活甘苦談Mu Chun Wang
 
大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度
大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度
大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度Mu Chun Wang
 
如何使用 iframe 製作一個易於更新及更安全的前端套件
如何使用 iframe 製作一個易於更新及更安全的前端套件如何使用 iframe 製作一個易於更新及更安全的前端套件
如何使用 iframe 製作一個易於更新及更安全的前端套件Mu Chun Wang
 
pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題
pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題
pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題Mu Chun Wang
 
模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構
模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構
模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構Mu Chun Wang
 
Google Maps 開始收費了該怎麼辦?
Google Maps 開始收費了該怎麼辦?Google Maps 開始收費了該怎麼辦?
Google Maps 開始收費了該怎麼辦?Mu Chun Wang
 
Git 可以做到的事
Git 可以做到的事Git 可以做到的事
Git 可以做到的事Mu Chun Wang
 
那些大家常忽略的 Cache-Control
那些大家常忽略的 Cache-Control那些大家常忽略的 Cache-Control
那些大家常忽略的 Cache-ControlMu Chun Wang
 
如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化
如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化
如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化Mu Chun Wang
 
如何與全世界分享你的 Library
如何與全世界分享你的 Library如何與全世界分享你的 Library
如何與全世界分享你的 LibraryMu Chun Wang
 
如何與 Git 優雅地在樹上唱歌
如何與 Git 優雅地在樹上唱歌如何與 Git 優雅地在樹上唱歌
如何與 Git 優雅地在樹上唱歌Mu Chun Wang
 
API Blueprint - API 文件規範的三大領頭之一
API Blueprint - API 文件規範的三大領頭之一API Blueprint - API 文件規範的三大領頭之一
API Blueprint - API 文件規範的三大領頭之一Mu Chun Wang
 
團體共同協作與版本管理 - 01認識共同協作
團體共同協作與版本管理 - 01認識共同協作團體共同協作與版本管理 - 01認識共同協作
團體共同協作與版本管理 - 01認識共同協作Mu Chun Wang
 

More from Mu Chun Wang (20)

如何在有限資源下實現十年的後端服務演進
如何在有限資源下實現十年的後端服務演進如何在有限資源下實現十年的後端服務演進
如何在有限資源下實現十年的後端服務演進
 
深入淺出 autocomplete
深入淺出 autocomplete深入淺出 autocomplete
深入淺出 autocomplete
 
你畢業後要任職的軟體業到底都在做些什麼事
你畢業後要任職的軟體業到底都在做些什麼事你畢業後要任職的軟體業到底都在做些什麼事
你畢業後要任職的軟體業到底都在做些什麼事
 
網路服務就是一連串搜尋的集合體
網路服務就是一連串搜尋的集合體網路服務就是一連串搜尋的集合體
網路服務就是一連串搜尋的集合體
 
老司機帶你上手 PostgreSQL 關聯式資料庫系統
老司機帶你上手 PostgreSQL 關聯式資料庫系統老司機帶你上手 PostgreSQL 關聯式資料庫系統
老司機帶你上手 PostgreSQL 關聯式資料庫系統
 
使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能
使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能
使用 PostgreSQL 及 MongoDB 從零開始建置社群必備的按讚追蹤功能
 
Funliday 新創生活甘苦談
Funliday 新創生活甘苦談Funliday 新創生活甘苦談
Funliday 新創生活甘苦談
 
大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度
大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度
大解密!用 PostgreSQL 提升 350 倍的 Funliday 推薦景點計算速度
 
如何使用 iframe 製作一個易於更新及更安全的前端套件
如何使用 iframe 製作一個易於更新及更安全的前端套件如何使用 iframe 製作一個易於更新及更安全的前端套件
如何使用 iframe 製作一個易於更新及更安全的前端套件
 
pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題
pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題
pppr - 解決 JavaScript 無法被搜尋引擎正確索引的問題
 
模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構
模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構
模糊也是一種美 - 從 BlurHash 探討前後端上傳圖片架構
 
Google Maps 開始收費了該怎麼辦?
Google Maps 開始收費了該怎麼辦?Google Maps 開始收費了該怎麼辦?
Google Maps 開始收費了該怎麼辦?
 
Git 可以做到的事
Git 可以做到的事Git 可以做到的事
Git 可以做到的事
 
那些大家常忽略的 Cache-Control
那些大家常忽略的 Cache-Control那些大家常忽略的 Cache-Control
那些大家常忽略的 Cache-Control
 
如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化
如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化
如何利用 OpenAPI 及 WebHooks 讓老舊的網路服務也可程式化
 
如何與全世界分享你的 Library
如何與全世界分享你的 Library如何與全世界分享你的 Library
如何與全世界分享你的 Library
 
如何與 Git 優雅地在樹上唱歌
如何與 Git 優雅地在樹上唱歌如何與 Git 優雅地在樹上唱歌
如何與 Git 優雅地在樹上唱歌
 
API Blueprint - API 文件規範的三大領頭之一
API Blueprint - API 文件規範的三大領頭之一API Blueprint - API 文件規範的三大領頭之一
API Blueprint - API 文件規範的三大領頭之一
 
團體共同協作與版本管理 - 01認識共同協作
團體共同協作與版本管理 - 01認識共同協作團體共同協作與版本管理 - 01認識共同協作
團體共同協作與版本管理 - 01認識共同協作
 
Git 經驗分享
Git 經驗分享Git 經驗分享
Git 經驗分享
 

Recently uploaded

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

Connecting to the network

  • 1. Connecting to the Network Kewang
  • 2. Add Permissions <?xml version="1.0" encoding="utf-8"?> <manifest> ...... <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> ...... </manifest> at AndroidManifest.xml 2
  • 3. isConnected? private boolean isConnected() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { return true; } else { return false; } } 3
  • 4. Long IO accessing Activity.runOnUiThread(Runnable) View.post(Runnable) View.postDelayed(Runnable, long) Handler AsyncTask 4
  • 5. AsyncTask private class ProcessingTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { try { return downloadUrl(params[0]); } catch (IOException e) { return "無法讀取網頁"; worker thread } } @Override protected void onPostExecute(String result) { txtContent.setText(result); } main thread } 5
  • 6. downloadUrl private String downloadUrl(String myurl) { int len = 500; URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.connect(); int statusCode = conn.getResponseCode(); return streamToString(conn.getInputStream(), len); 6 }
  • 7. streamToString private String streamToString(InputStream stream, int len) { Reader reader = new InputStreamReader(stream, "UTF- 8"); char[] buffer = new char[len]; reader.read(buffer); return new String(buffer); } 7
  • 8. streamToImage private Bitmap streamToImage(InputStream stream) { return BitmapFactory.decodeStream(stream); } GET http://example.com/mitake.png 8
  • 9. Where is My IP? private String getIP() { for (Enumeration<NetworkInterface> en = NetworkInterface .getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inet = enumIpAddr.nextElement(); if (!inet.isLoopbackAddress() && inet instanceof Inet4Address) { return inet.getHostAddress().toString(); } } } return ""; } 9
  • 10. HttpClient & HttpURLConnection ● HttpClient ● stable ● few bugs ● large size ● HttpURLConnection ● easy to use ● gzip-support 10
  • 13. HttpClient & HttpURLConnection org.apache.http.cl java.net.HttpURL ient.HttpClient Connection 2.1, 2.2 a r(close method issue) 2.3 and r(difficult to maintain) a higher 13
  • 14. prior 2.2 to use HttpURLConnection private void disableConnectionReuseIfNecessary() { if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) { System.setProperty("http.keepAlive", "false"); } } 14
  • 15. 2.3 and higher, gzip-support getContentLength() is incorrect ● disable gzip-support ● use getInputStream's length 15
  • 16. disable gzip-support HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Accept-Encoding", "identity"); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.connect(); 16
  • 17. use getInputStream's length private String streamToString(InputStream stream) { Reader reader = new InputStreamReader(stream, "UTF- 8"); StringBuffer sb = new StringBuffer(); int length = 0; char c; while ((c = (char) reader.read()) != 65535) { length++; sb.append(c); } return sb.toString(); } 17
  • 18. References ● http://developer.android.com/training/basics/network-ops/connecting.html ● http://developer.android.com/reference/java/net/HttpURLConnection.html ● http://developer.android.com/reference/java/net/URLConnection.html ● http://developer.android.com/reference/java/net/package-summary.html ● http://developer.android.com/reference/android/net/ConnectivityManager.html ● http://developer.android.com/reference/android/net/NetworkInfo.html ● http://android-developers.blogspot.tw/2011/09/androids-http-clients.html ● http://android-developers.blogspot.tw/2009/05/painless-threading.html ● http://www.droidnova.com/get-the-ip-address-of-your-device,304.html ● https://developers.google.com/speed/articles/gzip 18
  • 19. 19