首页 > 解决方案 > 设备与 PC 断开连接时连接失败

问题描述

我有一个 Android 应用程序,它使用 okhttp 库从服务器获取数据。它的版本在这里:https ://github.com/ertrzyiks/android-http-data-widget

class LoadData() : AsyncTask<Void, Void, String>() {
    override fun doInBackground(vararg params: Void?): String? {
        val client = OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .build()

        val url = URL("https://example.com/some/path")

        val request = Request.Builder()
            .url(url)
            .get()
            .build()

        try {
            val response = client.newCall(request).execute()
            val responseBody = response.body!!.string()

            return responseBody
        } catch (e: Exception) {
            return e.message
        }
    }
}

我还在清单文件中添加了互联网权限

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

我使用 USB 电缆将移动设备连接到我的计算机,使用 Android Studio 在该设备上运行应用程序,一切正常。发出请求,我可以看到响应。

当我断开 USB 电缆时,虽然我看到以下错误:

failed to connect to example.com/ip here (port 443) from /192.168.1.10 (port 41446) after 10000ms

当我使用 HttpUrlConnection 时也会出现此问题。

我的移动设备是三星 Galaxy S8,Android 版本是 9。

当我发出请求然后插入 USB 电缆时,它可以工作。所以显然我的应用程序只有在设备连接到 ADB 时才能访问互联网。我怎样才能解决这个问题?

我使用的库:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.squareup.okhttp3:okhttp:4.1.0'
    implementation 'com.fasterxml.jackson.core:jackson-core:2.0.1'
    implementation 'com.fasterxml.jackson.core:jackson-databind:2.9.8'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}

标签: androidhttpokhttp

解决方案


我的三星设备进入了节电模式,并选中了限制背景数据选项。此选项可防止后台应用程序使用 Wi-Fi 和移动数据。禁用此选项后,即使没有连接的调试器,我的小部件也可以访问 Internet 连接。

如何禁用此选项:

  1. 前往设置
  2. 设备保养
  3. 单击电池图标
  4. 电源模式
  5. 当前选择的电源模式(我有中等省电
  6. 取消选中限制后台数据
  7. 单击应用按钮

推荐阅读