在连接改变状态广播

时间:2018-05-04 13:13:53

标签: java android networking

在告诉我我的帖子已经得到解答之前,我在这个论坛上使用了一个解决方案,但不知道它对我有用..

我的问题:我想在打开或关闭网络连接时更改图像

为此,我做了一个extendsReceiver类,它扩展了BroadcastReceiver,它可以通知我的主类关于网络状态的变化。

public class ConnectivityReceiver
    extends BroadcastReceiver {

public static ConnectivityReceiverListener connectivityReceiverListener;

public ConnectivityReceiver() {
    super();
}

@Override
public void onReceive(Context context, Intent arg1) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null
            && activeNetwork.isConnectedOrConnecting();

    if (connectivityReceiverListener != null) {
        connectivityReceiverListener.onNetworkConnectionChanged(isConnected);
    }
}

public static boolean isConnected() {
    ConnectivityManager
            cm = (ConnectivityManager) MyApplication.getInstance().getApplicationContext()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null
            && activeNetwork.isConnectedOrConnecting();
}


public interface ConnectivityReceiverListener {
    void onNetworkConnectionChanged(boolean isConnected);
}
}

当我调用网络状态的手动检查时,这确实有效,但看起来我无法在网络更改状态时通知我的MainActivity。

MainActivity(代码的一部分):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    username_inputed = false;
    responseFromRequest = "";
    username_input = (EditText) findViewById(R.id.username_input);
    confirm_usrname = (ImageButton) findViewById(R.id.next_btn_username);
    passwd_input = (EditText) findViewById(R.id.password_input);
    login = (ImageButton) findViewById(R.id.next_btn_passwd);
    errorLog = (TextView) findViewById(R.id.logError);
    wifi_disp = (ImageView) findViewById(R.id.wifi_prompt);
    checkConnection();
}
private void checkConnection(){
    boolean isConnected = ConnectivityReceiver.isConnected();
    setWifiDisplay(isConnected);
}
@Override
protected void onResume(){
    super.onResume();
    //Register connection status listener
    MyApplication.getInstance().setConnectivityListener(this);
}
@Override
public void onNetworkConnectionChanged(boolean isConnected){
    setWifiDisplay(isConnected);
}
public void setWifiDisplay(boolean wifi){
    connection = wifi;
    if(wifi){
        wifi_disp.setImageResource(R.drawable.wifi_on);
    }else wifi_disp.setImageResource(R.drawable.wifi_off);
}

1 个答案:

答案 0 :(得分:1)

这不是一个完整的答案,但我认为您应该阅读有关向接收方发送广播的sendBroadcast(Intent)方法,您还应该在活动或清单文件中注册您的接收方。