我检查设备的连接,如this question建议用下面的代码打开:监控互联网连接,每次应用程序在Android的
final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.getState() == NetworkInfo.State.CONNECTED) {
//notify user you are online
} else {
//notify user you are not online
}
我有这个在我的主要活动,它工作正常,但我现在想做的是每次应用程序启动时检查互联网连接,有时应用程序处于某种状态,然后互联网断开连接,所以当它再次打开时,它不会经过主要活动,因此不检查任何内容。
如this question建议我遵循this tutorial与BroadcastReceiver监测互联网活动,我试图显示和AlertDialog时noConnectivity是真实的,但没有任何反应。
这是我的代码,使用上面提到的教程:
public class MyActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
registerReceivers() ;
(..my activity code goes here...)
}
private void noInternet()
{
Intent myIntent = new Intent(this, NoInternetActivity.class);
startActivity(myIntent);
}
/*
* method to be invoked to register the receiver
*/
private void registerReceivers() {
registerReceiver(mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
private void alert()
{
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("internet connection");
alertDialog.setMessage("To use this app you need intenet connection");
alertDialog.setButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
alertDialog.show();
}
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
@Override
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);
// do application-specific task(s) based on the current network state, such
// as enabling queuing of HTTP requests when currentNetworkInfo is connected etc.
if(noConnectivity)
{
alert();
noInternet();
}
}
};
}
但无论alert()
或noInternet()
被解雇了。
希望你能帮助我。 谢谢
但我将不得不为此在每一次活动我有吗? – marimaf
如果您需要在每项活动中建立连接,那么我可能会这样做。这会很困难还是有问题? – Tim
我会说95%的活动类需要连接性,因为他们从服务器获取动态内容。我不觉得把这个添加到每个活动都是最好的解决方案,但如果我找不到更好的解决方案,我可能会这样做。谢谢 – marimaf