package com.latinsud.wificonnect;


import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiManager;
import android.os.Bundle;

/*
 Try to fix a problem in RCMod 3.x on Geeksphone One that Wifi doesn't always connect.
 
 Requirements:
	- Have said hardware and software version.
	- Have the wifi network already configured.
	- Be near the AP.

 Usage:
   - Just open the application and wait. It will close when done.
   - Hopefully it will connect right after closing.
*/

public class WCActivity extends Activity {
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
       	WifiManager wm;
       	wm=(WifiManager) getSystemService(Context.WIFI_SERVICE);

      	// Enable Wifi (if not enabled)
       	wm.setWifiEnabled(true);
            	
       	try {
       		Thread.sleep(500);
       	} catch (Exception e) { ; }	
       	
       	// Force disconnect of previously connected network
       	wm.disconnect();
            	
        // Wait until supplicant connects
        while (wm.getConnectionInfo().getSupplicantState() != SupplicantState.COMPLETED) {
        	try {
        		Thread.sleep(100);            		
        	} catch (Exception e) { ; }
        }

        // Force dhcp relaunch
        ContentResolver cr = getContentResolver();
        int dhcpState=android.provider.Settings.System.getInt(cr, android.provider.Settings.System.WIFI_USE_STATIC_IP, 1);	           	 
        android.provider.Settings.System.putInt(cr, android.provider.Settings.System.WIFI_USE_STATIC_IP, 1-dhcpState);
        try {
        	Thread.sleep(100);
        } catch (Exception e) { ; }
        android.provider.Settings.System.putInt(cr, android.provider.Settings.System.WIFI_USE_STATIC_IP, dhcpState);
        
        // Exit happily
        finish();
    }   
}