English 中文(简体)
如何检测 Internet 连接 [重复]
原标题:How to detect Internet Connection [duplicate]
  • 时间:2012-05-22 02:46:41
  •  标签:
  • android
This question already has answers here:
Closed 11 years ago.

Possible Duplicate:
Android detect if device has internet connection

我有一个程序,我只允许有互联网连接的机器人用户进入, 其他没有互联网连接的用户提醒他们连接互联网, 如果不连接问题, 就会退出。

我的主要活动代码是bellow。 如果移动用户有互联网连接, 我要显示主布局, 但如果没有连接到警示用户, 请先连接互联网 。

我该怎么做?

My Main Activity:

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

谢谢你的帮助

最佳回答

我用在 Android App里的代码是:

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

您还需要在您的 Android Manifest. xml 文档中包含我代码的强制 < code\ lt; uses- permission and roid. permission.ACCESS_ NETWORK_ StateE > / & gt;

问题回答
//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()

<强度 > 和机器人manifest.xml:

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

您可以通过使用连接管理器来检查用户是否连接到互联网 :

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;
    }       

}

<强度 > 和机器人manifest.xml:

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

您应该制作一个 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" />

在此引用 这里的源





相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签