我的应用程序基于互联网。当我的应用程序运行时没有互联网时,我需要显示一个警报对话框。因此,我创建了一个BroadcastReceiver
并将其注册到MainActivity中。在每个活动或片段的顶部,我都无法显示带有烤面包的互联网,但是警报对话框仅在MainActivity中显示。当我处于另一个活动或片段中并且网络断开连接时,它在我当前的活动中不显示警报对话框,但在MainActivity中显示一个警报对话框,似乎上下文是MainActivity的上下文。我的代码在这里NetworkUtil.java
作为实用程序类。
//NetworkUtil.java
public class NetworkUtil {
public static final int TYPE_WIFI = 1;
public static final int TYPE_MOBILE = 2;
public static final int TYPE_NOT_CONNECTED = 0;
public static final int NETWORK_STATUS_NOT_CONNECTED = 0;
public static final int NETWORK_STATUS_WIFI = 1;
public static final int NETWORK_STATUS_MOBILE = 2;
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static int getConnectivityStatusString(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
int status = 0;
if (conn == NetworkUtil.TYPE_WIFI) {
status = NETWORK_STATUS_WIFI;
} else if (conn == NetworkUtil.TYPE_MOBILE) {
status = NETWORK_STATUS_MOBILE;
} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
status = NETWORK_STATUS_NOT_CONNECTED;
}
return status;
}
}
我的BroadcastReceiver
CheckConnectivity
public class CheckConnectivity extends BroadcastReceiver{
@Override
public void onReceive(final Context context, final Intent intent) {
int status = NetworkUtil.getConnectivityStatusString(context);
if ("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())) {
if (status == NetworkUtil.NETWORK_STATUS_NOT_CONNECTED) {
new SweetAlertDialog(context, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("No internet! Check your network connection")
.show();
Toast.makeText(context, "Internet Connection Lost", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Internet Connected", Toast.LENGTH_LONG).show();
}
}
}
}
MainActivity
,其中已注册BroadcastReceiver。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BroadcastReceiver networkChangeReceiver=new CheckConnectivity();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkChangeReceiver, intentFilter);
}
}
答案 0 :(得分:1)
面向Android 7.0(API级别24)及更高版本的应用程序如果在清单中声明了广播接收器,则不会收到CONNECTIVITY_ACTION广播。如果应用向Context.registerReceiver()注册了自己的BroadcastReceiver,并且该上下文仍然有效,则它们仍将接收CONNECTIVITY_ACTION广播。
因此,以下是所有设备的完整解决方案。
创建一个通用类来检查设备是否连接到网络状态。
class ConnectivityHelper() {
companion object {
fun isConnectedToNetwork(): Boolean {
val connectivityManager: ConnectivityManager =
CenceApplication.cenceAppContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo = connectivityManager.activeNetworkInfo
if (networkInfo != null) {
return networkInfo.isConnected
}
return false
}
}
}
现在要检查牛轧糖以下的设备: 1.您需要在清单中设置广播接收器 2.倾听变化 3.通知您的基本活动。
注意:基本活动是普通活动,它由应用程序中的所有其他活动扩展,而基本活动由AppCompatActivity()扩展
在清单中:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<receiver
android:name=".Utility.NetworkChangeReceiver"
android:label="NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
广播接收器类别:
class NetworkChangeReceiver : BroadcastReceiver() {
companion object {
lateinit var networkChangeListener: NetworkChangeListener
}
override fun onReceive(context: Context?, intent: Intent?) {
networkChangeListener.networkStateChanged(ConnectivityHelper.isConnectedToNetwork())
}
}
创建一个界面以在基本活动中进行通知:
interface NetworkChangeListener {
fun networkStateChanged(boolean: Boolean)
}
应用程序中的初始化界面:
class YourApplication:Application() {
companion object {
lateinit var appContext: Context
}
override fun onCreate() {
super.onCreate()
appContext = this
}
fun initializeNetworkListener(listener:NetworkChangeListener){
NetworkChangeReceiver.networkChangeListener = listener
}
}
BasActivity,它实现了接口并在MutableLivedata的帮助下在网络中断时通知任何活动/碎片:
class BaseActivity : AppCompatActivity(), NetworkChangeListener {
private var networkLiveData: MutableLiveData<Boolean> = MutableLiveData()
private lateinit var snackbar: Snackbar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupNetworkState()
}
private fun setupNetworkState() {
networkLiveData.postValue(checkNetworkState())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val connectivityManager: ConnectivityManager =
this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network?) {
super.onAvailable(network)
networkLiveData.postValue(checkNetworkState())
}
override fun onLost(network: Network?) {
super.onLost(network)
networkLiveData.postValue(checkNetworkState())
}
})
} else {
(application as YourApplication).initializeNetworkListener(this@BaseActivity)
}
}
override fun networkStateChanged(boolean: Boolean) {
networkLiveData.postValue(boolean)
}
fun getNetworkStateUpdate(): MutableLiveData<Boolean> {
return networkLiveData
}
fun checkNetworkState(): Boolean {
return ConnectivityHelper.isConnectedToNetwork()
}
现在进入**您的任何活动/片段的最后一步****: 在** onCreate()方法中,
getNetworkStateUpdate().observe(this, object : Observer<Boolean> {
val snackbar = Snackbar
.make(
mIndMainParentLayout, "You're Offline",
Snackbar.LENGTH_INDEFINITE
)
override fun onChanged(t: Boolean?) {
if (!t!!) {
snackbar.show()
} else {
snackbar.dismiss()
}
}
})
答案 1 :(得分:0)
尝试以下代码:
public static boolean isConnectedToInternet(Context context){
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null){
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if (info != null){
if (info.getType() == ConnectivityManager.TYPE_WIFI){
return true;
}else if (info.getType() == ConnectivityManager.TYPE_MOBILE){
return true;
}
}
}
return false;
}
if (isConnectedToInternet() {
Toast.makeText(context, "Internet Connected", Toast.LENGTH_LONG).show();
}else {
new SweetAlertDialog(MainActivity.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("No internet! Check your network connection")
.show();
Toast.makeText(context, "Internet Connection Lost", Toast.LENGTH_LONG).show();
}
答案 2 :(得分:0)
在每种活动的BroadcastReceiver
方法中注册onResume
,然后在onPause
中注销。现在,您仅在MainActivity
中注册,但是MainActivity
如果在后台,则无法显示AlertDialog
。