我正在使用以下代码检查此问题中建议的设备的连接性:
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
}
我在我的主要活动中有这个,它工作正常,但我现在想做的是每次应用程序启动时检查互联网连接,有时应用程序处于某种状态,然后互联网断开连接,所以当它再次打开它没有经过主要活动,因此没有检查任何内容。
正如这个问题中所建议的那样,我已经按照本教程使用 BroadcastReceiver 监控互联网活动,并且我试图在 noConnectivity 为真时显示和 AlertDialog ,但没有任何反应。
这是我的代码,使用上面提到的教程:
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()
解雇。
希望你能帮助我。谢谢