连接网络后如何检测网络更改并将活动从A更改为B

时间:2018-08-28 00:47:41

标签: java android android-connectivitymanager

我有SplashActivity,活动A和活动B。

当Internet不可用时,Splash活动将重定向到活动A;当Internet可用并已连接时,SplashActivity将重定向到活动B。

我想在用户自行连接时立即关闭活动A,并在用户仍在应用程序中并且打开其wifi或移动数据时立即打开活动B。

这是我在SplahsActivity中用于根据网络状态重定向到活动A和活动B的代码

public static boolean isNetworkStatusAvialable(Context context) {
    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null &&
            activeNetwork.isConnectedOrConnecting();

}

然后我与

核对
  if (isNetworkStatusAvialable(getApplicationContext())) {
    // Load Activity B
  } else {
    Load Activity A and Toast Message, " No Internet"
  }

谢谢。

1 个答案:

答案 0 :(得分:2)

在这种情况下,您应该使用BroadcastReceiver检查网络状态,因为您立即要关闭当前活动并转到其他活动。因此,下面是完整的代码:

ConnectivityStatusReceiver.java

public class ConnectivityStatusReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {

    final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();

    if (activeNetworkInfo != null) {
      Toast.makeText(context, activeNetworkInfo.getTypeName() + " connected", Toast.LENGTH_SHORT).show();

      // Your code to start Activity B
      Activity activity = (Activity) context;
      intent = new Intent(activity, ActivityB.class);
      activity.startActivity(intent);

    } else {
      Toast.makeText(context, "No Internet or Network connection available", Toast.LENGTH_LONG).show();
    }
  }

}

MainActivity.java

public class MainActivity extends AppCompatActivity {
  ConnectivityStatusReceiver connectivityStatusReceiver;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    connectivityStatusReceiver = new ConnectivityStatusReceiver();
  }

  @Override
  protected void onResume() {
    super.onResume();
    IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(connectivityStatusReceiver, intentFilter);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (connectivityStatusReceiver != null) {
      // unregister receiver
      unregisterReceiver(connectivityStatusReceiver);
    }
  }
}

要关闭活动A,只需在清单中添加android:noHistory="true",如下所示:

<activity android:label="@string/app_name" android:name="ActivityA"/>

希望这会对您有所帮助。