0

我有一个可以调用的按钮CheckNetworkConnectivity。如果 WiFi 不可用,它会显示带有一些文本的 toast(网络不可用),这很好。但是当 WiFi 连接可用Activity时,访问 URL 时会崩溃。

我的问题是有时 WiFi 网络可用,但您必须登录才能访问服务器。它在您的手机中显示为 WiFi 连接。

ExampleActivity.java:

public class ExampleActivity extends ListActivity {
    // url to make request
    private static String url = "http://10.0.2.2/test/index.php";

    // JSON Node usds
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_ID = "id";
    private static final String TAG_CURRENCY = "currency";
    private static final String TAG_BUY = "buy";
    private static final String TAG_SALE = "sale";
    private static final String TAG_UPDATE = "update";

    // contacts JSONArray
    JSONArray contacts = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.example_layout);

        // Hashmap for ListView
        ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of Contacts
            contacts = json.getJSONArray(TAG_CONTACTS);

            // looping through All Contacts
            for(int i = 0; i < contacts.length(); i++){
                JSONObject c = contacts.getJSONObject(i);

                // Storing each json item in variable
                String id = c.getString(TAG_ID);
                String currency = c.getString(TAG_CURRENCY);
                String buy = c.getString(TAG_BUY);
                String sale = c.getString(TAG_SALE);
                String update = c.getString(TAG_UPDATE);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_ID, id);
                map.put(TAG_CURRENCY, currency);
                map.put(TAG_BUY, buy);
                map.put(TAG_SALE, sale);
                map.put(TAG_UPDATE, update);

                // adding HashList to ArrayList
                contactList.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(this, contactList,
                R.layout.list_item_exchange,
                new String[] { TAG_CURRENCY, TAG_BUY, TAG_SALE, TAG_UPDATE }, new int[] {
                        R.id.currency, R.id.buy, R.id.sale, R.id.update });

        setListAdapter(adapter);

        // selecting single ListView item
        ListView lv = getListView();
    }
}
4

4 回答 4

1

你可以简单地使用这个:

public boolean isNetworkAvailable() {
    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;
}

并由以下人员使用:

   if(isNetworkAvailable()){

     // do your stuff
  }else{
  // no network..
  }

并为 Android Manifest 文件添加权限:

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

你不能在主线程中更新你的 UI 所以......在你的活动中使用它......并在 onCreate() 方法上调用这个函数:

喜欢 :

  new DowloadTest().execute();


  public class DowloadTest extends AsyncTask<String, Integer, String> {
    @Override
    protected void onPreExecute() {
        pDialog = new ProgressDialog(c);
        pDialog.setMessage("Please wait..");
        pDialog.setIndeterminate(true);
        pDialog.setCancelable(false);
        pDialog.show();
    };

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub



        JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);

    try {
        // Getting Array of Contacts
        contacts = json.getJSONArray(TAG_CONTACTS);

        // looping through All Contacts
        for(int i = 0; i < contacts.length(); i++){
            JSONObject c = contacts.getJSONObject(i);

            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String currency = c.getString(TAG_CURRENCY);
            String buy = c.getString(TAG_BUY);
            String sale = c.getString(TAG_SALE);
            String update = c.getString(TAG_UPDATE);

            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(TAG_ID, id);
            map.put(TAG_CURRENCY, currency);
            map.put(TAG_BUY, buy);
            map.put(TAG_SALE, sale);
            map.put(TAG_UPDATE, update);

            // adding HashList to ArrayList
            contactList.add(map);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub

        runOnUiThread(new Runnable() {
            public void run() {

                try {
                    if (pDialog != null) {
                        pDialog.dismiss();
                    }

                     ListAdapter adapter = new  SimpleAdapter(this, contactList,R.layout.list_item_exchange,new String[] { TAG_CURRENCY, TAG_BUY, TAG_SALE, TAG_UPDATE }, new int[] {
                    R.id.currency, R.id.buy, R.id.sale, R.id.update });

                    setListAdapter(adapter);

                    // selecting single ListView item
                    ListView lv = getListView();

                } catch (JSONException e) {
                    e.printStackTrace();
                }



            }

        });
        return;
    }
}
于 2013-09-10T08:24:57.897 回答
0

请确保,您在清单文件中指定所需的权限

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
于 2013-09-10T08:21:42.307 回答
0

假设 ExampleActivity 中的 URL 不为空,我猜你可能会得到一个NetworkOnMainThreadException(这将在 Android 3.0 及更高版本中发生)。

检查这个关于在 UI 线程上执行连接的答案(JParser.getJSONFromURL()也使用)getJSONfromURL - Null Pointer Exception

您可以使用AsyncTask. 也可以Thread这样使用:

new Thread(new Runnable() {
 public void run() {
  JSONObject json = jParser.getJSONFromUrl(url);
  ...
 }
}.start();

这将在另一个中执行连接,Thread并且不会阻塞 UI 也不会启动Exception.

更新:关于手机连接到 WIFI 但尚未验证/登录到热点的情况(因此,getJSONFromURL 方法将崩溃,因为连接将返回 wifi 登录页面而不是预期的 JSON)。您可以执行以下操作:

ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (mWifi.isConnected()) {
    // Do whatever
}

来自:https ://stackoverflow.com/a/3841407/801913

于 2013-09-10T08:52:55.443 回答
0

尝试这个

 public Boolean check() {
 ConnectivityManager conn = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (conn != null) {
        NetworkInfo[] net = conn.getAllNetworkInfo();
        if(net!=null)
        for (int i = 0; i < net.length; i++)
            if (net[i].getState() == NetworkInfo.State.CONNECTED)
                return true;
    }

然后在 MainActivity 中检索它

ConnectionDetector connection = new ConnectionDetector(this);
    Boolean internetConnection = connection.check();
    if (internetConnection == false) {
        Toast.makeText(getApplicationContext(), "No Internet Connectivity",
                Toast.LENGTH_SHORT).show();
    }
else
{
// enter code here
}
于 2013-09-10T08:17:04.790 回答