Skip to content

Commit

Permalink
Added un metered network connection
Browse files Browse the repository at this point in the history
  • Loading branch information
tonyofrancis committed Aug 17, 2020
1 parent 65421a5 commit c6b58fb
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
6 changes: 5 additions & 1 deletion fetch2/src/main/java/com/tonyodev/fetch2/NetworkType.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ enum class NetworkType(val value: Int) {
ALL(0),

/** Indicates that a download can be downloaded only on wifi networks.*/
WIFI_ONLY(1);
WIFI_ONLY(1),

/** Indicates that a download can be downloaded only on an unmetered connection.*/
UNMETERED(2);

companion object {

Expand All @@ -25,6 +28,7 @@ enum class NetworkType(val value: Int) {
-1 -> GLOBAL_OFF
0 -> ALL
1 -> WIFI_ONLY
2 -> UNMETERED
else -> ALL
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import android.net.NetworkRequest
import android.os.Build
import com.tonyodev.fetch2.NetworkType
import com.tonyodev.fetch2core.isNetworkAvailable
import com.tonyodev.fetch2core.isOnMeteredConnection
import com.tonyodev.fetch2core.isOnWiFi
import java.net.HttpURLConnection
import java.net.URL
Expand Down Expand Up @@ -102,6 +103,9 @@ class NetworkInfoProvider constructor(private val context: Context,
if (networkType == NetworkType.WIFI_ONLY && context.isOnWiFi()) {
return true
}
if (networkType == NetworkType.UNMETERED && !context.isOnMeteredConnection()) {
return true
}
if (networkType == NetworkType.ALL && context.isNetworkAvailable()) {
return true
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ package com.tonyodev.fetch2core

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.os.Build


fun Context.isOnWiFi(): Boolean {
Expand All @@ -16,6 +18,27 @@ fun Context.isOnWiFi(): Boolean {
}
}

fun Context.isOnMeteredConnection(): Boolean {
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (Build.VERSION.SDK_INT >= 16) {
cm.isActiveNetworkMetered
} else {
val info: NetworkInfo = cm.activeNetworkInfo ?: return true
when (info.type) {
ConnectivityManager.TYPE_MOBILE,
ConnectivityManager.TYPE_MOBILE_DUN,
ConnectivityManager.TYPE_MOBILE_HIPRI,
ConnectivityManager.TYPE_MOBILE_MMS,
ConnectivityManager.TYPE_MOBILE_SUPL,
ConnectivityManager.TYPE_WIMAX -> true
ConnectivityManager.TYPE_WIFI,
ConnectivityManager.TYPE_BLUETOOTH,
ConnectivityManager.TYPE_ETHERNET -> false
else -> true
}
}
}

fun Context.isNetworkAvailable(): Boolean {
val manager = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetworkInfo = manager.activeNetworkInfo
Expand Down

0 comments on commit c6b58fb

Please sign in to comment.