我有一个调用CheckNetworkConnectivity
的按钮。如果WiFi不可用,它会显示带有一些文本的Toast(网络不可用),这很好。但是,当WiFi连接可用时,访问URL时Activity
将崩溃。
我的问题是有时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();
}
}
答案 0 :(得分: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所以...在你的Activity中使用它并在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;
}
}
答案 1 :(得分: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
}
答案 2 :(得分:0)
请确保您在清单文件中指定所需的权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
答案 3 :(得分: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
中执行连接,不会阻止用户界面,也不会启动Exception
。
更新:关于手机连接到WIFI但尚未验证/登录热点的情况(因此,getJSONFromURL方法将崩溃,因为连接将返回wifi登录页面而不是预期的JSON)。您可以执行以下操作:
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
// Do whatever
}