Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.rabinkaspal.mobikart.helpers;
- import android.app.AlertDialog;
- import android.content.Context;
- import android.content.DialogInterface;
- import android.content.DialogInterface.OnClickListener;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- import android.util.Log;
- import android.widget.Toast;
- import com.rabinkaspal.mobikart.R;
- public class NetworkUtil {
- public static int TYPE_WIFI = 1;
- public static int TYPE_MOBILE = 2;
- public static int TYPE_NOT_CONNECTED = 0;
- private static boolean isConnected = false;
- public static int getConnectivityStatus(Context context) {
- ConnectivityManager cm = (ConnectivityManager) context
- .getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
- if (null != activeNetwork) {
- if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
- return TYPE_WIFI;
- if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
- return TYPE_MOBILE;
- }
- return TYPE_NOT_CONNECTED;
- }
- public static String getConnectivityStatusString(Context context) {
- int conn = NetworkUtil.getConnectivityStatus(context);
- String status = null;
- if (conn == NetworkUtil.TYPE_WIFI) {
- status = "Wifi enabled";
- } else if (conn == NetworkUtil.TYPE_MOBILE) {
- status = "Mobile data enabled";
- } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
- status = "Not connected to Internet";
- }
- return status;
- }
- public static void checkConnection(final Context context) {
- if(!isNetworkAvailable(context)){
- AlertDialog.Builder alert = new AlertDialog.Builder(context);
- alert.setTitle("Information");
- alert.setIcon(R.drawable.ic_launcher);
- alert.setMessage("Not connected to the internet.");
- alert.setPositiveButton("Retry", new OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- if(!isConnected){checkConnection(context);}
- else{
- Log.d("1", "asdf");
- Toast.makeText(context, "is connected", Toast.LENGTH_SHORT).show();
- dialog.cancel();}
- }
- });
- alert.show();
- }else{Toast.makeText(context, "is connected", Toast.LENGTH_SHORT).show();}
- }
- public static boolean isNetworkAvailable(Context context) {
- ConnectivityManager connectivity = (ConnectivityManager) context
- .getSystemService(Context.CONNECTIVITY_SERVICE);
- if (connectivity != null) {
- NetworkInfo[] info = connectivity.getAllNetworkInfo();
- if (info != null) {
- for (int i = 0; i < info.length; i++) {
- if (info[i].getState() == NetworkInfo.State.CONNECTED) {
- if (!isConnected) {
- isConnected = true;
- // do your processing here ---
- // if you need to post any data to the server or get
- // status
- // update from the server
- }
- return true;
- }
- }
- }
- }
- isConnected = false;
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement