查詢一個這樣的網站:
讓你的類中加入下面的方法類實現AsyncTaskCompleteListenere<Boolean>
:
@Override
public void onTaskComplete(Boolean result) {
Toast.makeText(getApplicationContext(), "URL Exist:" + result, Toast.LENGTH_LONG).show();
// continue your job
}
爲您的課程添加一個簡單的testConnection
方法,以便在您要檢查您的課程時調用nectivity:
public void testConnection() {
URLExistAsyncTask task = new URLExistAsyncTask(this);
String URL = "http://www.google.com";
task.execute(new String[]{URL});
}
最後的URLExistAsyncTask
類進行連通性測試作爲異步(後臺)任務和回叫你onTaskComplete
方法進行一次:
public class URLExistAsyncTask extends AsyncTask<String, Void, Boolean> {
AsyncTaskCompleteListenere<Boolean> callback;
public URLExistAsyncTask(AsyncTaskCompleteListenere<Boolean> callback) {
this.callback = callback;
}
protected Boolean doInBackground(String... params) {
int code = 0;
try {
URL u = new URL(params[0]);
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("GET");
huc.connect();
code = huc.getResponseCode();
} catch (IOException e) {
return false;
} catch (Exception e) {
return false;
}
return code == 200;
}
protected void onPostExecute(Boolean result){
callback.onTaskComplete(result);
}
}
檢查出的問題https://stackoverflow.com/questions/4238921/detect-whether-there-is-an-internet-connection-available-on-android – nyulan