Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a string using NFC from a windows phone 8 to an android device

haven't had any luck using google for this so I thought i'd ask.

Does anyone have any experience / know how to send a simple string i.e "hello" from a Windows Phone 8 device to an Android Device?

so far we have been able to do android -> android and android -> windows phone 8 but we haven't been able to find out how to do from windows phone 8 to android.

Has anyone seen a guide online or know how to do such a thing?

The first step I guess would be to find out how to make the application on windows phone 8 realize its near an android NFC device .. and then it would be to figure out how to make the application on the android phone receive the message.

Thanks in advance!

* Answer *

Alright so here are some answers/tips

I ended up sending the NFC messages as external type because sending application/my.mimetype kept giving me a "sorry your phone cant recorgnize this type of file" on the windows phone even though the message was getting through.

@Override
public NdefMessage createNdefMessage(NfcEvent event) {

    NdefMessage ndefMessage = new NdefMessage(( 
            new NdefRecord[] {createMimeRecord("packageName:externalType",docId.getBytes())}));

    return ndefMessage;
}

public NdefRecord createMimeRecord(String mimeType, byte[] payload) {
    byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII"));
    NdefRecord mimeRecord = new NdefRecord(NdefRecord.TNF_EXTERNAL_TYPE, mimeBytes, new byte[0], payload);
    return mimeRecord;
}

all you have to do in android is to follow the android example from the SDK samples (android-16/17 - AndroidBeamDemo) which is explained extremely thoroughly here - http://www.tappednfc.com/wp-content/uploads/TAPPED-NFCDeveloperGuide-Part1.pdf

but instead of using application mimetype use the above external type and in your manifest put the following instead of the mimetype in the intent filter:

                <data
                android:host="ext"
                android:pathPrefix="/cco.drugformulary:externalType"
                android:scheme="vnd.android.nfc" />

regarding reading and sending the message from the windows phone you can use what the accepted answer guy said to do and it should work but for the type put cco.drugformulary:externalType as from above (your project name of course though).

If you are running into any problems feel free to ask me

like image 546
krilovich Avatar asked Dec 20 '12 20:12

krilovich


People also ask

What is NFC permission?

Near Field Communication (NFC) is a set of short-range wireless technologies, typically requiring a distance of 4cm or less to initiate a connection. NFC allows you to share small payloads of data between an NFC tag and an Android-powered device, or between two Android-powered devices.

How do I know what type of NFC tag I have?

Small quantities of NFC tags can be tested by manually using an NFC enabled mobile device and an app such as the GoToTags Android App or GoToTags iOS App. For larger quantities of NFC tags, setting up a testing station using the GoToTags Windows App and an NFC reader might be more appropriate.


1 Answers

When using WP8 NFC there's fundamentally two types of messages you can work with: windows-specific messages and NDEF messages. Windows specific messages are easy to spot since you'll be publishing them as "Windows.*" message types. NDEF messages however get published using the "NDEF" message type. For example, here's a Windows app-specific message:

    private void WriteAppSpecificStringToTag(object sender, RoutedEventArgs e)
    {
        ProximityDevice device = ProximityDevice.GetDefault();

        if (device != null)
        {
            device.PublishBinaryMessage("Windows:WriteTag.myApp",
                GetBufferFromString("Hello World!"),
                UnregisterOnSend);

            MessageBox.Show("Tap to write 'Hello World' on tag.");
        }
    }

NDEF is a heavily used cross-platform format meant to optimize for the extremely space constrained environment of NFC tags (often under 100 bytes). While the WP8 Proximity framework allows sending & receiving NDEF messages it doesn't know anything about the NDEF format. Meaning, the WP8 proximity framework sends and receives a stream of bytes. Parsing that stream of bytes and formatting it correctly is your responsibility as the app developer.

In order to format & parse NDEF messages you'll need to either use a 3rd party framework or build your own. In terms of 3rd party frameworks NDEF Library for Proximity APIs does a great job.

For example, here's how to format and write an app-specific NDEF message using the NDEF Library:

    private void WriteNDEFRecordToTag(object sender, RoutedEventArgs e)
    {
        ProximityDevice device = ProximityDevice.GetDefault();

        if (device != null)
        {
            device.PublishBinaryMessage("NDEF:WriteTag",
                new NdefMessage()
                {
                    new NdefRecord
                    {
                        TypeNameFormat = NdefRecord.TypeNameFormatType.ExternalRtd,
                        Type = "myApp".Select(c => (byte) c).ToArray(),
                        Payload = "Hello World!".Select(c => (byte) c).ToArray()
                    }
                }.ToByteArray().AsBuffer(),
                UnregisterOnSend);

            MessageBox.Show("Tap to write 'Hello World' on tag.");
        }
    }

And here's how to receive and parse NDEF messages in your app:

    private void ReadNDEFRecordFromTag(object sender, RoutedEventArgs e)
    {
        ProximityDevice device = ProximityDevice.GetDefault();

        if (device != null)
        {
            device.SubscribeForMessage("NDEF", ndefMessageRecieved);

            MessageBox.Show("Registered to NFC tag. Tap with NFC tag.");
        }
    }

    private void ndefMessageRecieved(ProximityDevice sender, ProximityMessage message)
    {
        var ndefMessage = NdefMessage.FromByteArray(message.Data.ToArray());

        StringBuilder sb = new StringBuilder();
        foreach (NdefRecord record in ndefMessage)
        {
            sb.AppendLine(Encoding.UTF8.GetString(record.Payload, 0, record.Payload.Length));
        }
        Dispatcher.BeginInvoke(() => MessageBox.Show(sb.ToString()));
    }

When we run this code snippet on WP8 and tap the previously written NDEF tag we can see the following message:

MessageBox saying Hello World

And if we take the same NFC tag and use Android's NFC TagInfo app we can see the same data:

NfcTag Info data on Android

In case you're wondering what actually gets transmitted/trasnfered when you use NDEF, here's GoToTags Windows App on the tag we just use:

GoToTags showing the binary data stored in the NDEF tag

If NDEF Library feels a bit heavy for you, you can always crank out your on homegrown NDEF formatter and parser. There's a good example of that in this Nokia OSS project @ NFC Tag Reader

Regarding NFC phone-to-phone vs. NFC phone-to-tag, the code snippets above will work for either scenario. In case you want to write to a tag, simlpy keep the ":WriteTag" operation in the message type. In case you want to communicate directly with a nearby phone just remove the ":WriteTag" operation. Both work fine with WP8<=>Android.

Do note though that there are differences in how Android & WP8 address NDEF. WP8 can only read the first NDEF record in a message, whereas Android can read all NDEF records. Android can work with non NDEF-formatted tags and format those; WP8 has to use NDEF formatted tags.

like image 185
JustinAngel Avatar answered Oct 25 '22 22:10

JustinAngel