= =
Tworzenie aplikacji na WP. Blog dotyczący.net oraz WP. Kursy Walut: - 30k ściągnięć, - 1k ocen, - średnia ocena 4,5, - 3 miejsce w rankingu najczęściej pobieranych płatnych aplikacji. Ponad 300k ściągnięć aplikacji.
W 2015 roku już 42,3% platności mobilnych odbywać się będzie przy pomocy technologii NFC.
NFC (Near Field Communication) jest to komunikacja bezprzewodowa niewielkiego zasięgu. Umożwia ona przenoszenie informacji między telefonem, a innym urządzeniem NFC (telefon, tag, urządzenia płatnicze). Tagi NFC małe, pasywne urządzenia z zaprogramowanymi informacjami.
Typ sieci Peer-to-peer Point-to-multipoint Zasięg < 0,1 m 10 m (max 100 m) Tryb Aktywny / Pasywny Aktywny Prędkość 424 kbit/s 40 Mbit/s Bezpieczeństwo Wysokie Dobre Czas nawiązywania połączenia <0,1 s <6 s
Najczęściej NFC w telefonie jest wykorzystywane do parowania urządzeń, przesyłania danych pomiędzy urządzeniami oraz odczytywania danych zapisanych na tagach NFC.
Zobaczmy jak to działa
Coś co mogło być wielkim sukcesem, a wyszło jak zwykle. W Polsce ta funkcjonalność nie działa pomimo, że jest promowana.
Ultralight (UL) 48 41 39 Typ 2 Ultralight C (ULC) 148 132 130 Typ 2 NTAG203 144 132 130 Typ 2 MiFare 1K 1024 256 709 Classic (1) DESFire EV1 2k 2048 Typ 4 DESFire EV1 4k 4096 Typ 4 DESFire EV1 8k 8192 Typ 4 Sony FeliCa 4K 4096 Typ 3 Sony FeliCa Lite 224 Typ 3 Topaz 512 Typ 1 Telefony z WP wspierają tagi sformatowane w standardzie NDEF (NFC Data Exchange Format). Należy o tym pamiętać przy ich kupnie.
Zapis z hasłem Zapis Tylko odczyt Windows Phone 8 jest w stanie odczytać każdy z tych tagów. W przypadku zapisu nie ma możliwości zabezpieczenia taga przed zmianą. Zaleca się zamówić od razu odpowiednio zaprogramowany i zabezpieczony pakiet tagów ze sklepu.
Brak możliwości zabezpieczenia przed zapisem tagów. Brak możliwości sformatowania tagów do NDEF. Aby działały z naszym telefonem należy kupić sformatowane tagi lub użyć urządzania wspierającego formatowanie (np. Android). W przypadku uszkodzenia taga też nie jesteśmy w stanie go naprawić. Tagi mogą zawierać tylko wiadomość w formacie NDEF. Brak możliwości użycia całej dostępnej pamięci taga znaczniki, korekcja błędów, API nie wspiera zapisywania wiadomości w formacie NDEF domyślnie. Możemy to zrobić przygotowując wiadomość w formacie binarnym lub posłużyć się zewnętrzną biblioteką. Urządzenie domyślnie nie jest w stanie odczytać wszystkich wiadomości zapisanych na tagu. System wspiera odczyt tylko pierwszej wiadomości. Dodatkowe mogą być odczytane za pomocą własnej aplikacji. Nie ma możliwości odczytania taga przez aplikację działającą w tle.
Udostępnij zdjęcie
CameraCaptureTask cameracapturetask = new CameraCaptureTask(); cameracapturetask.completed +=(senderobject, photoresult) => { if (photoresult.taskresult == TaskResult.OK) { ShareMediaTask sharemediatask = new ShareMediaTask(); sharemediatask.filepath = photoresult.originalfilename; sharemediatask.show(); } }; cameracapturetask.show();
Wykrywanie urządzenia NFC
Należy wskazać funkcjonalności, które nasza aplikacja będzie wykorzystywać NFC to IP_CAP_PROXIMITY. Często od razu można włączyć IP_CAP_NETWORKING. Należy określić wymagania, które ma spełniać telefon ID_REQ_NFC. Telefony bez NFC nie będą widziały tej aplikacji w Windows Store.
ProximityDevice proximitydevice = ProximityDevice.GetDefault(); if (proximitydevice!= null) { // Urządzenie ma moduł NFC proximitydevice.devicearrived += proximitydevice_devicearrived; proximitydevice.devicedeparted += proximitydevice_devicedeparted; } else { // Brak modułu NFC }
Odczyt taga NFC
ProximityDevice proximitydevice = ProximityDevice.GetDefault(); if (proximitydevice!= null) { long subscribedmessageid = proximitydevice.subscribeformessage("writeabletag", Handler); } void Handler(ProximityDevice device, ProximityMessage message) { int writablesize = BitConverter.ToInt32(message.Data.ToArray(), 0); this.showmessage("messagetype: " + message.messagetype + "\n" + "DataAsString:" + message.dataasstring + "\n" + "SubscriptionId: " + message.subscriptionid + "\n" + "Size of tag: " + writablesize + "\n"); } proximitydevice.stopsubscribingformessage(subscribedmessageid);
The message contains binary data. The message data contains an URI (UTF-16LE encoded string). No subtype. The message data is of a specific MIME type. For example, if the message data is a JPEG image, the message type is WindowsMime.image/jpeg. Same as the Windows protocol, except that the content is intended to be written to a static tag. The message is not transmitted to any device except a writable static tag. This protocol is only valid for publications. Same as the WindowsUri protocol, except that the content is intended to be written to a static tag. The message is not transmitted to any device except a writable static tag. This protocol is only valid for publications. No subtype. Write a tag that can be used to launch a specific app with optional launch parameters. If you publish a LaunchApp:WriteTag message to a tag the result when that tag is tapped to a computer is the same as calling the PeerFinder.Start method and passing your launch parameters. When subscribing for this message protocol, if a writable tag is brought in to proximity, a proximity message is received that contains an int32 (little endian) indicating the maximum writable size of the tag. This protocol is only valid for subscriptions. The message contents are properly formatted NDEF records. The underlying type of the content for a publication using NDEF as the message type is contained in the NDEF records. A subscription for the NDEF type subscribes to all NDEF formatted messages. The message data is application defined NDEF records (TNF field value of 0x04). This protocol only applies to subscriptions; when publishing NDEF content, use NDEF. The message data is a properly formatted NDEF mime message (TNF field value of 0x02). For example,ndef:mime.image/jpeg. This protocol only applies to subscriptions; when publishing NDEF content, use NDEF. The message data is a properly formatted NDEF message of a type defined by a URI namespace (TNF field value of 0x03).This protocol only applies to subscriptions; when publishing NDEF content, use NDEF. This means that the data format is identified by the specified URI. The message data is a properly formatted NDEF message of a type defined by the NFC forum (TNF field value of 0x01).An example of this type isndef:wkt.u for the well known type of URI. This protocol only applies to subscriptions; when publishing NDEF content, use NDEF. The message data should be written to an NFC forum standard static tag. The message data must be in a proper NDEF format. This protocol is only valid for publications. The message data is an untyped NDEF message (TNF field value of 0x05).This protocol only applies to subscriptions; when publishing NDEF content, use NDEF.
Publikacja taga NFC
this.proximitydevice.publishmessage("windows.samplemessage", "Hello World", Handler); this.proximitydevice.publishurimessage(new System.Uri("http://www.onet.pl", Handler); this.proximitydevice.publishbinarymessage("windows:writetag.mysubtype", Encoding.Unicode.GetBytes("Hello World").AsBuffer(), Handler); Uri uri = new Uri("http://www.wp.pl"); byte[] buffer = Encoding.Unicode.GetBytes(uri.ToString()); proximitydevice.publishbinarymessage("windowsuri:writetag", buffer.asbuffer(), Handler); private void Handler(ProximityDevice sender, long messageid) { this.proximitydevice.stoppublishingmessage(messageid); this.showmessage("wysłano / Zapisano!"); }
this.subscribedmessageid = this.proximitydevice.subscribeformessage( "Windows.mySubType", Handler2); private void Handler2(ProximityDevice device, ProximityMessage message) { this.proximitydevice.stopsubscribingformessage( this.subscribedmessageid); } byte[] buf = message.data.toarray(); this.showmessage("messagetype: " + message.messagetype + "\n" +"Data:"+Encoding.Unicode.GetString(buf, 0, buf.length)+"\n" + "SubscriptionId: " + message.subscriptionid + "\n");
Uruchomienie aplikacji
Uri uri = new Uri("ms-drive-to:? destination.latitude=52.199506& destination.longitude=21.041737& destination.name=4developers"); byte[] buffer = Encoding.Unicode.GetBytes(uri.ToString()); proximitydevice.publishbinarymessage("windowsuri:writetag", buffer.asbuffer(), MessageTransmittedHandler);
Launches the web browser and navigates to the specified URL. Launches the email app and creates a new message with the specified email address on the To line. Note that the email is not sent until the user taps send. Launches the Account Settings app. Launches the Airplane Mode Settings app. Launches the Bluetooth Settings app. Launches the Cellular Settings app. Launches the email and accounts settings app. Launches the Location Settings app. Launches the Lock Screen settings app. Launches the Wi-Fi Settings app. Launches the Windows Phone Store and shows the details page for the specified app. Launches the Store and shows the review page for the calling app. Launches the Store and shows the review page for the specified app. Note that you must prepend app to the ID for the specified app. For example, the URI for reviewing an app with the ID fdf05477-814e-41d4-86cd-25d5a50ab2d8 would be zune:reviewapp?appid=appfdf05477-814e- 41d4-86cd-25d5a50ab2d8 Launches the Store and searches for apps by keyword. Launches the Store and searches for items by publisher name.
Dodanie obsługi własnego protokołu do aplikacji
... </Tokens> <Extensions> <Protocol Name="developers" NavUriFragment="encodedLaunchUri=%s" TaskID="_default" /> </Extensions> <ScreenResolutions>...
class AssociationUriMapper : UriMapperBase { private string tempuri; public override Uri MapUri(Uri uri) { this.tempuri = System.Net.HttpUtility.UrlDecode(uri.ToString()); if (this.tempuri.contains("developers:mainpage?param=")) { int categoryindex = this.tempuri.indexof("param=") + 6; string param = this.tempuri.substring(categoryindex); return new Uri("/MainPage.xaml?Param=" + param, UriKind.Relative); } // Zwykłe uruchomienie naszej aplikacji return uri; } } // Trzeba dodać go do App.cs: RootFrame = new PhoneApplicationFrame(); RootFrame.UriMapper = new AssociationUriMapper();
// Odczyt parametru: protected override void OnNavigatedTo(NavigationEventArgs e) { if (NavigationContext.QueryString.ContainsKey("Param")) { this.showmessage(navigationcontext.querystring["param"]); } base.onnavigatedto(e); } // Zapis to już znamy: Uri uri = new Uri("developers:MainPage?Param=HelloWorld"); byte[] buffer = Encoding.Unicode.GetBytes(uri.ToString()); proximitydevice.publishbinarymessage("windowsuri:writetag", buffer.asbuffer(), MessageTransmittedHandler);
Wadą jest dość duży rozmiar zajmowany przez dane na tagu. Jednakże instaluje ścisle wybraną aplikację.
Wiadomość typu NDEF
Standard zapisu wiadomości na urządzeniach wykorzystujących NFC do komunikacji. Specyfikacja dostępna na: http://www.nfc-forum.org/specs/spec_list/ Windows Phone potrafi domyślnie odczytać tylko pierwszy rekord z wiadomości. Pozostałe rekordy mogą być odczytane przez dodatkowe programy.
Windows Phone pozwala na zapis wiadomości w formacie NDEF, ale w formacie binarnym. Zanim zapiszemy wiadomość musimy sami ją przygotować. Alternatywnie można użyć biblioteki: NDEF Library (http://ndef.codeplex.com/).
// Zapis: NdefUriRecord urirecord = new NdefUriRecord { Uri = "http://4developers.org.pl"}; NdefMessage message = new NdefMessage { urirecord }; ProximityDevice.GetDefault().PublishBinaryMessage("NDEF:WriteTag", message.tobytearray().asbuffer(), MessageTransmittedHandler); // Odczyt ProximityDevice.GetDefault().SubscribeForMessage("NDEF", MesReceivedHan); void MesReceivedHan (ProximityDevice sender, ProximityMessage message) { byte[] rawmsg = message.data.toarray(); var ndefmessage = NdefMessage.FromByteArray(rawMsg); foreach (NdefRecord record in ndefmessage) { if (NdefUriRecord.IsRecordType(record)) { var urirecord = new NdefUriRecord(record); ShowMessage("URI: " + urirecord.uri); } }
Automatyczne nawiązywanie połączenia
// Rozpoczęcie konfiguracji połączenia PeerFinder.TriggeredConnectionStateChanged += OnTriggeredConnectionStateChanged; PeerFinder.AllowBluetooth = true; PeerFinder.AllowWiFiDirect = true; PeerFinder.Start(); private void OnTriggeredConnectionStateChanged(object sender, TriggeredConnectionStateChangedEventArgs args) { switch (args.state) { case TriggeredConnectState.Listening: // Łączenie jako host break; case TriggeredConnectState.PeerFound: // Zakończono używania NFC - połączenie wykorzystuje Wi-Fi, Bluetooth. // Można odsunąć urządzenia. break; case TriggeredConnectState.Connecting: // Łączenie... break; case TriggeredConnectState.Completed: // Połączenie ustanowiono streamsocket = args.socket; break; case TriggeredConnectState.Canceled: break; case TriggeredConnectState.Failed: // Nastąpił błąd - trzeba jeszcze raz spróbować break;
How to use emulators to develop NFC features on WP8 Proximity for Windows Phone 8 (MSDN) Use NFC tags with Windows Phone 8 (Nokia) NDEF Library for Proximity APIs (NFC)
< >