Я хочу проверить подключение к Интернету, после этого заполнить список. но мои коды для проверки подключения к Интернету не работают. я отключу свое сетевое подключение для тестирования, но mycodes (проверка соединения не работает). , пожалуйста, помогите мне, что не так.Проверка подключения к Интернету не работает в android
connectionDetector:
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
моя активность:
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.updateapp);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//check Internet Connection
Boolean isInternetPresent = false;
ConnectionDetector cd;
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
new JSONParse().execute(); }
else {
// Internet connection is not present
// Ask user to connect to Internet
showAlertDialog(UpdateFromSite.this, "No Internet Connection",
"You don't have internet connection.", false);
}
}
});
}
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
name = (TextView)findViewById(R.id.nameNewItem);
description = (TextView)findViewById(R.id.descriptionNewItem);
price = (TextView)findViewById(R.id.priceNewItem);
pDialog = new ProgressDialog(UpdateFromSite.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String name = c.getString(TAG_NAME);
String description = c.getString(TAG_DESCRIPTION);
String price = c.getString(TAG_PRICE);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NAME, name);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_PRICE, price);
oslist.add(map);
list=(ListView)findViewById(R.id.listupdate);
ListAdapter adapter = new SimpleAdapter(UpdateFromSite.this, oslist,
R.layout.updateapprow,
new String[] { TAG_NAME,TAG_DESCRIPTION, TAG_PRICE }, new int[] {
R.id.nameNewItem,R.id.descriptionNewItem, R.id.priceNewItem});
list.setAdapter(adapter);}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
manifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Ваш велосипед по всем типам сетей, один из которых может возвращать true, вы должны проверить тип в этом случае. –