我想创建一个Android服务,它会在断开连接并再次重新连接互联网时通知主要活动。我有以下检查互联网连接的功能:。
private boolean haveInternet(){
NetworkInfo info=(NetworkInfo)((ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if(info==null || !info.isConnected()){
return false;
}
if(info.isRoaming()){
//here is the roaming option you can change it if you want to disable internet while roaming, just return false
return true;
}
return true;
}
但我想知道如何在服务中使用它。
答案 0 :(得分:26)
服务专为长期运行任务而设计。
您应该使用BroadcastReceiver
:
这是我用来监控网络状态进入主Activity的示例方法:
private void installListener() {
if (broadcastReceiver == null) {
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
NetworkInfo info = (NetworkInfo) extras
.getParcelable("networkInfo");
State state = info.getState();
Log.d("InternalBroadcastReceiver", info.toString() + " "
+ state.toString());
if (state == State.CONNECTED) {
onNetworkUp();
} else {
onNetworkDown();
}
}
};
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
}
}
记得在onDestroy事件发生时调用unregisterReceiver
希望得到这个帮助。
答案 1 :(得分:0)
这是 Kotlin版本,遵循Francesco Laurita的解决方案:
private val broadcastReceiver by lazy {
NetworkListener.create({
btnOnlineVideos.visibility = View.VISIBLE
}, {
btnOnlineVideos.visibility = View.GONE
})
}
override fun onResume() {
super.onResume()
NetworkListener.register(this, broadcastReceiver)
}
override fun onPause() {
super.onPause()
NetworkListener.unregister(this, broadcastReceiver)
}
为此,我只需覆盖onResume
和onPause
方法,即可注册和注销BroadcastReceiver
。
这是如何工作的?
我创建了以下类,该类有助于初始化,注册和注销BroadcastReceiver
。这样,就无需重复大多数样板代码。
package com.programacionymas.app.services
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.os.Parcelable
import android.util.Log
object NetworkListener {
fun create(onNetworkUp: () -> Unit, onNetworkDown: () -> Unit): BroadcastReceiver {
return object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
intent.extras?.getParcelable<Parcelable>("networkInfo")?.let {
val info = it as NetworkInfo
val state: NetworkInfo.State = info.state
Log.d("BroadcastReceiver", "$info $state")
if (state === NetworkInfo.State.CONNECTED) {
onNetworkUp()
} else {
onNetworkDown()
}
}
}
}
}
fun register(context: Context, broadcastReceiver: BroadcastReceiver) {
val intentFilter = IntentFilter()
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
context.registerReceiver(broadcastReceiver, intentFilter)
}
fun unregister(context: Context, broadcastReceiver: BroadcastReceiver) {
context.unregisterReceiver(broadcastReceiver)
}
}
如果只需要为一种状态执行语句,则也可以传递一个null
匿名函数:
private val broadcastReceiver by lazy {
NetworkListener.create(null, {
toast(getString(R.string.check_your_internet))
finish()
})
}
并在create
方法中将参数声明为可选参数:
fun create(onNetworkUp: (()->Unit)?, onNetworkDown: (()->Unit)?): BroadcastReceiver {/* ... */}
以及仅在将函数作为参数发送时才调用这些函数:
if (state === NetworkInfo.State.CONNECTED) {
onNetworkUp?.invoke()
} else {
onNetworkDown?.invoke()
}