Android的 - 编程方式检查网络连接,并在显示对话框notConnected并在、对话框、方式、网络

2023-09-06 04:28:31 作者:29.月亮指挥官

我工作的一个活的项目。而当应用程序用户点击。出现欢迎屏幕(有一个web视图的屏幕上)。如果没有连接网络,然后应用程序崩溃。基本上,我的问题是检查编程是移动终端连接到互联网或没有。如果没有的话不获取从web服务数据到web视图,并显示一个对话框,显示请检查您的网络连接

I am working on a live project. and when user click on the app. the welcome screen appears(there is a webview on that screen). and if the internet is not connected then the app crashes. Basically, my problem is to check programmatically that is mobile is connected to internet or not. if not then don't fetch the data from webservice into webview and display a dialog box showing "Check your internet connection"

而做的研究,我发现了很多东西,我试图实现这一点。但是,它不能满足我的要求。

while doing research i found many things, and i have tried to implement that. but, its not satisfying my requirement

我的code是,

public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    else
    {
        Description.setVisibility(View.INVISIBLE);
        new AlertDialog.Builder(WelcomePage.this)
        .setTitle(getResources().getString(R.string.app_name))
        .setMessage(
                getResources().getString(
                        R.string.internet_error))
        .setPositiveButton("OK", null).show();
    }
    return false;
}

我打电话的此功能doInBackground() 的AsyncTask

请帮助!

推荐答案

最后,我得到了答案。

ConnectivityManager conMgr =  ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

    {  
            NetworkInfo netInfo = conMgr.getActiveNetworkInfo();

            if (netInfo == null)
            {

                Description.setVisibility(View.INVISIBLE);
                new AlertDialog.Builder(WelcomePage.this)
                .setTitle(getResources().getString(R.string.app_name))
                .setMessage(
                        getResources().getString(
                                R.string.internet_error))
                .setPositiveButton("OK", null).show();

        }
        else
        {
            dialog = ProgressDialog.show(WelcomePage.this, "", "Loading...", true,
                    false);
            new Welcome_Page().execute();

        }