如何检测Internet连接

时间:2012-05-22 02:46:41

标签: android

  

可能重复:
  Android detect if device has internet connection

我有一个程序,我只允许有互联网连接的Android用户可以访问,其他没有互联网连接的用户提醒他们连接到互联网,如果没有连接问题将退出。

我的主要活动代码如下。我想如果移动用户已连接互联网将显示主要布局,但如果没有连接提醒用户首先连接互联网。

我该怎么办?请帮帮我。

我的主要活动:

public class MainSong extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


  //My Profile
    Button myProfile = (Button) findViewById(R.id.myprofile);


    myProfile.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent i = new Intent();
            i.setClassName("aaa.bbb.ccc", "aaa.bbb.ccc.myprofile");
            startActivity(i); }
    });

  //My Songs
    Button mySong = (Button) findViewById(R.id.mysongs);
    mySong.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent i = new Intent();
            i.setClassName("aaa.bbb.ccc", "aaa.bbb.ccc.mysong");
            startActivity(i); }
    });

    //bar album
    Button album = (Button) findViewById(R.id.myalbum);
    album.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent i = new Intent();
            i.setClassName("aaa.bbb.ccc", "aaa.bbb.ccc.myalbum");
            startActivity(i); }
    });

    //bar video
    Button video = (Button) findViewById(R.id.myvideo);
    video.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Intent i = new Intent();
            i.setClassName("aaa.bbb.ccc", "aaa.bbb.ccc.myvideo");
            startActivity(i); }
    });
}
}

感谢您的帮助。

4 个答案:

答案 0 :(得分:1)

您可以使用ConnectivityManager检查用户是否已连接到互联网:

public boolean checkNetworkStatus() {

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

    final android.net.NetworkInfo wifi = connMgr
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    final android.net.NetworkInfo mobile = connMgr
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    if (wifi.isAvailable()) {
     if (wifiInfo.getState() == NetworkInfo.State.CONNECTED)
      {
        Toast.makeText(this, "Wifi connection.", Toast.LENGTH_LONG).show();
        return true;
      }
      else
      {
        Toast.makeText(this, "No Connect using wifi connection.", Toast.LENGTH_LONG).show();
        return false;
      }
    } else if (mobile.isAvailable()) {
      if (mobile.getState() == NetworkInfo.State.CONNECTED)
      {
        Toast.makeText(this, "Connected using GPRS connection.", Toast.LENGTH_LONG).show();
        return true;
      }
      else
      {
        Toast.makeText(this, "No Connect using GPRS connection.", Toast.LENGTH_LONG).show();
        return false;
      }

    } else {
        Toast.makeText(this, "No network connection.", Toast.LENGTH_LONG).show();
        return false;
    }       

}

<强>的AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

答案 1 :(得分:1)

//To check whether network connection is available on device or not
public static boolean checkInternetConnection(Context _activity) {
        ConnectivityManager conMgr = (ConnectivityManager) _activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conMgr.getActiveNetworkInfo() != null
                && conMgr.getActiveNetworkInfo().isAvailable()
                && conMgr.getActiveNetworkInfo().isConnected()) 
            return true;
        else
            return false;
    }//checkInternetConnection()

<强>的AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

答案 2 :(得分:1)

以下是我在Android应用中使用的代码:

            CharSequence network_fail = "This application requires that you are connected to the Internet.";
            int duration = Toast.LENGTH_SHORT;
            boolean isAvailable = false;

            // Check availability of network connection
            try
            {
                ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                if(cm == null)
                    isAvailable = false;
                else
                    isAvailable = cm.getActiveNetworkInfo().isAvailable();
            }
            catch(Exception e){}

如果符合以下条件,请将依赖Internet的代码放入其中:

            // Check if user is connected to the Internet, and show an error if they are not.
            if(isAvailable && (isAirplaneModeOn(context) == false))
            {
              // Internet-reliant code
            }
            else
            {
                Toast fail = Toast.makeText(context, network_fail, duration);
                fail.show();
            }

您还需要AndroidManifest.xml文件中的强制性<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />和我的代码。

答案 3 :(得分:0)

当连接状态发生变化时,您应该触发BroadcastReceiver

     public class BroadCastSampleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        this.registerReceiver(this.mConnReceiver,
                new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }
    private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
            String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
            boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

            NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

            if(currentNetworkInfo.isConnected()){
                Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(getApplicationContext(), "Not Connected", Toast.LENGTH_LONG).show();
            }
        }
    };
}

然后在AndroidManifest中,您可以检查是否有连接:

 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

此处参考here source