-1

大家好,我正在构建一个应用程序,我只想在设备失去连接时通知用户,无论是移动数据还是 wifi。

到目前为止,我已经使用了这种方法:

private void setupReceiver() {
        CheckNetworkStatusReceiver receiver = new CheckNetworkStatusReceiver();
        registerReceiver(receiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
    }

和我的接收者:

public class CheckNetworkStatusReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null){
            Log.e("Action ",intent.getAction());
            if(intent.getAction().equalsIgnoreCase("android.net.conn.CONNECTIVITY_CHANGE")) {
                Toast.makeText(context, "Connection changed", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

它工作正常,但问题是当它连接到网络时,吐司也会显示,这是我不想要的。我只希望吐司在断开连接时显示。

有任何想法吗?

4

2 回答 2

2

您可以像这样检查网络连接:

    public static boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) MBankApplication.appContext.getSystemService
            (Context.CONNECTIVITY_SERVICE);

    NetworkInfo wifiNetwork = cm.getNetworkInfo(1);
    if (wifiNetwork != null && wifiNetwork.isConnected()) {
        return true;
    }
    NetworkInfo mobileNetwork = cm.getNetworkInfo(0);
    if (mobileNetwork != null && mobileNetwork.isConnected()) {
        return true;
    }
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork == null || !activeNetwork.isConnected()) {
        return false;
    }
    return true;
}

然后展示你的吐司

    if(!isNetworkConnected()){
        Toast.makeText(context, "Connection changed", Toast.LENGTH_SHORT).show();
    }
于 2016-11-23T10:20:03.583 回答
0

在显示 toast 之前检查连接是否可用这样的东西

 if(!isNetworkAvailable()){
Toast.makeText(context, "Connection changed", Toast.LENGTH_SHORT).show();
 }




private boolean isNetworkAvailable() {
 ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
 return activeNetworkInfo != null; 
}

编辑

为了安全起见,请使用此

private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager 
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
于 2016-11-23T09:53:14.527 回答