java - 无法设置互联网连接的广播接收器,如下是我的代码

标签 java android broadcastreceiver android-broadcast android-broadcastreceiver

我已经在util包中完成了这个方法类,但问题是如何调用这个方法来检查互联网连接,请帮忙。 因为我的代码运行良好,没有错误

public class NetworkChangeReceiver extends BroadcastReceiver {

private static final String LOG_TAG = "NetworkChangeReceiver";
private boolean isConnected = false;

@Override
public void onReceive(Context context, Intent intent) {
    Log.v(LOG_TAG, "Receieved notification about network status");
    isNetworkAvailable(context);
}

private boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    if (!isConnected) {
                        Log.v(LOG_TAG, "Now you are connected to Internet!");
                        Toast.makeText(context, "Internet availablle via Broadcast receiver", Toast.LENGTH_SHORT).show();
                        isConnected = true;
                        // do your processing here ---
                        // if you need to post any data to the server or get
                        // status
                        // update from the server
                    }
                    return true;
                }
            }
        }
    }
    Log.v(LOG_TAG, "You are not connected to Internet!");
    Toast.makeText(context, "Internet NOT availablle via Broadcast receiver", Toast.LENGTH_SHORT).show();
    isConnected = false;
    return false;
}
}

最佳答案

Using broadcast receiver, your app will be automatically notified when there is a change in network connection.

   boolean isConnected = NetworkChangeReceiver.isNetworkAvailable(YourACTIVITY.this);
   System.out.println("STATUS"+isConnected );

关于java - 无法设置互联网连接的广播接收器,如下是我的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46883454/

相关文章:

java - 比较Hashmap下载excel中的数据

java - 如何在全屏模式下隐藏任务栏JavaFx

java - spring hibernate maven 项目出现 nosuchmethod 错误 InjectionMetadata

javascript - Android原生分享菜单: Detect supporting browsers

Android Market 订阅付费模式。如何?

android - Intent 和广播接收器

android - 如何处理android中每天触发的警报

java - 制作透明背景

android - 具有多个 mp3 文件问题的媒体播放器

android - 在 fragment BroadcastReceiver 上显示 progressDialog