【发布时间】:2011-05-19 09:06:53
【问题描述】:
是否有事件告诉我设备已连接到 INTERNET(3G 或 wifi)?只有在设备连接到 INTERNET 后,我才需要启动一些请求。代码需要支持Android 2.1。谢谢
【问题讨论】:
标签: android events connection
是否有事件告诉我设备已连接到 INTERNET(3G 或 wifi)?只有在设备连接到 INTERNET 后,我才需要启动一些请求。代码需要支持Android 2.1。谢谢
【问题讨论】:
标签: android events connection
您可以使用广播接收器并等待操作ConnectivityManager.CONNECTIVITY_ACTION
这里是doc
例如:
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] info = connectivity.getAllNetworkInfo();
//Play with the info about current network state
}
}
};
intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
【讨论】:
使用广播接收器,只要网络状态发生变化,它就会被调用:
private NetworkStateReceiver mNetSateReceiver = null;
private class NetworkStateReceiver extends BroadcastReceiver
{
@Override
public void onReceive( Context context, Intent intent )
{
// Check the network state to determine whether
// we're connected or disconnected
}
}
@Override
public void onCreate()
{
registerReceiver( mNetSateReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION ) );
}
@Override
public void onDestroy()
{
save();
unregisterReceiver( mNetSateReceiver );
}
只要网络状态发生变化,就会调用 onReceive,您可以使用其他答案中详述的技术来确定您是否实际连接。
【讨论】:
使用此功能,您可以知道设备是否已连接互联网:
public static boolean connectionCheck(final Context context)
{
boolean returnTemp=true;
ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo i = conManager.getActiveNetworkInfo();
if ((i == null)||(!i.isConnected())||(!i.isAvailable()))
{
AlertDialog.Builder dialog = new Builder(context);
dialog.setTitle("CONNECTION STATUS");
dialog.setMessage("Failed");
dialog.setCancelable(false);
dialog.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
Toast.makeText(TennisAppActivity.mContext,"Wi-Fi On", Toast.LENGTH_LONG).show();
}
});
dialog.show();
return false;
}
return true;`enter code here`
}
【讨论】:
public static boolean checkInternetConnection(Context context) {
final ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else
return false;
}
使用此函数,如果连接了互联网,函数将返回true,否则返回false
【讨论】: