如何检查定期在整个应用程序的Internet连接? [英] How to check the Internet Connection periodically in whole application?
问题描述
我在做什么,它使用通过互联网连接了应用程序。如果在使用应用程序失去了互联网连接,应用程序被强制关闭。为了避免这种情况,如果网络不可用,我想显示提示信息。我怎样才能做到这一点。 在登录的时候我检查使用下面的code的连通性。但是,我怎么能做到这一点在后台整个应用程序。
I am doing a application which uses the Internet Connection through out the application. If the internet connection is lost while using the application, the application is forcibly closing. To avoid this, if internet is not available i want to show a Alert message. How can i do this. At the time of Login i am checking the connectivity using the below code. But how can i do this for whole application in background.
private boolean haveInternet(){
NetworkInfo info = ((ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info==null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option you can change it if you want to disable internet while roaming, just return false
return true;
}
return true;
}
感谢你..
推荐答案
您应该作出的BroadcastReceiver
将被触发,当连接状态发生了变化:
You should make an BroadcastReceiver
that will be triggered when the connectivity status has changed :
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
您可以检查您是否已经连接:
and then in your AndroidManifest
you can check if you have connectivity:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
下载源$ C $ C - 这里
这篇关于如何检查定期在整个应用程序的Internet连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!