gpt4 book ai didi

android - 每次在 android 中打开应用程序时监控互联网连接

转载 作者:行者123 更新时间:2023-11-29 22:06:57 25 4
gpt4 key购买 nike

我正在按照 this question 中的建议检查设备的连接性使用以下代码:

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
}

我在我的主要 Activity 中有这个并且工作正常,但我现在想做的是在每次应用程序启动时检查互联网连接,有时应用程序处于某种状态然后互联网断开连接,所以当它再次打开时,它不会通过主要 Activity ,因此不会检查任何内容。

this question 中的建议我关注了this tutorial关于使用 BroadcastReceiver 监控互联网 Activity ,当 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() 都没有启动。

希望你能帮帮我。谢谢

最佳答案

如果您想在每次 Activity 恢复时运行一些代码,即使它已经打开,那么覆盖并将您的检查代码放在 onResume() 中。每次 Activity 打开时都会调用它。

关于android - 每次在 android 中打开应用程序时监控互联网连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10574021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com