gpt4 book ai didi

android - 在没有互联网访问android时显示 toast

转载 作者:行者123 更新时间:2023-11-29 20:18:02 24 4
gpt4 key购买 nike

我如何让这段代码永远在后台运行并始终检测是否有互联网访问(没有互联网连接)并在没有互联网访问时显示 toast ?

here is我想要的(见喵喵的回答),但它是为了检测互联网

// check connectivity (Internet access)
private boolean checkConnectivity() {
System.out.println("executeCommand");
Runtime runtime = Runtime.getRuntime();
try {
Process mIpAddrProcess = runtime
.exec("/system/bin/ping -c 1 8.8.8.8");
int mExitValue = mIpAddrProcess.waitFor();
System.out.println(" mExitValue " + mExitValue);
if (mExitValue == 0) {
img_c1.setImageResource(R.drawable.index2);
return true;
} else {
img_c2.setImageResource(R.drawable.index2);
return false;
}
} catch (InterruptedException ignore) {
ignore.printStackTrace();
System.out.println(" Exception:" + ignore);
} catch (IOException e) {
e.printStackTrace();
System.out.println(" Exception:" + e);
}
return false;
}

最佳答案

First of all, its bad idea to run this code forever in background.

改为使用BroadCastReceiver来检查网络状态,因此它只会在网络状态改变时激活,

您必须为网络状态更改事件注册您的BroadcastReceiver。因此,每当网络 android 广播事件的设备发生任何变化时,您的 BroadcastReceiver 将监听该事件并基于该事件显示 Toast。

好的教程:http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html

http://www.grokkingandroid.com/android-getting-notified-of-connectivity-changes/

关于android - 在没有互联网访问android时显示 toast ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33584746/

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