I want to check if user has available connection to the internet and show Snackbar
for him or other custom action.
App's minSdk is 23 (Android 6.0).
Since Android 7.0 there were some changes to BroadcastReceiver
and receiving connection status. Now i have to use JobScheduler
and Service
to check connection status.
I've found tutorial here
But he is initializing JobScheduler
inside NetworkConnectionActivity
. I did this at the start of Application
class where other services are initialized (like FirebaseMessagingService
).
What I want to achieve is to implement ConnectivityReceiverListener
to multiple Activities in my App and override onNetworkConnectionChanged
to get info when connection is changed. I will make custom reaction to this status depends on current Activity
Problem with this solution: As I implement that listener in my MainActivity
it is not fired. But toast inside onNetworkConnectionChanged
in NetworkSchedulerService
was fired
Example Code:
class MainActivity : AppCompatActivity(), ConnectivityReceiver.ConnectivityReceiverListener{
var mConnectionSnackbar: Snackbar? = null
override fun onNetworkConnectionChanged(isConnected: Boolean) {
App.log("ConnectionChanged: $isConnected")
app.isConnected = isConnected
maybeShowConnectionSnackbar(isConnected)
}
fun maybeShowConnectionSnackbar(isConnected: Boolean){
if (isConnected){
mConnectionSnackbar?.dismiss()
} else {
if (mConnectionSnackbar == null){
mConnectionSnackbar = Snackbar.make(content, "Connection Lost", Snackbar.LENGTH_INDEFINITE)
}
}
}
**** onCreate and variable init ***
}
Function in Application
class:
private fun createConnectivityJobScheduler(){
val myJob = JobInfo.Builder(0, ComponentName(this, NetworkSchedulerService::class.java))
.setMinimumLatency(1000)
.setOverrideDeadline(2000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.build()
val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
jobScheduler.schedule(myJob)
}
try this
val serviceComponent = ComponentName(context, CallJob()::class.java)
val builder = JobInfo.Builder(0, serviceComponent)
builder.setMinimumLatency((30000).toLong())
builder.setOverrideDeadline((300000).toLong())
val jobScheduler = context.getSystemService(JobScheduler::class.java)
try {
jobScheduler.schedule(builder.build())
} catch (e: Exception) {
e.printStackTrace()
}
before that you need to check weather the scheduler was currently running or not..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.