Last active
September 11, 2017 13:35
-
-
Save alfianyusufabdullah/7b5a4235a00a14f0c01a93ea3ea847b1 to your computer and use it in GitHub Desktop.
Cara Cek Network & Internet Status Java Android Cara barbar :D :v *OKHTTP3 REQUIRED
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package jonesrandom.firebasechat.Utils; | |
| import android.content.Context; | |
| import android.net.ConnectivityManager; | |
| import android.net.NetworkInfo; | |
| import android.os.AsyncTask; | |
| import java.io.IOException; | |
| import okhttp3.OkHttpClient; | |
| import okhttp3.Request; | |
| import okhttp3.Response; | |
| /** | |
| * Created by JonesRandom on 9/9/17. | |
| * https://masx-dev.blogspot.com | |
| */ | |
| public class NetworkStatus { | |
| private Context ctx; | |
| public NetworkStatus(Context ctx) { | |
| this.ctx = ctx; | |
| } | |
| public void openConnection(final onNetworkStatusListener listener) { | |
| ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); | |
| NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); | |
| if (activeNetwork != null) { | |
| class getConnectionStatus extends AsyncTask<Void, Void, Integer> { | |
| @Override | |
| protected void onPreExecute() { | |
| super.onPreExecute(); | |
| listener.onConnecting(); | |
| } | |
| @Override | |
| protected Integer doInBackground(Void... voids) { | |
| OkHttpClient client = new OkHttpClient(); | |
| Request request = new Request.Builder() | |
| .url("https://firebase.google.com/") | |
| .build(); | |
| try { | |
| Response response = client.newCall(request).execute(); | |
| return response.code(); | |
| } catch (IOException e) { | |
| e.printStackTrace(); | |
| return 0; | |
| } | |
| } | |
| @Override | |
| protected void onPostExecute(Integer integer) { | |
| super.onPostExecute(integer); | |
| if (integer == 200){ | |
| listener.onConnected(); | |
| } else { | |
| listener.onConnectionFailure(); | |
| } | |
| } | |
| } | |
| new getConnectionStatus().execute(); | |
| } else { | |
| listener.onDisconnected(); | |
| } | |
| } | |
| public interface onNetworkStatusListener { | |
| void onConnected(); | |
| void onConnectionFailure(); | |
| void onConnecting(); | |
| void onDisconnected(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment