Connect to WIFI using Android NFC phone and NFC tag.

Standard

Target:

The target is to make a small little app with which you can scan a NFC tag and you phone will be connected to the local wifi automatically. This app has to be installed in the phone. The wifi name and password has to be written in a NFC tag.

When users tap his phone on the NFC tag, the phone will read the wifi name and password from the NFC tag and will connect with the wifi. At this point the app will display a confirmation that you are connected to the wifi. There will be a ‘close’ button. When users click the button, the app will be closed and you will be able to use the connected wifi.

You need:

1. You need an Android phone with NFC capabilities.
2. A NFC tag
3. A free NFC writer app from google play
4. Local wifi (to test with if you dont have wifi at work or home, you can make an wifi hot spot from another phone)

To do (code and other things)

Step 1:

Create an android project with Eclipse with the minimum SDK version 10.
In the manifest file you need to use NFC hardware and also give permission to wifi and NFC.

The file more or less should look like the below:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.seibatoron.wificonnect"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<uses-feature
android:name="android.hardware.nfc"
android:required="true" />
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="17" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.seibatoron.wificonnect.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />

<category android:name="android.intent.category.DEFAULT" />

<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED" />

<category android:name="android.intent.category.DEFAULT" />

<data android:mimeType="text/plain" />
</intent-filter>
</activity>
</application>

</manifest>

Step 2:

In the layout file I will ad two element. One TextView and a Button. The textview will display te confirmation that users are connected or not and if users click on the button, the app will be closed.

This is how the code should look like;

<TextView
 android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/wifiname"
android:layout_centerVertical="false"
android:textSize="35sp"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:layout_marginBottom="10dp"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/close"
android:text="Close"
android:layout_below="@+id/wifiname"
/>

Step 3:

Now in the MainActivity, there are two things to consider. We have to read from the NFC tag and also connect to wifi.

import java.util.List;

import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
private EditText wifiname;
private String password;
private  NfcAdapter mAdapter;
private  PendingIntent mPendingIntent;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mAdapter = NfcAdapter.getDefaultAdapter(this);
		// Create a generic PendingIntent that will be deliver to this activity.
		// The NFC stack
		// will fill in the intent with the details of the discovered tag before
		// delivering to
		// this activity.
		mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
				getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

		// Setup an intent filter for all MIME based dispatches
		IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);

		WifiManager wifiMgr = (WifiManager)getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
		String connectionName = wifiInfo.getSSID();

		TextView tv=(TextView)findViewById(R.id.wifiname);
		if(connectionName==null){
			tv.setText("You are not connected :(");
		}else{

			tv.setText("You are connected to: "+connectionName+" :) ");
		}

		Button close=(Button)findViewById(R.id.close);
		close.setOnClickListener(new OnClickListener() {

	        @Override
	        public void onClick(View v) {
	            // TODO Auto-generated method stub
	            finish();
	            System.exit(0);
	        }
	    });

	}
	@Override
	public void onResume(){
		super.onResume();

		if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(getIntent().getAction())||NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())){
			processReadIntent(getIntent());
		}
	}
	@Override
	public void onNewIntent(Intent intent){
		setIntent(intent);
	}
	public void processReadIntent(Intent intent){
		Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
                NfcAdapter.EXTRA_NDEF_MESSAGES);

        // only one message sent during the beam
        NdefMessage msg = (NdefMessage) rawMsgs[0];

        // record 0 contains the MIME type, record 1 is the AAR, if present
        Log.d("msg", msg.getRecords()[0].getPayload().toString());

        byte[]payload=msg.getRecords()[0].getPayload();
        String msgtext=null;
        try{

        //Get the Text Encoding
        String textEncoding = ((payload[0] & 0200) == 0) ? "UTF-8" : "UTF-16";

        //Get the Language Code
        int languageCodeLength = payload[0] & 0077;
        String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");

        //Get the Text
        msgtext = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
        }catch(Exception e){

        }

        // splitting the message by comma. The first part is the name and 2nd part is the password.
        String[]tagdata=msgtext.split(",");

        String networkSSID = tagdata[0].toString();
		String networkPass = tagdata[1].toString();

		WifiConfiguration conf = new WifiConfiguration();
		conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain ssid in quotes

		conf.preSharedKey = "\""+ networkPass +"\"";
		WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE); 
		wifiManager.addNetwork(conf);

		List list = wifiManager.getConfiguredNetworks();
		for( WifiConfiguration i : list ) {
		    if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
		         wifiManager.disconnect();
		         wifiManager.enableNetwork(i.networkId, true);
		         wifiManager.reconnect();               
		         break;
		    }           
		 }

		TextView wifiname=(TextView)findViewById(R.id.wifiname);
		wifiname.setText("You are now connected to"+networkSSID +" :) ");

	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}

Thats is…..

Step 4:

Now get your NFC tag, write network name and password (separate by comma) into the tag using any tag writer app.
Get your phone, tap the phone to the tag and voila.

happy coding.

 

About these ads

2 responses »

  1. Pingback: NFC Example Source Code Does Not Read NFC Tags (without modification) - How-To Video

  2. Pingback: NFC Example Source Code Does Not Read NFC Tags (without modification) | BlogoSfera

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s