5

我有 SplashActivity、Activity A 和 Activity B。

当 Internet 不可用时,Splash 活动重定向到 Activity A,当 Internet 可用且已连接时,SplashActivity 重定向到 Activity 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"
  }

提前致谢。

4

1 回答 1

5

在这种情况下,您应该使用检查网络状态,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);
    }
  }
}

要关闭 Activity A,您只需添加android:noHistory="true"Manifest,如下所示:

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

希望这会帮助你。

于 2018-08-28T01:21:04.023 回答