如何检测互联网连接[重复]
Posted
技术标签:
【中文标题】如何检测互联网连接[重复]【英文标题】:How to detect Internet Connection [duplicate] 【发布时间】:2012-05-22 02:46:41 【问题描述】:可能重复:android detect if device has internet connection
我有一个程序,我只允许连接互联网的安卓用户可以访问,其他没有互联网连接的用户会提醒他们连接到互联网,如果没有连接问题将退出。
我的主要活动代码如下。如果移动用户连接了互联网,我想显示主布局,但如果没有连接,则提醒用户先连接互联网。
我该怎么做?请帮帮我。
我的主要活动:
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);
);
感谢您的帮助。
【问题讨论】:
【参考方案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();
您的 AndroidManifest.xml 文件中还需要包含我的代码的强制性 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
。
【讨论】:
亲爱的 Alex W,你能比这更清楚地解释我吗?因为我不知道如何在我的主活动中添加你的代码? 在我的应用程序中,我在按钮的 onClickListener 中拥有上述所有代码,按照它出现的顺序。示例:按钮 imgButton = (Button)findViewById(R.id.buttonImg); imgButton.setOnClickListener(new OnClickListener()public void onClick(View arg0) // 把代码放在这里 ); ...把它放在你的主要活动中,并将其更改为与你布局中的按钮相关【参考方案2】://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" />
【讨论】:
Agarwal,我添加了你的代码,它没有出现任何错误,但是在没有互联网连接的情况下编译它之后,我仍然可以正常访问我的应用程序。 你必须在每次需要网络连接时调用这个函数,并检查它是否返回true。如果它返回 true,则网络连接可用,如果返回 false,您可以继续操作,那么您必须向用户显示带有消息的警报对话框【参考方案3】:您可以使用 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" />
【讨论】:
亲爱的 Imran Khan,您的代码无效。【参考方案4】:您应该创建一个BroadcastReceiver
,当连接状态发生变化时将触发该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
【讨论】:
以上是关于如何检测互联网连接[重复]的主要内容,如果未能解决你的问题,请参考以下文章