连接管理器或HttpUrl连接是否阻止漫游网络下载文件?

时间:2018-07-09 14:32:17

标签: android networking restriction roaming

我一直在尝试编辑模板应用程序。这是一个墙纸应用程序,可以从在线上传的JSON下载图像。

在WIFI或移动网络上,文件下载正常。 但是,一旦网络更改为漫游状态,文件就不会下载。

我对此很陌生,不了解在修改它的代码中查找的位置并摆脱了这个问题。

该应用程序使用常规的ConnectivityManager,SSLSocketFactory和HttpUrlConnection来访问Internet并下载文件。

如果有人可以指导我解决该问题的目标。 谢谢。

这是它的开始-

  if (downloadable && isNetworkAvailable && actuallyComplies) {
            findViewById<RelativeLayout>(R.id.download_container).setOnClickListener {
                doItemClick(DOWNLOAD_ACTION_ID)
            }
}

连接WIFI后,点击下载按钮,打开进度对话框,然后下载文件。在“漫游网络”中,对话框打开,但没有加载任何内容,没有下载任何内容,它会一直保留在那里。

'downloadable'和'actuallyComplies'变量与互联网连接无关。

isNetworkAvailable链接到具有以下代码的外部库。

inline val Context.isNetworkAvailable: Boolean
    @SuppressLint("MissingPermission")
    get() {
        val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val activeNetworkInfo = connectivityManager.activeNetworkInfo
        return activeNetworkInfo?.isConnectedOrConnecting ?: false
    }

doItemClick(DOWNLOAD_ACTION_ID),显示此代码-

抽象类BaseWallpaperActionsActivity:ActivityWFragments(){

companion object {
    const val DOWNLOAD_ACTION_ID = 1
    const val APPLY_ACTION_ID = 2
}

private var actionDialog: MaterialDialog? = null
internal var wallActions: WallpaperActionsDialog? = null

internal abstract var wallpaper: Wallpaper?
internal abstract val allowBitmapApply: Boolean

override fun autoTintStatusBar(): Boolean = true
override fun autoTintNavigationBar(): Boolean = true

private val request by lazy {
    permissionsBuilder(Manifest.permission.WRITE_EXTERNAL_STORAGE).build()
}

override fun onDestroy() {
    super.onDestroy()
    try {
        request.detachAllListeners()
    } catch (e: Exception) {
    }
}

open fun doItemClick(actionId: Int) {
    when (actionId) {
        DOWNLOAD_ACTION_ID -> downloadWallpaper(false)
        APPLY_ACTION_ID -> downloadWallpaper(true)
    }
}

fun requestStoragePermission(explanation: String, whenAccepted: () -> Unit) {
    try {
        request.detachAllListeners()
    } catch (e: Exception) {
    }
    request.listeners {
        onAccepted { whenAccepted() }
        onDenied { showSnackbar(R.string.permission_denied, Snackbar.LENGTH_LONG) }
        onPermanentlyDenied {
            showSnackbar(R.string.permission_denied_completely, Snackbar.LENGTH_LONG)
        }
        onShouldShowRationale { _, nonce -> showPermissionInformation(explanation, nonce) }
    }
    request.send()
}

@SuppressLint("NewApi")
private fun downloadWallpaper(toApply: Boolean) {
    if (isNetworkAvailable) {
        requestStoragePermission(getString(R.string.permission_request, getAppName())) {
            checkIfFileExists(toApply)
        }
    } else {
        if (toApply && allowBitmapApply) showWallpaperApplyOptions(null)
        else showNotConnectedDialog()
    }
}

private fun showPermissionInformation(
    explanation: String,
    nonce: PermissionNonce
                                     ) {
    showSnackbar(explanation, Snackbar.LENGTH_LONG) {
        setAction(R.string.allow) {
            dismiss()
            nonce.use()
        }
    }
}

private fun checkIfFileExists(toApply: Boolean) {
    wallpaper?.let {
        properlyCancelDialog()
        val folder = File(configs.downloadsFolder)
        folder.mkdirs()
        val extension = it.url.substring(it.url.lastIndexOf("."))
        var correctExtension = getWallpaperExtension(extension)
        val fileName = it.name.formatCorrectly().replace(" ", "_")
        if (toApply) correctExtension = "_temp$correctExtension"
        val dest = File(folder, fileName + correctExtension)
        if (dest.exists()) {
            actionDialog = mdDialog {
                content(R.string.file_exists)
                negativeText(R.string.file_replace)
                positiveText(R.string.file_create_new)
                onPositive { _, _ ->
                    val time = getCurrentTimeStamp().formatCorrectly().replace(" ", "_")
                    val newDest = File(folder, fileName + "_" + time + correctExtension)
                    if (toApply) showWallpaperApplyOptions(newDest)
                    else startDownload(newDest)
                }
                onNegative { _, _ ->
                    if (toApply) showWallpaperApplyOptions(dest)
                    else startDownload(dest)
                }
            }
            actionDialog?.show()
        } else {
            if (toApply) showWallpaperApplyOptions(dest)
            else startDownload(dest)
        }
    }
}

private fun startDownload(dest: File) {
    wallpaper?.let {
        properlyCancelDialog()
        wallActions = WallpaperActionsDialog.create(this, it, dest)
        wallActions?.show(this)
    }
}

fun reportWallpaperDownloaded(dest: File) {
    sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(dest)))
    runOnUiThread {
        properlyCancelDialog()
        showSnackbar(
            getString(R.string.download_successful, dest.toString()),
            Snackbar.LENGTH_LONG) {
            setAction(
                R.string.open, {
                dest.getUri(context)?.let { openWallpaper(it) }
            })
        }
    }
}

@SuppressLint("SimpleDateFormat")
private fun getCurrentTimeStamp(): String {
    val sdfDate = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    return sdfDate.format(Date())
}

private fun getWallpaperExtension(currentExt: String): String {
    val validExtensions = arrayOf(".jpg", ".jpeg", ".png")
    validExtensions.forEach {
        if (currentExt.contains(it, true)) return it
    }
    return ".png"
}

private fun showWallpaperApplyOptions(dest: File?) {
    properlyCancelDialog()
    val options = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        arrayListOf(
            getString(R.string.home_screen),
            getString(R.string.lock_screen),
            getString(R.string.home_lock_screen))
    } else {
        arrayListOf(getString(R.string.home_lock_screen))
    }
    if (isNetworkAvailable && dest != null)
        options.add(getString(R.string.apply_with_other_app))

    actionDialog = mdDialog {
        title(R.string.apply_to)
        items(options)
        itemsCallback { _, _, position, _ ->
            val rightPosition =
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) position + 2 else position
            if (dest != null) {
                applyWallpaper(
                    dest, rightPosition == 0, rightPosition == 1, rightPosition == 2,
                    rightPosition == 3)
            } else {
                if (allowBitmapApply)
                    applyBitmapWallpaper(
                        rightPosition == 0, rightPosition == 1, rightPosition == 2,
                        rightPosition == 3)
            }
        }
    }
    actionDialog?.show()
}

abstract fun applyBitmapWallpaper(
    toHomeScreen: Boolean, toLockScreen: Boolean, toBoth: Boolean,
    toOtherApp: Boolean
                                 )

private fun applyWallpaper(
    dest: File,
    toHomeScreen: Boolean, toLockScreen: Boolean, toBoth: Boolean,
    toOtherApp: Boolean
                          ) {
    wallpaper?.let {
        properlyCancelDialog()
        wallActions = WallpaperActionsDialog.create(
            this, it, dest, arrayOf(toHomeScreen, toLockScreen, toBoth, toOtherApp))
        wallActions?.show(this)
    }
}

fun showWallpaperAppliedSnackbar(
    toHomeScreen: Boolean, toLockScreen: Boolean,
    toBoth: Boolean
                                ) {
    properlyCancelDialog()
    showSnackbar(
        getString(
            R.string.apply_successful,
            getString(
                when {
                    toBoth -> R.string.home_lock_screen
                    toHomeScreen -> R.string.home_screen
                    toLockScreen -> R.string.lock_screen
                    else -> R.string.empty
                }).toLowerCase()), Snackbar.LENGTH_LONG)
}

private var file: File? = null

fun applyWallpaperWithOtherApp(dest: File) {
    try {
        dest.getUri(this)?.let {
            file = dest
            val setWall = Intent(Intent.ACTION_ATTACH_DATA)
            setWall.setDataAndType(it, "image/*")
            setWall.putExtra("mimeType", "image/*")
            setWall.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            startActivityForResult(
                Intent.createChooser(setWall, getString(R.string.apply_with_other_app)),
                WallpaperActionsDialog.TO_OTHER_APP_CODE)
        } ?: dest.delete()
    } catch (e: Exception) {
        FL.e(e.message)
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == WallpaperActionsDialog.TO_OTHER_APP_CODE) {
        try {
            file?.delete()
            file = null
        } catch (e: Exception) {
            FL.e(e.message)
        }
    }
}

private fun showNotConnectedDialog() {
    properlyCancelDialog()
    actionDialog = mdDialog {
        title(R.string.muzei_not_connected_title)
        content(R.string.not_connected_content)
        positiveText(android.R.string.ok)
    }
    actionDialog?.show()
}

internal fun properlyCancelDialog() {
    wallActions?.stopActions()
    wallActions?.dismiss(this)
    wallActions = null
    actionDialog?.dismiss()
    actionDialog = null
}

private fun showSnackbar(
    @StringRes text: Int,
    duration: Int,
    defaultToToast: Boolean = false,
    settings: Snackbar.() -> Unit = {}
                        ) {
    showSnackbar(getString(text), duration, defaultToToast, settings)
}

abstract fun showSnackbar(
    text: String,
    duration: Int,
    defaultToToast: Boolean = false,
    settings: Snackbar.() -> Unit = {}
                         )

override fun startActivityForResult(intent: Intent?, requestCode: Int) {
    intent?.putExtra(REQUEST_CODE, requestCode)
    super.startActivityForResult(intent, requestCode)
}

@SuppressLint("RestrictedApi")
override fun startActivityForResult(intent: Intent?, requestCode: Int, options: Bundle?) {
    intent?.putExtra(REQUEST_CODE, requestCode)
    super.startActivityForResult(intent, requestCode, options)
}

}

这是URL请求代码-

object FramesUrlRequests {     有趣的requestJson(url:String):字符串{

    val result = StringBuilder()
    val urlConnection: HttpURLConnection? = buildHttpUrlConnection(url)
    urlConnection ?: return result.toString()

    try {
        val ins = BufferedInputStream(urlConnection.inputStream)
        val reader = BufferedReader(InputStreamReader(ins))
        var line: String? = null
        while ({ line = reader.readLine(); line }() != null) {
            result.append(line)
        }
        ins.close()
        reader.close()
    } catch (e: Exception) {
        FL.e("Error", e)
    } finally {
        urlConnection.disconnect()
    }
    return result.toString()
}

fun requestFileInfo(url: String, onlySize: Boolean): WallpaperInfo {

    var info = WallpaperInfo(0, Dimension(0, 0))
    val urlConnection: HttpURLConnection? = buildHttpUrlConnection(url)
    urlConnection ?: return info

    try {
        info = if (onlySize) {
            WallpaperInfo(urlConnection.contentLength.toLong(), Dimension(0L, 0L))
        } else {
            val options = BitmapFactory.Options()
            options.inJustDecodeBounds = true
            val ins = urlConnection.inputStream
            BitmapFactory.decodeStream(ins, null, options)
            val size = urlConnection.connectTimeout.toLong()
            ins.close()
            WallpaperInfo(
                size, Dimension(options.outWidth.toLong(), options.outHeight.toLong()))
        }
    } catch (e: Exception) {
        FL.e("Error", e)
    } finally {
        urlConnection.disconnect()
    }
    return info
}

private fun buildHttpUrlConnection(url: String): HttpURLConnection? {
    return (if (url.matches("^(https?)://.*$".toRegex())) {
        (URL(url).openConnection() as HttpsURLConnection).apply {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
                sslSocketFactory = FramesSocketFactory()
        }
    } else {
        URL(url).openConnection() as HttpURLConnection
    }).apply {
        connectTimeout = 20000
        readTimeout = 20000
    }
}

}

很显然,丢失的代码(例如导入和其他内容)已正确完成。 可以在WIFI甚至移动网络上很好地下载文件。 但不在漫游蜂窝网络上。

这仅在此APP中发生。在其他任何地方都没有。

因此,我只需要帮助才能知道故障可能在哪里。 谢谢。

0 个答案:

没有答案