如何使此代码永远在后台运行,并始终检测是否存在internet访问(非internet连接),并在没有internet访问时敬酒?
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;
}发布于 2015-11-07 16:11:43
首先,永远在后台运行这段代码是个坏主意。
相反,使用BroadCastReceiver检查网络状态,因此它只在网络状态更改时才会激活,
您必须注册网络状态更改事件的BroadcastReceiver。因此,当任何改变发生在设备上的网络安卓广播事件和你的BroadcastReceiver将监听该事件,并在此基础上显示烤面包。
好的教程:http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
http://www.grokkingandroid.com/android-getting-notified-of-connectivity-changes/
https://stackoverflow.com/questions/33584746
复制相似问题