-
-
Save PhongHuynh93/7ee5c79feeabd61c993e13417a0bb24d to your computer and use it in GitHub Desktop.
check Network ConnectivityManager , connect to web service and return JSON HttpUURLConnection OkHttp Retrofit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sending and Managing Network Requests: | |
http://guides.codepath.com/android/Sending-and-Managing-Network-Requests | |
Core java: | |
. HttpUURLConnection: core java và android, low level, ta tự parse kết quả và tự làm request | |
Library: | |
. OkHttp(library của Android): http://square.github.io/okhttp/ | |
. http://loopj.com/android-async-http/ (library ) | |
. handle the entire process of sending and parsing network requests for us in a more robust and easy-to-use way. | |
. Retrofit | |
http://guides.codepath.com/android/Consuming-APIs-with-Retrofit | |
which uses OkHttp and makes it easier to make more RESTful API calls. | |
=> There can be a bit of a learning curve when using these libraries, so your best bet when first learning is to use Android Async Http Client. With OkHttp you also have to deal with the complexity of whether your callbacks need to be run on the main thread to update the UI, | |
######################################################################################################### | |
#Cachematters for networking | |
https://www.youtube.com/watch?v=7lxVqqWwTb0&list=PLWz5rJ2EKKc9CBxr3BVjPTPoDPLdPIFCE&index=11 | |
TH khi 1 thông tin trên mạng cần lấy thường xuyên -> cache sẽ tăng performance, nếu ta tự viết cách cache thì phải | |
chỉ 1 file cache lưu trên đĩa size bao nhiêu. Cache áp dúng mọi TH httprequest (tin hay image). | |
https://developer.android.com/samples/DisplayingBitmaps/src/com.example.android.displayingbitmaps/util/DiskLruCache.html?utm_campaign=android_series_#cachematters_for_networking_101315&utm_source=anddev&utm_medium=yt-annt | |
hay dơn giản hơn là sd thư viện có tích hợp networking + cache: | |
http://square.github.io/okhttp/ | |
https://developer.android.com/training/volley/index.html?utm_campaign=android_series_#cachematters_for_networking_101315&utm_source=anddev&utm_medium=yt-annt | |
http://square.github.io/picasso/ | |
http://stackoverflow.com/search?q=android+image+load+http | |
* Using the Network Traffic tool | |
https://developer.android.com/studio/profile/ddms.html#network?utm_campaign=android_series_#cachematters_for_networking_101315&utm_source=anddev&utm_medium=yt-annt | |
thấy khoảng thời gian, size của data transfer. | |
######################################################################################################### | |
Optimizing Network Request Frequencies | |
https://www.youtube.com/watch?v=nDHeuEM30ks&list=PLWz5rJ2EKKc9CBxr3BVjPTPoDPLdPIFCE&index=12 | |
chtr này nói về sync less: vd trong fb khi update new feed: | |
. khi pull to refresh: cần sync now. | |
. khi dag đợi server trả về or đang push data: ko cần sync. | |
Ta ko cần sync để hỏi server xem có tin mới ko, sẽ tối ưu hơn khi server có tin mới sẽ send cho ta -> | |
lúc đó mới cần sycn | |
Xem thêm về google cloud message: https://developers.google.com/cloud-messaging/ | |
Khi cần sync liên tục: cach tối ưu, sycn ko có tin mới thì thời gian sync tiếp theo x2, cứ thế. | |
Hay tìm hiểu xem hành động của con người(họ dang di độ, đi xe) đẻ xem liệu họ có cần sync ko | |
https://plus.google.com/+MagnusHyttsten/posts | |
vd nếu phone đang nằm chừng 8 tiếng mà đột nhien wake up và move thì ta biết là hãy bắt đầu sync đi. | |
hay nếu điện thoại đang cắm sạc (-> sync ko sao) ... -> các pattern này thì nhờ google api detect | |
GcmNetworkManager | |
https://developers.google.com/android/reference/com/google/android/gms/gcm/GcmNetworkManager | |
######################################################################################################### | |
KIEM TRA XEM CÓ ĐƯỜNG CONNECTION ĐẾN MỤC TIÊU KHÔNG TRƯỚC KHI TẠO KẾT NỐI TỚI MỤC TIÊU | |
<!--TODO 1 thêm quyền truy cập internet--> | |
<uses-permission android:name="android.permission.INTERNET" /> | |
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> | |
What's the difference between ACCESS_NETWORK_STATE and INTERNET? | |
http://stackoverflow.com/questions/19642032/whats-the-difference-between-access-network-state-and-internet | |
https://developer.android.com/reference/android/Manifest.permission.html#ACCESS_NETWORK_STATE | |
ACCESS_NETWORK_STATE: Allows applications to access information about networks | |
INTERNET: Allows applications to open network sockets. | |
In short, the INTERNET permission lets you use the internet, whereas ACCESS_NETWORK_STATE will just give you information about the network, such as whether you are connected to a network at all. | |
You can use either one without needing the other. If you don't check that you have a valid network connection before trying to use the Internet, your HTTP requests will simply fail. | |
-> You dont have to check if there is a connection or not, if there isnt the request will fail or whatever. If there is no internet the HTTP request will fail and you will jet some sort of exception that you will have to handle | |
Chú ý: Note that having an active network interface doesn't guarantee that a particular networked service is available or that the internet is actually connected. Network issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service. | |
######################################################################################################### | |
Determining and Monitoring the Connectivity Status | |
https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html | |
Check connect khi, check trước khi quyết đinh có sync hay ko, nếu sync phải kết nối tới internet và kết nối tới server đợi nó rất tốn time. | |
Determine if You Have an Internet Connection: There's no need to schedule an update based on an Internet resource if you aren't connected to the Internet. | |
Determine the Type of your Internet Connection: By querying the type of the active network, as shown below, you can alter your refresh rate based on the bandwidth available. Mobile data costs tend to be significantly higher than Wi-Fi, so in most cases, your app's update rate should be lower when on mobile connections. Similarly, downloads of significant size should be suspended until you have a Wi-Fi connection. | |
Monitor for Changes in Connectivity: Having disabled your updates, it's important that you listen for changes in connectivity in order to resume them once an Internet connection has been established. | |
Broadcast <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/> | |
Changes to a device's connectivity can be very frequent—this broadcast is triggered every time you move between mobile data and Wi-Fi. As a result, it's good practice to monitor this broadcast only when you've previously suspended updates or downloads in order to resume them. | |
=> check for Internet connectivity before beginning an update and, should there be none, suspend further updates until connectivity is restored. | |
######################################################################################################### | |
ConnectivityManager | |
https://developer.android.com/reference/android/net/ConnectivityManager.html | |
Class that answers queries about the state of network connectivity. It also notifies applications when network connectivity changes. Get an instance of this class by calling Context.getSystemService(Context.CONNECTIVITY_SERVICE). | |
The primary responsibilities of this class are to: | |
Monitor network connections (Wi-Fi, GPRS, UMTS, etc.) | |
Send broadcast intents when network connectivity changes | |
Attempt to "fail over" to another network when connectivity to a network is lost | |
Provide an API that allows applications to query the coarse-grained or fine-grained state of the available networks | |
Provide an API that allows applications to request and select networks for their data traffic | |
public class Connectivity { | |
/** | |
* Get the network info | |
* | |
* @param context | |
* @return | |
*/ | |
public static NetworkInfo getNetworkInfo(Context context) { | |
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); | |
return cm.getActiveNetworkInfo(); | |
} | |
/** | |
* Check if there is any connectivity | |
* | |
* @param context | |
* @return | |
*/ | |
public static boolean isConnected(Context context) { | |
NetworkInfo info = Connectivity.getNetworkInfo(context); | |
return (info != null && info.isConnected()); | |
} | |
/** | |
* Check if there is any connectivity to a Wifi network | |
* | |
* @param context | |
* @return | |
*/ | |
public static boolean isConnectedWifi(Context context) { | |
NetworkInfo info = Connectivity.getNetworkInfo(context); | |
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI); | |
} | |
/** | |
* Check if there is any connectivity to a mobile network | |
* | |
* @param context | |
* @return | |
*/ | |
public static boolean isConnectedMobile(Context context) { | |
NetworkInfo info = Connectivity.getNetworkInfo(context); | |
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE); | |
} | |
/** | |
* Check if there is fast connectivity | |
* | |
* @param context | |
* @return | |
*/ | |
public static boolean isConnectedFast(Context context) { | |
NetworkInfo info = Connectivity.getNetworkInfo(context); | |
return (info != null && info.isConnected() && Connectivity.isConnectionFast(info.getType(), info.getSubtype())); | |
} | |
/** | |
* Check if the connection is fast | |
* | |
* @param type | |
* @param subType | |
* @return | |
*/ | |
public static boolean isConnectionFast(int type, int subType) { | |
if (type == ConnectivityManager.TYPE_WIFI) { | |
return true; | |
} else if (type == ConnectivityManager.TYPE_MOBILE) { | |
switch (subType) { | |
case TelephonyManager.NETWORK_TYPE_1xRTT: | |
return false; // ~ 50-100 kbps | |
case TelephonyManager.NETWORK_TYPE_CDMA: | |
return false; // ~ 14-64 kbps | |
case TelephonyManager.NETWORK_TYPE_EDGE: | |
return false; // ~ 50-100 kbps | |
case TelephonyManager.NETWORK_TYPE_EVDO_0: | |
return true; // ~ 400-1000 kbps | |
case TelephonyManager.NETWORK_TYPE_EVDO_A: | |
return true; // ~ 600-1400 kbps | |
case TelephonyManager.NETWORK_TYPE_GPRS: | |
return false; // ~ 100 kbps | |
case TelephonyManager.NETWORK_TYPE_HSDPA: | |
return true; // ~ 2-14 Mbps | |
case TelephonyManager.NETWORK_TYPE_HSPA: | |
return true; // ~ 700-1700 kbps | |
case TelephonyManager.NETWORK_TYPE_HSUPA: | |
return true; // ~ 1-23 Mbps | |
case TelephonyManager.NETWORK_TYPE_UMTS: | |
return true; // ~ 400-7000 kbps | |
/* | |
* Above API level 7, make sure to set android:targetSdkVersion | |
* to appropriate level to use these | |
*/ | |
case TelephonyManager.NETWORK_TYPE_EHRPD: // API level 11 | |
return true; // ~ 1-2 Mbps | |
case TelephonyManager.NETWORK_TYPE_EVDO_B: // API level 9 | |
return true; // ~ 5 Mbps | |
case TelephonyManager.NETWORK_TYPE_HSPAP: // API level 13 | |
return true; // ~ 10-20 Mbps | |
case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8 | |
return false; // ~25 kbps | |
case TelephonyManager.NETWORK_TYPE_LTE: // API level 11 | |
return true; // ~ 10+ Mbps | |
// Unknown | |
case TelephonyManager.NETWORK_TYPE_UNKNOWN: | |
default: | |
return false; | |
} | |
} else { | |
return false; | |
} | |
} | |
} | |
######################################################################################################### | |
Cach khac1: // TODO: 5/20/2016 4 check internet connection by pinging to google | |
private Boolean isOnline() { | |
Runtime runtime = Runtime.getRuntime(); | |
try { | |
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8"); | |
int exitValue = ipProcess.waitFor(); | |
return (exitValue == 0); | |
} catch (IOException e) { e.printStackTrace(); } | |
catch (InterruptedException e) { e.printStackTrace(); } | |
return false; | |
} | |
######################################################################################################### | |
######################################################################################################### |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
TẠO KẾT NỐI ĐẾN MỤC TIÊU SAU KHI ĐÃ BIẾT CHÍNH XÁC LÀ ĐÃ KẾT NỐI ĐƯỢC | |
https://gist.github.com/PhongHuynh93/42be08bd07bd06926723ca1f3b0b4484 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment