Warum hat mein Workmanager -Arbeit beim Ausführen im Hintergrund nie eine Internetverbindung?
Posted: 04 Mar 2025, 00:00
Ich verwende Workmanager in meiner Android -Anwendung, um Hintergrundarbeiten zu erledigen. /> Ich kann es nicht zuverlässig auf meinem Pixel 7 -API 35 -Emulator zum Laufen bringen - Warum könnte das sein? AndroidManifest.xml :
-20S Delay ermöglicht es mir, vor der Arbeit woanders im Vordergrund zu gehen:
:
). Jetzt ...
Code: Select all
< /code>
MainActivity.kt
Code: Select all
val oneTimeRequest = OneTimeWorkRequestBuilder()
.setInitialDelay(20, TimeUnit.SECONDS)
.build()
WorkManager.getInstance(context)
.enqueue(oneTimeRequest)
< /code>
Worker.kt
Code: Select all
class LocationWorker(
context: Context,
workerParams: WorkerParameters
): CoroutineWorker(context, workerParams) {
override suspend fun doWork(): Result {
// ... (1. Getting the location and storing it in a local database)
if (isNetworkAvailable(applicationContext)) {
// Always get here when the app is visible on-screen
Log.d("LocationWorker", "Uploading location.")
// ... (2. Uploading the data from the database to a remote API)
} else {
// Always get here when not having the app on-screen
Log.d("LocationWorker", "Network not available.")
}
}
private fun isNetworkAvailable(context: Context): Boolean {
val connectivityManager = context.getSystemService(ConnectivityManager::class.java)
val network = connectivityManager.activeNetwork ?: return false
val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false
return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
}
< /code>
I ensured that the device itself has WiFi enabled, the app is not stripped of permissions when unused and all permissions are allowed.
Minimum SDK version is 29 (Android 10).
Minimal demo to reproduce the problem
I've created a minimal example of the [url=viewtopic.php?t=15738]problem[/url] on GitHub.
The second commit shows all that there is to the application (plus a README.md