如题所述
åºç¨åºæ¯ï¼å®ç°å¤æå½åç½ç»æ¯å¦å¯ç¨
å½åæå¯ç¨ç½ç»ï¼å¦ä¸å¾ï¼
å½å没æå¯ç¨ç½ç»ï¼å¦ä¸å¾ï¼
å®ç°æ¥éª¤ï¼
1ãè·åConnectivityManager对象
Context context = activity.getApplicationContext();// è·åææºææè¿æ¥ç®¡ç对象ï¼å
æ¬å¯¹wi-fi,netçè¿æ¥ç管çï¼ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
2ãè·åNetworkInfo对象
// è·åNetworkInfo对象NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
3ãå¤æå½åç½ç»ç¶ææ¯å¦ä¸ºè¿æ¥ç¶æ
if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
{ return true;
}
4ãå¨AndroidManifest.xmlä¸æ·»å 访é®å½åç½ç»ç¶ææé
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
代ç å¦ä¸ï¼
public class ClassTestDemoActivity extends Activity
{
@Override public void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.main); if (isNetworkAvailable(ClassTestDemoActivity.this))
{
Toast.makeText(getApplicationContext(), "å½åæå¯ç¨ç½ç»ï¼", Toast.LENGTH_LONG).show();
} else
{
Toast.makeText(getApplicationContext(), "å½å没æå¯ç¨ç½ç»ï¼", Toast.LENGTH_LONG).show();
}
}
/**
* æ£æ¥å½åç½ç»æ¯å¦å¯ç¨
*
* @param context
* @return
*/
public boolean isNetworkAvailable(Activity activity)
{
Context context = activity.getApplicationContext(); // è·åææºææè¿æ¥ç®¡ç对象ï¼å
æ¬å¯¹wi-fi,netçè¿æ¥ç管çï¼
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null)
{ return false;
} else
{ // è·åNetworkInfo对象
NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
if (networkInfo != null && networkInfo.length > 0)
{ for (int i = 0; i < networkInfo.length; i++)
{
System.out.println(i + "===ç¶æ===" + networkInfo[i].getState());
System.out.println(i + "===ç±»å===" + networkInfo[i].getTypeName()); // å¤æå½åç½ç»ç¶ææ¯å¦ä¸ºè¿æ¥ç¶æ
if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
{ return true;
}
}
}
} return false;
}
}
æ§å¶å°æå°åºçç»æï¼