简体   繁体   English

如何在android中检查互联网和服务器(url)的可用性

[英]how to check availability of internet and server(url) in android

I have developed my application in android for weather forecasting. 我已经在android中开发了用于天气预报的应用程序。 In my application when my internet is not working or server is not reachable (given on the URL) ,the application gets crashed with the message "Unfortunately, application is stopped" . 在我的应用程序中,当我的Internet无法正常工作或服务器无法访问(通过URL给出)时,应用程序崩溃,并显示消息"Unfortunately, application is stopped" Here I have posted my code. 我在这里发布了我的代码。 I don't understand where I have to handle this exception. 我不知道该在哪里处理该异常。 please help me..Thanks in advance... 请帮助我..提前谢谢...

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(isNetworkAvailable())
        {
        setContentView(R.layout.activity_location);
        weatherlist = new ArrayList<HashMap<String, String>>();

        // Getting complete weather details in background thread
        new GetWeatherDetails().execute();
        new GetWeatherDetails1().execute();
        // Get listview
                ListView lv = getListView();

                // on seleting single product
                // launching Edit Product Screen
                lv.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
                        // getting values from selected ListItem
                        String FC_DATE = ((TextView) view.findViewById(R.id.fc_date)).getText()
                                .toString();

                        // Starting new intent
                        Intent in = new Intent(getApplicationContext(),
                                ForecastActivity.class);
                        // sending pid to next activity

                        in.putExtra(TAG_FC_DATE, FC_DATE);
                        in.putExtra(TAG_LAT, LAT);
                        in.putExtra(TAG_LONG, LONGITUDE);
                        // starting new activity and expecting some response back
                        startActivityForResult(in, 100);
                    }
                });

            }
        else
        {
            Toast.makeText(this, "Network unavailable", Toast.LENGTH_SHORT).show();
        }
    }
    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        LocationActivity.this, weatherlist,
                        R.layout.list_item, new String[] { TAG_FC_DATE},
                        new int[] { R.id.fc_date });

                // updating list view
                setListAdapter(adapter);
            }
        });

    }
    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

Use the following method to check if internet is available 使用以下方法检查互联网是否可用

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Then call it like this and display a message to your user. 然后像这样调用它并向您的用户显示一条消息。 I've included a Toast, but you may want to use a dialog of some sort 我包含了一个Toast,但您可能需要使用某种对话框

if (isNetworkAvailable())
{
    // do your request
}
else
{
    Toast.makeText(this, "Network unavailable", Toast.LENGTH_SHORT).show();
}

To get getActiveNetworkInfo() to work you need to add the below permission to the manifest file. 为了使getActiveNetworkInfo()正常工作,您需要将以下权限添加到清单文件中。

uses-permission android:name="android.permission.INTERNET"
   uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"

Also, when you're doing async tasks, you should be updating the UI in the onPostExecuted method of the AsyncTask Class. 另外,在执行异步任务时,应该在AsyncTask类的onPostExecuted方法中更新UI。 Provided the method below, put this in the same scope as your doInBackground of your Async Task: 提供以下方法,将其置于与异步任务的doInBackground相同的范围内:

@Override
protected void onPostExecute(String result) {
    // parse your response here and update the UI with the data parsed.
}

Use This Method. 使用此方法。

public static boolean isInternetAvailable(Context ctx) {
    ConnectivityManager cm = (ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()
            && cm.getActiveNetworkInfo().isAvailable()
            && cm.getActiveNetworkInfo().isConnected()) {
        return true;
    } else {
        return false;
    }
}

First add a check to see if the phone is connected to a Netwerk. 首先添加检查以查看电话是否已连接到Netwerk。

You can do this using the following code; 您可以使用以下代码执行此操作;

public boolean isNetwork() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

if (isNetwork()) {
    // do your request && server ping !!
} else {
    Toast.makeText(this, "Not connected to a network", Toast.LENGTH_SHORT).show();
}

Also add the following permission to the AndroidManifest.xml: 还要向AndroidManifest.xml添加以下权限:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

However, it can return a false positive for example, if the phone is connected to a WiFi network with a captive portal or vpn, this function will incorrectly return true. 但是,它可能返回假阳性,例如,如果电话通过强制门户或vpn连接到WiFi网络,则此功能将错误地返回true。

That's why you still need to check if you have internet, you can do this by adding a simple ping to your server or Google (Because Google is up 99,99% of the time). 这就是为什么您仍然需要检查是否有互联网,可以通过向服务器或Google添加简单的ping操作来完成此操作(因为Google的使用率高达99,99%)。

Something like this; 像这样的东西;

public boolean isNetwork() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return netInfo != null && netInfo.isConnectedOrConnecting();
}

public Boolean isInternet() {
    try {       
        Process process = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");      
        int returnVal = process.waitFor();      
        boolean reachable = (returnVal==0);
        return reachable
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false; 
}

if (isNetwork()) {
    if (isInternet()) {
        // do your request
    } else {
        Toast.makeText(this, "No internet connection", Toast.LENGTH_SHORT).show();
    }
else {
    Toast.makeText(this, "Not connected to a network", Toast.LENGTH_SHORT).show();
}

Finally dont forget, when you're doing a async tasks, you update the GUI in the onPostExecute Method. 最后不要忘记,当您执行异步任务时,可以在onPostExecute方法中更新GUI。 You dont call the runOnUiThread() in doInBackground. 您不要在doInBackground中调用runOnUiThread()。

Some documentation explaining this; 一些说明文件;

http://developer.android.com/reference/android/os/AsyncTask.html http://developer.android.com/reference/android/os/AsyncTask.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM