Android 应仅在有 Internet 连接时打开应用程序

Android App should open only when there is Internet Connectivity

假设我有一个简单的 hello world 应用程序..现在我希望我的应用程序仅在有 Internet 连接时打开,否则它应该显示没有可用的 Internet 连接消息..提前致谢

在您的第一个 activity、

中使用此方法
/**
 * @return true if network is available and presents no UI message.
 */
public void isNetworkAvailable() {
    try {
        ConnectivityManager connectivity = (ConnectivityManager) sContext.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) {
                        //present your UI
                    }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    //exit the app
    finish();
}

请在 Manifest 中添加 android.permission.ACCESS_NETWORK_STATE 权限。