您可以使用 NetworkChangeReceiver
public class NetworkChangeReceiver extends BroadcastReceiver {
private static final String LOG_TAG = "NetworkChangeReceiver";
private boolean isConnected = false;
Context mContext;
@Override
public void onReceive(Context context, Intent intent) {
Log.v(LOG_TAG, "Receieved notification about network status");
isNetworkAvailable(context);
mContext=context;
}
public boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
if (!isConnected) {
Log.v(LOG_TAG, "Now you are connected to Internet!");
Toast.makeText(context, R.string.internet_available, Toast.LENGTH_SHORT).show();
isConnected = true;
}
return true;
}
}
}
}
Log.v(LOG_TAG, "You are not connected to Internet!");
Toast.makeText(context, R.string.internet_not_available, Toast.LENGTH_SHORT).show();
isConnected = false;
return false;
}