0

我正在使用BroadCastReceiver监视活动的网络状态。但这行不通。谁能帮帮我。

import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.Toast;

public class GTChat extends ListActivity {

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

    }

    // /////////////////////////////////////////////////////////////////

    private BroadcastReceiver mConnReceiver = new BroadcastReceiver()

    {

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

        {

            NetworkInfo info = (NetworkInfo) intent
                    .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

            if (info.getState().equals(NetworkInfo.State.CONNECTED))

            {

                GTalkChatDetails.chat(getApplicationContext());
                GTalkChatDetails.adddMsgListener(getApplicationContext());

            }

            else

            {

                Toast.makeText(getApplicationContext(),
                        "Network not connected", Toast.LENGTH_LONG).show();

            }

        }

    };

    // //////////////////////////////////////////////////

    protected void onPause()

    {

        unregisterReceiver(mNetworkReceiver);

        super.onPause();

    }

    protected void onResume()

    {

        registerReceiver(mNetworkReceiver, new IntentFilter(
                ConnectivityManager.CONNECTIVITY_ACTION));

        super.onResume();

    }
}
4

1 回答 1

0

尝试使用此代码段:

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

由于您没有在清单中注册广播接收器,因此应该这样做。或者把它改成这样

 private final BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
  @Override
 public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

   // your check here

}}
于 2012-09-13T11:51:08.840 回答