android - 设备与 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'
}
解决方案
我的三星设备进入了节电模式,并选中了限制背景数据选项。此选项可防止后台应用程序使用 Wi-Fi 和移动数据。禁用此选项后,即使没有连接的调试器,我的小部件也可以访问 Internet 连接。
如何禁用此选项:
- 前往设置
- 设备保养
- 单击电池图标
- 电源模式
- 当前选择的电源模式(我有中等省电)
- 取消选中限制后台数据
- 单击应用按钮
推荐阅读
- php - PHP - PHPSESSID 欺骗
- thread-safety - 将 Observables 合并到一个 Observable 时是 Observable doOnNext 线程安全的吗
- laravel - 使用 laravel vue js 在 axios 成功响应上关闭父模式并打开子模式
- node.js - 将参数传递给 Node.js 程序
- postgresql - 使用 Liquibase、postgreSQL 和序列插入新数据
- ios - sizeWithAttributes 让我获得不同的 CGSize 宽度和高度
- oracle - 在 Oracle PL/SQL 中使用密码保护 PDF 文件
- oracle - 将 Oracle 分区和存储选项与 Redgate 模式比较一起使用失败
- r - 如何解决 R 中未找到数据框 bbject 错误
- ios - Swift 4 Rotation 跳回