2

我的应用程序需要互联网连接,因此它会检查用户是否有连接。但它仅在活动开始时检查,所以我如何检测用户在活动开始后是否没有连接?

这是我在活动开始时用来检测连接的代码:

@Override

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main );

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info != null) {
            if (!info.isConnected()) {
            }
        }
        else {
            Intent intent = new Intent(hello.this, connectionerror.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            hello.this.finish();
        }

.....我的应用程序其他代码在这里继续......

4

1 回答 1

3

您可以BroadcastReceiverandroid.net.conn.CONNECTIVITY_CHANGE. 您可以查看意图(查看更改了哪些网络),也可以使用ConnectivityManager.

于 2011-08-08T21:21:37.807 回答