问题描述
- 如果没有网络连接Toast就不显示
-
如果网络连接不可用,我的Toast信息就不显示。代码如下:public class HomeMenu extends Activity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.homemenu); if (!Utils.isNetworkAvailable(HomeMenu.this)) { Toast.makeText(HomeMenu.this, getString(R.string.no_internet), Toast.LENGTH_SHORT).show(); } } }
Util 类:
public static boolean isNetworkAvailable(Activity activity) { ConnectivityManager connectivity = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity == null) { return false; } else { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; }
解决方案
修改Internet连接:
public static boolean isNetworkAvailable(Activity activity) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null
// otherwise check if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false; }
检测onCreate()方法:
if (!Utils.isNetworkAvailable(HomeMenu.this)) {
Showtoast("No Connection Available.");
}
void Showtoast(String message) {
Toast.makeText(HomeMenu.this, message, Toast.LENGTH_LONG).show();}
时间: 2024-09-12 10:54:21