Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Check Network Connectivity available or not
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);
}
}
}
@agusibrahim

This comment has been minimized.

Copy link
Owner Author

agusibrahim commented Jul 2, 2017

Cara menggunakan, ada 2 CARA

ConnectionStatus cs = new ConnectionStatus(CONTEXT);
// CARA 1: cek apakah data seluler aktif
boolean isDatacellActivated=cs.isNetworkAvailable();
// CARA 2: cek apakah data selular bisa konek (ada kuota) secara async
cs.setOnStatusListener(new ConnectionStatus.onStatus(){
							@Override
							public void gotStatus(boolean isOnline) {
								  // do action here
							}
						});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.