Last active
July 3, 2017 00:45
-
-
Save agusibrahim/ea410d660f9696efbaedd3b4b867d2d1 to your computer and use it in GitHub Desktop.
Check Network Connectivity available or not
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 ai.agusibrahim.kepooto; | |
import java.net.Socket; | |
import java.io.IOException; | |
import java.net.InetSocketAddress; | |
import java.net.SocketAddress; | |
import android.os.AsyncTask; | |
import ai.agusibrahim.kepooto.ConnectionStatus.*; | |
import android.content.Context; | |
import android.net.ConnectivityManager; | |
import android.net.NetworkInfo; | |
public class ConnectionStatus | |
{ | |
private ConnectionStatus.onStatus ons; | |
private Context context; | |
public ConnectionStatus(Context context){ | |
this.context=context; | |
} | |
public interface onStatus{ | |
void gotStatus(boolean isOnline); | |
} | |
public boolean isNetworkAvailable() { | |
ConnectivityManager cm = | |
(ConnectivityManager)context. getSystemService(Context.CONNECTIVITY_SERVICE); | |
NetworkInfo netInfo = cm.getActiveNetworkInfo(); | |
return netInfo != null && netInfo.isConnectedOrConnecting(); | |
} | |
public boolean isOnline() { | |
try { | |
int timeoutMs = 1500; | |
Socket sock = new Socket(); | |
SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 80); | |
sock.connect(sockaddr, timeoutMs); | |
sock.close(); | |
return true; | |
} catch (IOException e) { return false; } | |
} | |
public void setOnStatusListener(onStatus ons){ | |
this.ons=ons; | |
new getOnlineStatus().execute(); | |
} | |
private class getOnlineStatus extends AsyncTask<Void,Void,Boolean> { | |
@Override | |
protected Boolean doInBackground(Void[] p1) { | |
return isOnline(); | |
} | |
@Override | |
protected void onPostExecute(Boolean result) { | |
ons.gotStatus(result); | |
super.onPostExecute(result); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cara menggunakan, ada 2 CARA