0

我的应用程序需要 Internet 从我的数据库中检索数据。此外,它使用谷歌地图作为主要活动。我发现每当我在没有互联网连接的情况下测试它时,屏幕都会变黑然后就崩溃了。当我没有互联网时,我应该如何在我的代码中处理这个问题?

4

3 回答 3

1

试试这个.......

public boolean isNet()
 {
     boolean status=false;
     String line;
     try
     {
         URL url = new URL("http://www.google.com");
         BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
         while(( line = reader.readLine()) != null) 
         {
         }
         status=true;
    }
    catch (IOException ex)
    {
        System.out.println("ex in isNet : "+ex.toString());
        if(ex.toString().equals("java.net.UnknownHostException: www.google.com"))
            status=false;
    }
    catch(Exception e)
    {

    }
    return status;
 }


if(status==true)
            {
            //Do your operation
            }
            else
                show("No Internet Connection.");
于 2013-03-07T07:14:15.600 回答
0

您可以检查互联网连接:

public boolean isOnline() 
{
    //Getting the ConnectivityManager.
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    //Getting NetworkInfo from the Connectivity manager.
    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    //If I received an info and isConnectedOrConnecting return true then there is an Internet connection.
    if (netInfo != null && netInfo.isConnectedOrConnecting()) 
    {
        return true;
    }
    return false;
}

如果互联网连接不可用,则向用户显示一条消息。

于 2013-03-06T23:01:59.623 回答
0

这个问题已经回答过几次了,试试这些:

Android - 如何检查互联网访问,而不仅仅是连接到 wifi?

检查android上的互联网连接

于 2013-03-07T00:51:47.163 回答