0

可能重复:
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

4 回答 4

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" />
于 2012-05-22T02:48:57.753 回答
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" />
于 2012-05-22T03:00:15.747 回答
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){}

如果:

            // 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();
            }

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

于 2012-05-22T03:03:57.777 回答
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来源

于 2012-05-22T07:00:30.893 回答