问题
how do i make this code run in background forever and always detect if there is internet access or not (not internet connection) and show a toast when there is no internet access?
here is what i want (See meow meo's answer), but it is for detecting internet
// 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;
}
回答1:
First of all, its bad idea to run this code forever in background.
Instead use BroadCastReceiver
to check network status, so it will only active at the time of network status change,
You have to register your BroadcastReceiver
for Network Status Change event. So whenver any changes happen on device for network android broadcast event and your BroadcastReceiver will listen that event and display Toast based on that.
Good tutorials: 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/show-toast-when-there-is-no-internet-access-android