This code use for check internet connection on your application when needs acess internet for running API client-server or other access URL.
the first you create java file with name class
HttpRequest.java
the first you create java file with name class
HttpRequest.java
package com.rki.yourapps.internet; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import android.util.Log; public class HttpRequest { public HttpResponse response = null; private String url = null; private Mapparams = new HashMap (); private Method requestMethod = null; final int CONN_WAIT_TIME = 10000; final int CONN_DATA_WAIT_TIME = 0; public enum Method { GET, POST } public HttpRequest(String url, Map params, Method requestMethod) { this.url = url; this.params = params; this.requestMethod = requestMethod; } public HttpRequest(String url, Method requestMethod) { this.url = url; this.requestMethod = requestMethod; } public String sendRequest() { Log.d("HttpRequest@sendRequest", "Starting request..."); Log.d("HttpRequest@sendRequest", "URL: " + this.url + ", requestMethod: " + this.requestMethod); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, CONN_WAIT_TIME); HttpConnectionParams.setSoTimeout(httpParams, CONN_DATA_WAIT_TIME); // Create a new HttpClient and Post Header DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); HttpRequestBase httpRequest = null; InputStream responseStream = null; String responseString = null; try { if (this.requestMethod == Method.POST) { httpRequest = new HttpPost(this.url); if (httpRequest != null) { ((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity( encodePostParameter(this.params))); // Execute HTTP Post Request // Execute HTTP Post Request try { @SuppressWarnings("rawtypes") Class strictModeClass = Class.forName("android.os.StrictMode"); @SuppressWarnings("rawtypes") Class strictModeThreadPolicyClass = Class .forName("android.os.StrictMode$ThreadPolicy"); Object laxPolicy = strictModeThreadPolicyClass.getField("LAX").get( null); @SuppressWarnings("unchecked") java.lang.reflect.Method method_setThreadPolicy = strictModeClass.getMethod( "setThreadPolicy", strictModeThreadPolicyClass); method_setThreadPolicy.invoke(null, laxPolicy); } catch (Exception e) { } response = httpClient.execute(httpRequest); } } else if (this.requestMethod == Method.GET) { httpRequest = new HttpGet(this.url + encodeGetParameter(this.params)); if (httpRequest != null) { // Execute HTTP Post Request try { @SuppressWarnings("rawtypes") Class strictModeClass = Class.forName("android.os.StrictMode"); @SuppressWarnings("rawtypes") Class strictModeThreadPolicyClass = Class .forName("android.os.StrictMode$ThreadPolicy"); Object laxPolicy = strictModeThreadPolicyClass.getField("LAX").get( null); @SuppressWarnings("unchecked") java.lang.reflect.Method method_setThreadPolicy = strictModeClass.getMethod( "setThreadPolicy", strictModeThreadPolicyClass); method_setThreadPolicy.invoke(null, laxPolicy); } catch (Exception e) { } response = httpClient.execute(httpRequest); } } if (response != null) { responseStream = response.getEntity().getContent(); responseString = generateResponseString(responseStream); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Log.d("HttpRequest@sendRequest", "Finished!"); return responseString; } public List encodePostParameter(Map params) { List nameValuePairs = new ArrayList (1); Set keys = params.keySet(); for (String key : keys) { String value = params.get(key); nameValuePairs.add(new BasicNameValuePair(key, value)); } return nameValuePairs; } @SuppressWarnings("deprecation") public String encodeGetParameter(Map params) { StringBuilder buff = new StringBuilder("?"); Set keys = params.keySet(); for (String key : keys) { String value = params.get(key); buff.append(key).append("=").append(URLEncoder.encode(value)); } return buff.toString(); } public String generateResponseString(InputStream stream) { InputStreamReader reader = new InputStreamReader(stream); BufferedReader buffer = new BufferedReader(reader); StringBuilder sb = new StringBuilder(); try { String cur; while ((cur = buffer.readLine()) != null) { sb.append(cur + "\n"); } } catch (IOException e) { e.printStackTrace(); } try { stream.close(); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } public void setEntity(UrlEncodedFormEntity urlEncodedFormEntity) { // TODO Auto-generated method stub } }
and second, you create java file with name class
InternetChecker.java
package com.rki.demokrado.internet; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class InternetChecker { public static boolean isNetworkAvailable(Context context) { boolean outcome = false; if (context != null) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo[] networkInfos = cm.getAllNetworkInfo(); for (NetworkInfo tempNetworkInfo : networkInfos) { if (tempNetworkInfo.isConnected()) { outcome = true; break; } } } return outcome; } }
And the last, you can chect internet connection use conndition operator "IF" like this script:
if (InternetChecker.isNetworkAvailable(getApplicationContext()) == true) { //if there is a internet connection } else { //if no internet connection }
And don't forget you have to declaration "Permission Internet" on AndroidManifest.xml
0 komentar:
Post a Comment