Reputation: 386
I have an Android app which fetches data from the server using okhttp library. It's versioned here: 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
}
}
}
I also added the internet permission to my manifest file
<uses-permission android:name="android.permission.INTERNET"/>
I connect the mobile device to my computer with USB cable, run application on that device using Android Studio and everything works properly. The request is issued and I can see the response.
When I disconnect USB cable though I see the following error:
failed to connect to example.com/ip here (port 443) from /192.168.1.10 (port 41446) after 10000ms
The issue occurs also when I use HttpUrlConnection.
My mobile device is Samsung Galaxy S8, the Android version is 9.
When I issue a request and then plug USB cable, it works. So apparently my app can access internet only when the device is connected to ADB. How can I fix this?
The libraries I use:
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'
}
Upvotes: 0
Views: 662
Reputation: 386
My Samsung device was put in a battery saving mode with Restrict background data option checked. This option prevents background apps from using Wi-Fi and mobile data. Once I disabled this option, my widget has access to the internet connection even without a connected debugger.
How to disable this option:
Upvotes: 0