假設今天我們要做一個網路連線的請求, 如果使用者按下 button 你的 app 不管三七二十一就直接去做連線,這樣是很糟的~
運氣好一點你的 function return false 或者 catch exception,歹運的話就等等等等等等到 timeout,為了避免這種運氣差的狀況,你需要在開始連線前先檢查一下使用者的裝置到底有沒有連上網路。
我們可以使用 ConnectivityManager 取得 NetworkInfo 來查查目前裝置的網路狀態,包含目前是使用何種連線方式、網路是否連接、是否漫遊中……等等,應有盡有,簡單一點的話用 NetworkInfo.isConnectedOrConnecting() 就妥當了,以下是範例。
public boolean isOK() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnectedOrConnecting();
}
而要使用這個功能呢,需要在 manifest 加入以下 permisiion
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Reference:
How to check internet access on Android? InetAddress never timeouts…
Written with StackEdit.
I'm eager to get your advice on...
回覆刪除Agen Joker123
Slot Joker123
Bandar Joker123
Tembak Ikan Joker123
Agen Tembak Ikan Joker123
I'm eager to get your advice on...
回覆刪除Jadwalbola.info
Tumbuhanberkhasiat.web.id
game joker123
download joker123
login joker123
Thanks for getting in touch
回覆刪除daftar joker123
joker 123
liga inggris
jenis tumbuhan berkhasiat
joker338
Hope this email finds you well
回覆刪除joker123
agen play338 terbaik dan terpercaya
bandar joker338 terbaik indonesia
Joker123
Agen Joker123
It's great to hear from you
回覆刪除joker slot
game joker123
login joker123
main joker123
daftar joker123
Thank you for your help
回覆刪除daftar joker123
login joker123
download joker123
slot joker123
slot joker123
Thanks for the quick response
回覆刪除download joker123
login joker123
daftar joker123
bandar joker123
agen joker123
I'm eager to get your advice on...
回覆刪除joker123
slot joker123
daftar joker123
login joker123
download joker123
I hope you enjoyed your weekend
回覆刪除joker123
agen joker123
bandar joker123