package org.jivesoftware.smack;

import org.jivesoftware.smackx.ConfigureProviderManager;
import org.jivesoftware.smackx.InitStaticCode;
import org.xbill.DNS.ResolverConfig;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

public class SmackAndroid {
    private static SmackAndroid sSmackAndroid = null;

    private BroadcastReceiver mConnectivityChangedReceiver;
    private Context mCtx;

    private SmackAndroid(Context ctx) {
        ConfigureProviderManager.configureProviderManager();
        InitStaticCode.initStaticCode(ctx);
	maybeRegisterReceiver();
        mCtx = ctx;
    }

    public static SmackAndroid init(Context ctx) {
        if (sSmackAndroid == null) {
            sSmackAndroid = new SmackAndroid(ctx);
        } else {
	    sSmackAndroid.maybeRegisterReceiver();
        }
        return sSmackAndroid;
    }

    public void onDestroy() {
	if (mConnectivityChangedReceiver != null) {
	    mCtx.unregisterReceiver(mConnectivityChangedReceiver);
	    mConnectivityChangedReceiver = null;
	}
    }

    private void maybeRegisterReceiver() {
	if (mConnectivityChangedReceiver == null) {
	    mConnectivityChangedReceiver = new ConnectivtyChangedReceiver();
	    mCtx.registerReceiver(mConnectivityChangedReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
	}
    }

    class ConnectivtyChangedReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            ResolverConfig.refresh();
        }

    }
}

@@ -513,32 +513,52 @@
 (Context ctx) %7B%0A
+        mCtx = ctx;%0A
         Configur
@@ -646,17 +646,24 @@
 e(ctx);%0A
-%09
+        
 maybeReg
@@ -679,36 +679,16 @@
 iver();%0A
-        mCtx = ctx;%0A
     %7D%0A%0A 

Set context first to avoid NPE. Fixes #18