Inheritance: Parcelable
        public static void startReceiver(Activity act)
        {
            activity = act;
            if (!registeredReceiver)
            {
                Log.d(TAG, "!!#######!! Registering console receiver");

                IntentFilter filter = new IntentFilter();
                filter.addAction(CONSOLE_INTENT);
                act.registerReceiver(receiver, filter);
                registeredReceiver = true;
            }
            else
            {
                Log.d(TAG, "!!!!!!!!!!! Already registered console receiver!");
            }
        }
        protected override void onResume()
        {
            base.onResume();
            var intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);

            registerReceiver(downloadReceiver, intentFilter);
        }
		public override void replacePreferredActivity (IntentFilter filter, int match, ComponentName[] set, ComponentName activity)
		{
			throw new NotImplementedException ();
		}
 public override Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter)
 {
     throw new NotImplementedException();
 }
        public override int onStartCommand(Intent value0, int value1, int value2)
        {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ACTION);
            //registerReceiver(notifyServiceReceiver, intentFilter);


            // Send Notification
            var notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

            var Title = "Notification!";

            var TargetUri = "http://www.jsc-solutions.net";

            if (value0.hasExtra("data0"))
                Title = value0.getStringExtra("data0");

            if (value0.hasExtra("data1"))
                TargetUri = value0.getStringExtra("data1");


            var myNotification = new Notification(
                // http://docs.since2006.com/android/2.1-drawables.php
                android.R.drawable.ic_menu_view,
                Title,
                //java.lang.JavaSystem.currentTimeMillis()
                java.lang.System.currentTimeMillis()
            );

            var context = getApplicationContext();

            var myIntent = new Intent(Intent.ACTION_VIEW,
                android.net.Uri.parse(TargetUri));

            var pendingIntent = PendingIntent.getActivity(
                getBaseContext(),
                0, myIntent,
                Intent.FLAG_ACTIVITY_NEW_TASK
            );

            myNotification.defaults |= Notification.DEFAULT_SOUND;
            myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
            myNotification.setLatestEventInfo(context,
                    Title,
                    TargetUri,
               pendingIntent);
            notificationManager.notify(1, myNotification);


            this.stopSelf();

            return 0;
        }
        public async Task batteryStatusCheck()
        {

            // http://developer.android.com/training/monitoring-device-state/battery-monitoring.html
            // http://stackoverflow.com/questions/20663403/android-batterymanager-not-reporting-correct-charging-status
            // X:\jsc.svn\core\ScriptCoreLib\JavaScript\BCLImplementation\System\Net\WebClient.cs

            Console.WriteLine("enter batteryStatus");

#if DEBUG
            batteryStatus = new Random().NextFloat();
            isCharging = new Random().NextDouble() > 0.5;


            //return Task.FromResult(new object());
#else


            // partial build?
            var ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

            var intent = global::ScriptCoreLib.Android.ThreadLocalContextReference.CurrentContext.registerReceiver(null, ifilter);


            // I/System.Console(11387): { batteryStatus = Intent { act=android.intent.action.BATTERY_CHANGED flg=0x60000010 (has extras) }, isCharging = false }
            int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);


            // X:\jsc.svn\examples\java\Test\TestJavaFinalIntegerField\TestJavaFinalIntegerField\Foo\Bar.java
            //isCharging = (chargePlug > 0);
            isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING;

            Console.WriteLine("batteryStatusCheck " + new { status, chargePlug, isCharging });



            // http://developer.android.com/reference/android/os/BatteryManager.html
            // ???
            // is our java natives for android messing up const int?
            //public const int BATTERY_PLUGGED_AC = 0;
            //        public const int BATTERY_PLUGGED_USB = 0;
            //        public const int BATTERY_PLUGGED_WIRELESS = 0;

            //batteryStatusCheck { status = 3, chargePlug = 0 }
            //{ batteryStatus = Intent { act=android.intent.action.BATTERY_CHANGED flg=0x60000010 (has extras) }, isCharging = true }


            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

            // are floats correctly serialize from android?
            this.batteryStatus = level / (float)scale;

            // android webview does not get our floats?
            Console.WriteLine(new { this.batteryStatus, intent, isCharging });
            //I/System.Console(11110): { batteryStatus = 0.8, intent = Intent { act=android.intent.action.BATTERY_CHANGED flg=0x60000000 (has extras) }, isCharging = true }

            //return Task.FromResult(batteryPct);
#endif

        }
        public override int onStartCommand(Intent value0, int value1, int value2)
        {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ACTION);
            registerReceiver(notifyServiceReceiver, intentFilter);


            // Send Notification
            var notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

            var myNotification = new Notification(
                android.R.drawable.star_on,
                (CharSequence)(object)"Notification!",
                java.lang.System.currentTimeMillis()
            );

            Context context = getApplicationContext();

            Intent myIntent = new Intent(Intent.ACTION_VIEW, android.net.Uri.parse("http://www.jsc-solutions.net"));

            PendingIntent pendingIntent
              = PendingIntent.getActivity(getBaseContext(),
                0, myIntent,
                Intent.FLAG_ACTIVITY_NEW_TASK);
            myNotification.defaults |= Notification.DEFAULT_SOUND;
            myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
            myNotification.setLatestEventInfo(context,
                    (CharSequence)(object)"The title that goes in the expanded entry.",
                    (CharSequence)(object)"The text that goes in the expanded entry.",
               pendingIntent);
            notificationManager.notify(1, myNotification);


            return base.onStartCommand(value0, value1, value2);
        }
        public override int onStartCommand(Intent value0, int value1, int value2)
        {
            // http://stackoverflow.com/questions/14182014/android-oncreate-or-onstartcommand-for-starting-service


            new Thread(
                delegate()
                {
                    var sw = Stopwatch.StartNew();

                    while (true)
                    {
                        var xmyPid = android.os.Process.myPid();

                        // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150612/ovroculus360photoshud
                        // cpu 
                        Console.WriteLine(new { xmyPid, Thread.CurrentThread.ManagedThreadId, sw });

                        // "x:\util\android-sdk-windows\platform-tools\adb.exe" uninstall AndroidBootServiceNotificationActivity.Activities
                        Thread.Sleep(1000);
                    }
                }
            ) { Name = "namedthread1" }.Start();

            var myPid = android.os.Process.myPid();

            var intentFilter = new IntentFilter();
            intentFilter.addAction(ACTION);
            registerReceiver(notifyServiceReceiver, intentFilter);


            #region Send Notification
            var notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

            var myNotification = new Notification(
                android.R.drawable.star_on,
                //(CharSequence)(object)"Boot!!",
                "Boot!!" + new { myPid },

                when: 0

            //java.lang.System.currentTimeMillis()
            );

            var context = getApplicationContext();

            var myIntent = new Intent(Intent.ACTION_VIEW, android.net.Uri.parse("http://youtube.com"));

            var pendingIntent
              = PendingIntent.getActivity(getBaseContext(),
                0, myIntent,
                Intent.FLAG_ACTIVITY_NEW_TASK);
            myNotification.defaults |= Notification.DEFAULT_SOUND;
            myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
            myNotification.setLatestEventInfo(context,
                "Boot!!" + new { myPid },
                    "Proud to be a jsc developer :)",
               pendingIntent);
            notificationManager.notify(1, myNotification);
            #endregion



            return base.onStartCommand(value0, value1, value2);
        }
 public void enableForegroundDispatch(Activity activity, PendingIntent intent,
     IntentFilter[] filters, string[][] techLists)
 { }
        // "x:\util\android-sdk-windows\platform-tools\adb.exe" connect 192.168.1.126:5555

        //  x:\util\android-sdk-windows\platform-tools\adb.exe logcat -s "xNativeActivity" "System.Console" "DEBUG"

        // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201505/20150513
        // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201505/20150531

        // 01. lets have our service think of a port, and send it back to activity at start. or save into file as cpu does it?
        // http://developer.android.com/reference/android/os/MemoryFile.html
        // http://stackoverflow.com/questions/19778196/class-memoryfile-of-any-use
        // http://stackoverflow.com/questions/15123402/share-memory-between-two-processes-in-dalvik
        // http://www.slideshare.net/tetsu.koba/interprocess-communication-of-android
        // http://www.codota.com/android/scenarios/52fcbca7da0a12229fc989b1/android.os.MemoryFile?tag=dragonfly
        // https://groups.google.com/forum/#!topic/android-developers/r-oqeI7MlJg
        // http://stackoverflow.com/questions/19778196/class-memoryfile-of-any-use
        // https://vec.io/posts/andriod-ipc-shared-memory-with-ashmem-memoryfile-and-binder
        // http://notjustburritos.tumblr.com/post/21442138796/an-introduction-to-android-shared-memory
        // https://developer.android.com/training/articles/memory.html
        // http://www.slideshare.net/jserv/android-ipc-mechanism

        //Action AtActivityResult;

        //protected override void onActivityResult(int arg0, int arg1, Intent arg2)
        //{
        //    base.onActivityResult(arg0, arg1, arg2);

        //    if (AtActivityResult != null)
        //        AtActivityResult();
        //}




        //        I/ActivityManager(  475): Killing 7649:AndroidMultiProcTCPServerAsync.Activities/u0a49 (adj 9): remove task
        //I/ActivityManager(  475): Killing 7627:AndroidMultiProcTCPServerAsync.Activities:gateway7/u0a49 (adj 5): remove task
        //I/ActivityManager(  475): START u0 {act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10200000 cmp=com.android.l
        //W/ActivityManager(  475): Scheduling restart of crashed service AndroidMultiProcTCPServerAsync.Activities/.GatewayService in 16000ms

        //protected override void onPause()
        //{
        //    Console.WriteLine("enter onPause, finishAndRemoveTask");


        //    // not called on back button?
        //    // keep service running, remove activity
        //    this.finishAndRemoveTask();

        //    base.onPause();



        //}

        protected override void onCreate(Bundle savedInstanceState)
        {
            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);
            // fill the button
            ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);


            this.setContentView(sv);

            var activity = this;


            new Button(activity).WithText("is the service already running?").AttachTo(ll);

            var m = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
            // why limit?
            var s = m.getRunningServices(0xffff);

            var a = Enumerable.FirstOrDefault(
                from i in Enumerable.Range(0, s.size())
                let rsi = (android.app.ActivityManager.RunningServiceInfo)s.get(i)
                let cn = rsi.service.getClassName()
                where cn == typeof(GatewayService).FullName
                select new { i, rsi, cn }
            );

            if (a == null)
            {
                new Button(activity).WithText("start service").AttachTo(ll).AtClick(
                    delegate
                    {
                        // start the service unless already running?
                        var intent = new Intent(this.getApplicationContext(), typeof(GatewayService).ToClass());
                        // if the user can swipe us away service is restarted?
                        this.getApplicationContext().startService(intent);

                    }
                );
            }
            else
            {

            }


            // whats the port?

            new Button(activity).WithText("which port are we on? " + new { a }).AttachTo(ll).AtClick(
                delegate
                {
                    var aa = default(AsyncReplyReceiver);

                    aa = new AsyncReplyReceiver
                    {
                        AtReceive = (cc, ii) =>
                        {
                            Console.WriteLine("ui now has the port...");
                            this.unregisterReceiver(aa);


                            var host = ii.getStringExtra("host");
                            var port = ii.getIntExtra("port", 0);

                            new Button(activity).WithText("open " + host + ":" + port).AttachTo(ll).AtClick(
                                 delegate
                                 {

                                     var href =
                                         "http://" + host + ":" + port;

                                     Console.WriteLine(
                                         href
                                     );



                                     //this.runOnUiThread(
                                     //    delegate
                                     //    {
                                     var i = new Intent(Intent.ACTION_VIEW,
                                        android.net.Uri.parse(href)
                                    );

                                     // http://vaibhavsarode.wordpress.com/2012/05/14/creating-our-own-activity-launcher-chooser-dialog-android-launcher-selection-dialog/
                                     var ic = Intent.createChooser(i, href);


                                     this.startActivity(ic);
                                     //    }
                                     //);
                                 }
                            );
                        }
                    };

                    var intentFilter = new IntentFilter();
                    intentFilter.addAction(GatewayService.ACTION + "reply");
                    this.registerReceiver(aa, intentFilter);


                    var intent = new Intent();
                    intent.setAction(GatewayService.ACTION);
                    intent.putExtra("whats my port", "?");
                    this.sendBroadcast(intent);
                }
            );



            new Button(this).WithText("exit").AttachTo(ll).AtClick(
             delegate
             {

                 // will it be logged?
                 System.Environment.Exit(13);

                 // application still visible in tasks?
             }
         );

            new Button(this).WithText("finish").AttachTo(ll).AtClick(
               delegate
               {
                   //this.finishAndRemoveTask();
                   this.finish();

                   // will it be logged?
                   //System.Environment.Exit(13);

                   // application still visible in tasks?
               }
           );

            new Button(this).WithText("finishAndRemoveTask").AttachTo(ll).AtClick(
             delegate
             {
                 this.finishAndRemoveTask();
                 //this.finish();

                 // will it be logged?
                 //System.Environment.Exit(13);

                 // application still visible in tasks?
             }
         );


            //            [javac] W:\src\AndroidMultiProcTCPServerAsync\Activities\ApplicationActivity.java:56: error: unreported exception IOException; must be caught or declared to be thrown
            //[javac]         class22.m = new MemoryFile("foo0", 100);

            //// ipc memory referenced
            //var m = default(MemoryFile);

            //try
            //{
            //    m = new MemoryFile("foo0", 100);
            //}
            //catch { throw; }


            // MemoryFile not available yet. bypass to NDK? workaround to filesystem?

            // E/AndroidRuntime(28716): Caused by: android.system.ErrnoException: open failed: EROFS (Read-only file system)

            // http://developer.android.com/training/basics/data-storage/files.html

            //  File.WriteAllText(this.getFilesDir().getAbsolutePath() + "/MemoryFile-foo0", "awaiting...");



            //  new Button(activity).WithText("Next " +

            //      File.ReadAllText(this.getFilesDir().getAbsolutePath() + "/MemoryFile-foo0")

            //      ).AttachTo(ll).AtClick(
            //      button =>
            //      {
            //          Intent intent = new Intent(activity, typeof(SecondaryActivity).ToClass());
            //          intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

            //          // share scope
            //          var myPid = android.os.Process.myPid();
            //          intent.putExtra("_item", "hello from " + new { myPid });

            //          //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

            //          //new Button(activity).WithText("read").AttachTo(ll).AtClick(
            //          //      button2 =>
            //          //      {
            //          //          var m2 = default(MemoryFile);

            //          //          try
            //          //          {
            //          //              m2 = new MemoryFile("foo0", 100);
            //          //          }
            //          //          catch { throw; }


            //          //          var pos = 0;

            //          //          //var __out = new __NetworkStream { InternalOutputStream = m.getOutputStream() };
            //          //          var __in = new __NetworkStream { InternalInputStream = m2.getInputStream() };

            //          //          // block the ui?

            //          //          var ipcByte = 0;
            //          //          while (ipcByte == 0)
            //          //          {
            //          //              ipcByte = __in.ReadByte();
            //          //              button2.WithText(new { ipcByte, pos }.ToString());
            //          //              pos++;
            //          //          }
            //          //      }
            //          //  );

            //          AtActivityResult +=
            //              delegate
            //              {
            //                  // if we read too early we get all zeros..

            //                  //var pos = 0;

            //                  ////var __out = new __NetworkStream { InternalOutputStream = m.getOutputStream() };
            //                  //var __in = new __NetworkStream { InternalInputStream = m.getInputStream() };

            //                  //// block the ui?

            //                  //var ipcByte = 0;
            //                  //while (ipcByte == 0)
            //                  //{
            //                  //    ipcByte = __in.ReadByte();
            //                  //    button.WithText(new { ipcByte, pos }.ToString());
            //                  //    pos++;
            //                  //}

            //                  button.WithText(
            //                   File.ReadAllText(this.getFilesDir().getAbsolutePath() + "/MemoryFile-foo0")
            //                 );

            //              };

            //          // cached backgroun process?
            //          // switching to another process.. easy...
            //          //activity.startActivity(intent);
            //          activity.startActivityForResult(intent, requestCode: 0x14);

            //      }
            //);

            //  //var s = new SemaphoreSlim(0);

            //  ////java.lang.Object, rt
            //  ////enter async { ManagedThreadId = 1 }
            //  ////awaiting for SemaphoreSlim{ ManagedThreadId = 1 }
            //  ////after delay{ ManagedThreadId = 8 }
            //  ////http://127.0.0.1:8080
            //  ////{ fileName = http://127.0.0.1:8080 }
            //  ////enter catch { mname = <0032> nop.try } ClauseCatchLocal:
            //  ////{ Message = , StackTrace = java.lang.RuntimeException
            //  ////        at ScriptCoreLibJava.BCLImplementation.System.Net.Sockets.__TcpListener.AcceptTcpClientAsync(__TcpListener.java:131)

            //  //new { }.With(
            //  //    async delegate
            //  //    {
            //  //        //System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
            //  //        //enter async { ManagedThreadId = 1 }
            //  //        //awaiting for SemaphoreSlim{ ManagedThreadId = 1 }
            //  //        //after delay{ ManagedThreadId = 4 }
            //  //        //http://127.0.0.1:8080
            //  //        //awaiting for SemaphoreSlim. done.{ ManagedThreadId = 1 }
            //  //        //--
            //  //        //accept { c = System.Net.Sockets.TcpClient, ManagedThreadId = 6 }
            //  //        //System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
            //  //        //accept { c = System.Net.Sockets.TcpClient, ManagedThreadId = 8 }
            //  //        //{ ManagedThreadId = 6, input = GET / HTTP/1.1





            //  //        // jump back to main thread..
            //  //        s.Release();
            //  //    }
            //  //);
        }
        // gateway service process/ event thread / async enabled?
        public override int onStartCommand(Intent value0, int flags, int startId)
        {
            // Options that have been set in the service declaration in the manifest.
            // http://developer.android.com/reference/android/content/pm/ServiceInfo.html#FLAG_STOP_WITH_TASK

            Console.WriteLine("enter onStartCommand " + new { flags, startId });



            // until wifi changes?
            var xipv4 =
                //from n in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()
                from n in AllNetworkInterfaces
                let IPProperties = n.GetIPProperties()
                let c = IPProperties.UnicastAddresses.Count
                from i in Enumerable.Range(0, c)
                let ip = IPProperties.UnicastAddresses[i]


                where ip.Address.AddressFamily == AddressFamily.InterNetwork
                //let loop = IPAddress.Loopback == ip.Address
                let loop = IPAddress.IsLoopback(ip.Address)

                orderby loop
                select new { n, ip, loop, ip.Address };

            //I/System.Console(20546): 5042:0001 { n = ScriptCoreLibJava.BCLImplementation.System.Net.NetworkInformation.__NetworkInterface@37e1894a, ip = { Address = 192.168.1.126 }, loop = false, Address = 192.168.1.126 }
            //I/System.Console(20546): 5042:0001 { n = ScriptCoreLibJava.BCLImplementation.System.Net.NetworkInformation.__NetworkInterface@3c1830bb, ip = { Address = 127.0.0.1 }, loop = true, Address = 127.0.0.1 }

            xipv4.WithEach(
                Console.WriteLine
            );

            var BestGuessHost = xipv4.FirstOrDefault();
            Console.WriteLine(" " + new { BestGuessHost });


            //var port = new Random().Next(8000, 30000);

            // cached by cloudflare?
            //var port = 80;
            var port = 8080;
            // https://github.com/NanoHttpd/nanohttpd/blob/master/core/src/main/java/fi/iki/elonen/NanoHTTPD.java

            var notifyServiceReceiver = new AsyncReplyReceiver
            {
                AtReceive = (cc, ii) =>
                {
                    Console.WriteLine("enter onReceive");

                    //android.content.IntentFilter
                    //android.content.Intent.ACTION_BOOT_COMPLETED
                    int rqs = ii.getIntExtra("RQS", 0);

                    if (rqs == RQS_STOP_SERVICE)
                        this.stopSelf();

                    if (ii.hasExtra("whats my port"))
                    {
                        // how do we reply?
                        // sharedmemory implementation is missing and useless

                        xipv4.WithEach(
                            Console.WriteLine
                        );

                        var intent = new Intent();
                        //intent.putExtra("host", BestGuessHost.Address.ToString());

                        // did we switch networks?
                        intent.putExtra("host", xipv4.FirstOrDefault().ToString());
                        intent.putExtra("port", port);
                        intent.setAction(GatewayService.ACTION + "reply");
                        this.sendBroadcast(intent);
                    }
                }
            };



            #region AtDestroy
            this.AtDestroy = delegate
            {
                Console.WriteLine("enter AtDestroy");

                this.unregisterReceiver(notifyServiceReceiver);
                //            I/System.Console( 8080): onDestroy { xmyPid = 8080 }
                //I/art     ( 8080): System.exit called, status: 42

                var xmyPid = android.os.Process.myPid();
                Console.WriteLine("onDestroy " + new { xmyPid });

                System.Environment.Exit(42);
            };
            #endregion


            //I/System.Console( 9390): 24ae:0001 { OperationalStatus = 2, Name = ip6tnl0, Description = ip6tnl0, SupportsMulticast = false, InetAddressesString =  }
            //I/System.Console( 9390): 24ae:0001 { OperationalStatus = 2, Name = rmnet4, Description = rmnet4, SupportsMulticast = true, InetAddressesString =  }
            //I/System.Console( 9390): 24ae:0001 { OperationalStatus = 2, Name = rmnet2, Description = rmnet2, SupportsMulticast = true, InetAddressesString =  }
            //I/System.Console( 9390): 24ae:0001 { OperationalStatus = 2, Name = rmnet3, Description = rmnet3, SupportsMulticast = true, InetAddressesString =  }
            //I/System.Console( 9390): 24ae:0001 { OperationalStatus = 2, Name = rmnet7, Description = rmnet7, SupportsMulticast = true, InetAddressesString =  }
            //I/System.Console( 9390): 24ae:0001 { OperationalStatus = 2, Name = rmnet5, Description = rmnet5, SupportsMulticast = true, InetAddressesString =  }
            //I/System.Console( 9390): 24ae:0001 { OperationalStatus = 2, Name = rmnet6, Description = rmnet6, SupportsMulticast = true, InetAddressesString =  }
            //I/System.Console( 9390): 24ae:0001 { OperationalStatus = 2, Name = rmnet1, Description = rmnet1, SupportsMulticast = true, InetAddressesString =  }
            //I/System.Console( 9390): 24ae:0001 { OperationalStatus = 2, Name = rmnet0, Description = rmnet0, SupportsMulticast = true, InetAddressesString =  }

            //I/System.Console( 9390): 24ae:0001 { OperationalStatus = 1, Name = lo, Description = lo, SupportsMulticast = false, InetAddressesString = , ::1%1, 127.0.0.1 }
            //I/System.Console( 9390): 24ae:0001 { OperationalStatus = 2, Name = sit0, Description = sit0, SupportsMulticast = false, InetAddressesString =  }
            //I/System.Console( 9390): 24ae:0001 { OperationalStatus = 1, Name = p2p0, Description = p2p0, SupportsMulticast = true, InetAddressesString = , fe80::e850:8bff:fe7d:277c%p2p0 }
            //I/System.Console( 9390): 24ae:0001 { OperationalStatus = 1, Name = wlan0, Description = wlan0, SupportsMulticast = true, InetAddressesString = , 2001:7d0:8414:3001:ea50:8bff:fe7d:277c%13, fe80::ea50:8bff:fe7d:277c%wlan0, 2001:7d0:8414:3001:b421:4790:ede8:826c%13, 192.168.1.126 }



            //I/System.Console(15259): 3b9b:0001 { OperationalStatus = 1, Name = lo, Description = lo, SupportsMulticast = false, InetAddressesString = , ::1%1, 127.0.0.1 }
            //I/System.Console(15259): 3b9b:0001 { OperationalStatus = 2, Name = dummy0, Description = dummy0, SupportsMulticast = false, InetAddressesString =  }
            //I/System.Console(15259): 3b9b:0001 { OperationalStatus = 2, Name = sit0, Description = sit0, SupportsMulticast = false, InetAddressesString =  }
            //I/System.Console(15259): 3b9b:0001 { OperationalStatus = 2, Name = ip6tnl0, Description = ip6tnl0, SupportsMulticast = false, InetAddressesString =  }
            //I/System.Console(15259): 3b9b:0001 { OperationalStatus = 1, Name = p2p0, Description = p2p0, SupportsMulticast = true, InetAddressesString = , fe80::10bf:48ff:febe:6b7d%p2p0 }
            //I/System.Console(15259): 3b9b:0001 { OperationalStatus = 1, Name = wlan0, Description = wlan0, SupportsMulticast = true, InetAddressesString = , 2001:7d0:8414:3001:a06f:6dfe:8dfc:42b8%6, 2001:7d0:8414:3001:12bf:48ff:febe:6b7d%6, fe80::12bf:48ff:febe:6b7d%wlan0, 192.168.1.211 }

            // I/System.Console(11408): 2c90:0001 { OperationalStatus = 1, Name = rmnet0, Description = rmnet0, SupportsMulticast = true, InetAddressesString = , 83.187.193.24 }

            //Implementation not found for type import :
            //type: System.Net.NetworkInformation.UnicastIPAddressInformationCollection
            //method: System.Net.NetworkInformation.UnicastIPAddressInformation get_Item(Int32)
            //Did you forget to add the [Script] attribute?
            //Please double check the signature!







            // http://stackoverflow.com/questions/14182014/android-oncreate-or-onstartcommand-for-starting-service



            var myPid = android.os.Process.myPid();

            var intentFilter = new IntentFilter();
            intentFilter.addAction(ACTION);
            registerReceiver(notifyServiceReceiver, intentFilter);


            Func<TcpListener> ctor = delegate
            {
                TcpListener x = null;
                try
                {
                    Console.WriteLine("774 TcpListener " + new { port });
                    x = new TcpListener(IPAddress.Any, port);
                    Console.WriteLine("776 TcpListener ");

                    // signal UI service is yet again available
                    //Console.WriteLine("before Start ");

                    // I/System.Console(25817): 64d9:0001 { err = java.lang.RuntimeException: bind failed: EACCES (Permission denied) }

                    x.Start();

                    Console.WriteLine("782 TcpListener ");

                }
                catch (Exception err)
                {
                    Console.WriteLine(new { err });
                    System.Environment.Exit(42);
                }

                return x;
            };



            #region TcpListener
            new { }.With(
                async delegate
                {

                    //var l = new TcpListener(IPAddress.Any, port);
                    var l = ctor();

            


                    var href =
                        "http://127.0.0.1:" + port;

                    Console.WriteLine(
                        href
                    );

                    while (true)
                    {
                        //Console.WriteLine("before AcceptTcpClientAsync ");

                        var c = await l.AcceptTcpClientAsync();

                        // time to do firewall or security?

                        //Console.WriteLine("before yield " + new { c });

                        yield(c);
                        //Console.WriteLine("after yield " + new { c });
                    }
                }
            );
            #endregion


            var onStartCommand_status = base.onStartCommand(value0, flags, startId);

            Console.WriteLine("exit onStartCommand " + new { onStartCommand_status });

            // I/System.Console( 9005): 232d:0001 exit onStartCommand { onStartCommand_status = 1 }

            return onStartCommand_status;
        }
        public override int onStartCommand(Intent value0, int value1, int value2)
        {
            #region Notify
            int counter = 0;
            Action<string, string, string> Notify =
                (Title, link, search) =>
                {
                    counter++;

                    var nm = (NotificationManager)this.getSystemService(Activity.NOTIFICATION_SERVICE);


                    //var nn = new NotificationCompat
                    // see http://developer.android.com/reference/android/app/Notification.html
                    var notification = new Notification(
                        android.R.drawable.star_on,
                        Title,
                         java.lang.System.currentTimeMillis()
                    );

                    // ToClass is like GetTypeInfo
                    //var xmyIntent = new Intent(Intent.ACTION_VIEW, android.net.Uri.parse("http://youtube.com"));

                    //http://stackoverflow.com/questions/9860456/search-a-specific-string-in-youtube-application-from-my-app

                    // http://grokbase.com/t/gg/android-developers/123s02429a/use-marquee-on-notification-bar

                    Intent xmyIntent = new Intent(Intent.ACTION_SEARCH);
                    xmyIntent.setPackage("com.google.android.youtube");
                    xmyIntent.putExtra("query", search);

                    // https://code.google.com/p/android/issues/detail?id=82065
                    // http://stackoverflow.com/questions/11939018/scrolling-text-in-notification
                    xmyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    //startActivity(intent);

                    //var xmyIntent = new Intent(Intent.ACTION_VIEW, android.net.Uri.parse(link));


 //[javac] W:\src\JVMCLRBroadcastLogger\__AndroidMulticast.java:165: error: bad operand type __Func_2< __f__AnonymousType_109_1_2<__NetworkInterface, Boolean>,__IEnumerable_1 < __UnicastIPAddressInformation >> for unary operator '!'
 //     [javac]             if (!__AndroidMulticast.CS___9__CachedAnonymousMethodDelegate10)
 //[javac] ^

                    var xpendingIntent
                      = PendingIntent.getActivity(
                          getBaseContext(),
                        0,
                        xmyIntent,
                        Intent.FLAG_ACTIVITY_NEW_TASK);


                    notification.setLatestEventInfo(
                        this,
                        Title,
                       Title,
                        xpendingIntent);

                    
                    // http://stackoverflow.com/questions/10402686/how-to-have-led-light-notification
                    //notification.defaults |= Notification.DEFAULT_VIBRATE;
                    //notification.defaults |= Notification.DEFAULT_SOUND;
                    //notification.defaults |= Notification.DEFAULT_LIGHTS;
                    //notification.defaults |= Notification.FLAG_SHOW_LIGHTS;


                    //new Notification.BigTextStyle(
                    
                    // http://androiddrawableexplorer.appspot.com/
                    nm.notify(counter, notification);

                    //context.ToNotification(
                    //      Title: Title,
                    //      Content: Title,

                    //      id: (int)java.lang.System.currentTimeMillis(),
                    //        icon: android.R.drawable.star_on,
                    //      uri: "http://my.jsc-solutions.net"
                    //  );
                };
            #endregion

            var intentFilter = new IntentFilter();
            intentFilter.addAction(ACTION);
            registerReceiver(notifyServiceReceiver, intentFilter);

            //            0001 02000006 AndroidServiceUDPNotification.AndroidActivity::< module >.SHA1c9cbee88a1edabb97eb411ca262280fe2fa18dd1@229018826
            //{ OwnerMethod = Int32 onStartCommand(android.content.Intent, Int32, Int32), DeclaringType = AndroidServiceUDPNotification.Activities.NotifyService }
            //            {
            //                exc = System.Security.VerificationException: Operation could destabilize the runtime.
            //                 at System.RuntimeMethodHandle.GetMethodBody(IRuntimeMethodInfo method, RuntimeType declaringType)
            //               at System.Reflection.RuntimeMethodInfo.GetMethodBody()
            //               at jsc.ILBlock..ctor(MethodBase SourceMethod) in x:\jsc.internal.git\compiler\jsc\CodeModel\ILBlock.cs:line 349

            Notify("awaiting for tv...", "http://youtube.com", "music");

            // http://developer.android.com/reference/android/net/wifi/WifiManager.html
            // http://developer.android.com/reference/android/net/wifi/WifiManager.html#createMulticastLock(java.lang.String)
            ((WifiManager)this.getSystemService(Context.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "ApplicationActivity").acquire();
            ((WifiManager)this.getSystemService(Context.WIFI_SERVICE)).createMulticastLock("ApplicationActivity").acquire();

            new JVMCLRBroadcastLogger.__AndroidMulticast(
                AtData:
                xmlstring =>
                {
                    // X:\jsc.svn\examples\javascript\chrome\apps\ChromeUDPNotification\ChromeUDPNotification\Application.cs

                    var xml = XElement.Parse(xmlstring);

                    if (xml.Value.StartsWith("Visit me at "))
                    {
                        // what about android apps runnning on SSL?
                        // what about preview images?
                        // do we get localhost events too?

                        var n = xml.Attribute("n");

                        var uri = "http://" + xml.Value.SkipUntilOrEmpty("Visit me at ");
                        var link = uri + "/results?search_query=" + n.Value;

                        Notify(n.Value, link, n.Value);
                    }
                }
            );



            return base.onStartCommand(value0, value1, value2);
        }
 // X:\jsc.svn\examples\javascript\android\com.abstractatech.battery\com.abstractatech.battery\ApplicationWebService.cs
 public abstract Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter);
Exemple #14
0
 public override Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter)
 {
     throw new NotImplementedException();
 }
        // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201402/20140223-nfc
        // http://blog.atlasrfidstore.com/rfid-vs-nfc

        static ApplicationWebService()
        {
            // http://lifehacker.com/run-an-action-when-you-remove-your-phone-from-an-nfc-ta-1208446359
            // https://groups.google.com/forum/#!topic/android-developers/8-17f6ZLYJY

            //  android:launchMode="singleTop"
            // http://www.intridea.com/blog/2011/6/16/android-understanding-activity-launchmode
            Console.WriteLine("enter ApplicationWebService " + new { Thread.CurrentThread.ManagedThreadId });

            // http://mobile.tutsplus.com/tutorials/android/reading-nfc-tags-with-android/
            // http://stackoverflow.com/questions/10848134/android-on-nfc-read-close-activity-not-the-main-activity
            // http://stackoverflow.com/questions/17989055/nfc-not-able-to-detect-a-tag
            // http://stackoverflow.com/questions/5685946/nfc-broadcastreceiver-problem

            var activity = ScriptCoreLib.Android.ThreadLocalContextReference.CurrentContext as ScriptCoreLib.Android.CoreAndroidWebServiceActivity;
            var adapter = android.nfc.NfcAdapter.getDefaultAdapter(activity);
            var isEnabled = adapter.isEnabled();

            Console.WriteLine(new { isEnabled });

            var intent = new Intent(
                activity,
                activity.GetType().ToClass()
                );

            // /ActivityManager(  510): startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { act=android.nfc.action.TECH_DISCOVERED cmp=AndroidNFCIsoDepTest.Activities/.ApplicationWebServiceActivity (has extras) }
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            //intent.addFlags(Intent.flag);
            //intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);

            // http://comments.gmane.org/gmane.comp.handhelds.android.devel/165860

            // https://code.google.com/p/android/issues/detail?id=4155
            //            Well onNewIntent will only be called when the activity has "singleTop" property and
            //exists in the activity stack(not destroyed)
            //intent.addFlags(Intent.fl);
            //com.p2.A2 is an Activity with launchMode="singleTop".


            //But without Intent.FLAG_ACTIVITY_SINGLE_TOP being set,
            //A2.onNewIntent() will not be invoked.
            // http://comments.gmane.org/gmane.comp.handhelds.android.devel/165860
            var pendingIntent = PendingIntent.getActivity(
                activity,
                0,
                intent,
                0
            );

            //var techList = new[]
            //{ 
            //    //  [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.Ndef]
            //    //  dispatch tag: TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.NdefFormatable] message: null
            //    new [] { typeof(android.nfc.tech.MifareClassic).FullName },
            //    new [] {     typeof(android.nfc.tech.NfcA).FullName},
            //    new [] {     typeof(android.nfc.tech.Ndef).FullName},
            //    new [] {     typeof(android.nfc.tech.NdefFormatable).FullName },

            //    // current javacards? (ISO 14443-4)
            //    new [] {     typeof(android.nfc.tech.IsoDep).FullName },


            //};

            // http://124.16.139.131:24080/lxr/source/packages/apps/Nfc/src/com/android/nfc/NfcDispatcher.java?v=android-4.0.4


            //String[][] techList = new String[][] { new String[] { NfcA.class.getName(),
            //NfcB.class.getName(), NfcF.class.getName(),
            //NfcV.class.getName(), IsoDep.class.getName(),
            //MifareClassic.class.getName(),
            //MifareUltralight.class.getName(), Ndef.class.getName() } };



            // Notice that this is the same filter as in our manifest.
            var filters = new IntentFilter[1];

            filters[0] = new IntentFilter();

            // https://code.google.com/p/android/issues/detail?id=37673
            // http://www.xda-developers.com/android/activate-actions-upon-removal-of-nfc-tags/
            //filters[0].addAction(NfcAdapter.ACTION_TAG_LOST);

            // https://android.googlesource.com/platform/frameworks/base.git/+/android-4.2.2_r1/core/java/android/nfc/NfcAdapter.java
            filters[0].addAction("android.nfc.action.TAG_LOST");

            filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
            filters[0].addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
            filters[0].addAction(NfcAdapter.ACTION_TECH_DISCOVERED);


            filters[0].addCategory(Intent.CATEGORY_DEFAULT);

            //V:\src\AndroidNFCIsoDepTest\ApplicationWebService.java:57: unreported exception android.content.IntentFilter.MalformedMimeTypeException; must be caught or declared to be thrown
            try
            {
                filters[0].addDataType("*/*");
            }
            catch
            {
                throw;
            }

            //            D/NfcDispatcher(  747): Set Foreground Dispatch
            //D/dalvikvm(20170): GC_CONCURRENT freed 488K, 8% free 7978K/8584K, paused 4ms+2ms, total 27ms
            //D/dalvikvm(  581): GC_CONCURRENT freed 4091K, 44% free 12001K/21124K, paused 3ms+5ms, total 32ms
            //D/NfcDispatcher(  747): dispatch tag: TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.Ndef] message: NdefMessage [NdefRecord tnf=4 type=70696C65742E65653A656B616172743A32 payload=66195F26063133303130385904202020205F28033233335F2701316E1B5A13333038363439303039303030333032313336315304FDCCD727, NdefRecord tnf=1 type=536967 payload=01020080B489DEDA8C2271386B7962250063A7C7C8612C3D58C8CD44D674F9D1615E80C72D961F8AC822C3188D48EFC7DA9DA3FF5C306E1EF54E0610F66D1C891CC59428A27CAA4211D4040527CF9BCD16F20E0B3116966AFC2390B7EF30CCC877B8532281CA3CBE286D295AECEA4447FD62874872A46099D6CEED99ED6766B829FD3FDF800025687474703A2F2F70696C65742E65652F6372742F33303836343930302D303030312E637274]
            //D/dalvikvm(  747): GC_CONCURRENT freed 491K, 10% free 8255K/9160K, paused 3ms+1ms, total 33ms
            //D/dalvikvm(  747): WAIT_FOR_CONCURRENT_GC blocked 8ms
            //D/NfcHandover(  747): tryHandover(): NdefMessage [NdefRecord tnf=4 type=70696C65742E65653A656B616172743A32 payload=66195F26063133303130385904202020205F28033233335F2701316E1B5A13333038363439303039303030333032313336315304FDCCD727, NdefRecord tnf=1 type=536967 payload=01020080B489DEDA8C2271386B7962250063A7C7C8612C3D58C8CD44D674F9D1615E80C72D961F8AC822C3188D48EFC7DA9DA3FF5C306E1EF54E0610F66D1C891CC59428A27CAA4211D4040527CF9BCD16F20E0B3116966AFC2390B7EF30CCC877B8532281CA3CBE286D295AECEA4447FD62874872A46099D6CEED99ED6766B829FD3FDF800025687474703A2F2F70696C65742E65652F6372742F33303836343930302D303030312E637274]
            //I/ActivityManager(  440): START u0 {flg=0x10008000 cmp=com.android.nfc/.NfcRootActivity (has extras)} from pid 747
            //D/NfcDispatcher(  747): Set Foreground Dispatch
            //I/NfcDispatcher(  747): matched single TECH
            //I/ActivityManager(  440): START u0 {act=android.nfc.action.TECH_DISCOVERED cmp=com.google.android.tag/com.android.apps.tag.TagViewer (has extras)} from pid 747
            //I/ActivityManager(  440): Displayed com.google.android.tag/com.android.apps.tag.TagViewer: +100ms (total +114ms)
            //W/IInputConnectionWrapper(20170): showStatusIcon on inactive InputConnection
            //I/CalendarProvider2(17732): Sending notification intent: Intent { act=android.intent.action.PROVIDER_CHANGED dat=content://com.android.calendar }
            //W/ContentResolver(17732): Failed to get type for: content://com.android.calendar (Unknown URL content://com.android.calendar)


            activity.AtNewIntent +=
                i =>
                {
                    var action = i.getAction();





                    Console.WriteLine("AndroidNFCIsoDepTest AtNewIntent " + new { action });

                    //I/System.Console(25300): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED }

                    #region android.nfc.action.TECH_DISCOVERED
                    if (action == "android.nfc.action.TECH_DISCOVERED")
                    {
                        //                    U:\src\AndroidNFCIsoDepTest\ApplicationWebService___c__DisplayClass4.java:93: <identifier> expected
                        //private static Tag _<.cctor>b__0_Isinst_0064(Object _0064)
                        //                     ^

                        //                        I/System.Console(26970): AtPause
                        //D/NfcDispatcher(  747): Set Foreground Dispatch
                        //I/System.Console(26970): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED }
                        //I/System.Console(26970): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, tag =  }
                        //D/AndroidRuntime(26970): Shutting down VM
                        //W/dalvikvm(26970): threadid=1: thread exiting with uncaught exception (group=0x419dc700)
                        //I/ActivityManager(  440): START u0 {act=android.nfc.action.TECH_DISCOVERED flg=0x20000000 cmp=AndroidNFCIsoDepTest.Activities/.ApplicationWebServiceActivity (has extras)} from pid -1
                        //W/ActivityManager(  440): startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { act=android.nfc.action.TECH_DISCOVERED flg=0x20000000 cmp=AndroidNFCIsoDepTest.Activities/.ApplicationWebServiceActivity (has extras) }

                        //var tag = (Tag)intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

                        //Console.WriteLine("AtNewIntent " + new { action, tag });

                        // D/NfcDispatcher(  747): dispatch tag: TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.Ndef] 
                        // message: NdefMessage 
                        // [NdefRecord tnf=4 type=70696C65742E65653A656B616172743A32 payload=66195F26063133303130385904202020205F28033233335F2701316E1B5A13333038363439303039303030333032313336315304FDCCD727, 
                        //  NdefRecord tnf=1 type=536967 payload=01020080B489DEDA8C2271386B7962250063A7C7C8612C3D58C8CD44D674F9D1615E80C72D961F8AC822C3188D48EFC7DA9DA3FF5C306E1EF54E0610F66D1C891CC59428A27CAA4211D4040527CF9BCD16F20E0B3116966AFC2390B7EF30CCC877B8532281CA3CBE286D295AECEA4447FD62874872A46099D6CEED99ED6766B829FD3FDF800025687474703A2F2F70696C65742E65652F6372742F33303836343930302D303030312E637274
                        // ]



                        //                        I/ActivityManager(  440): START u0 {act=android.nfc.action.TECH_DISCOVERED flg=0x20000000 cmp=AndroidNFCIsoDepTest.Activities/.ApplicationWebServiceActivity (has extras)} from pid -1
                        //W/ActivityManager(  440): startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { act=android.nfc.action.TECH_DISCOVERED flg=0x20000000 cmp=AndroidNFCIsoDepTest.Activities/.ApplicationWebServiceActivity (has extras) }
                        //I/System.Console(30978): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED }
                        //I/NfcDispatcher(  747): matched TECH override
                        //I/System.Console(30978): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG }
                        //I/System.Console(30978): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG, p = TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.NdefFormatable], FullName = android.nfc.Tag }
                        //I/System.Console(30978): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.ID }
                        //I/System.Console(30978): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.ID, p = [B@4212cfc8, FullName = [B }
                        //I/System.Console(30978): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.ID, p = [B@4212cfc8, FullName = [B, HexString = fc4969f9 }
                        //I/System.Console(30978): AtResume

                        // https://groups.google.com/forum/#!topic/android-developers/8-17f6ZLYJY
                        //http://stackoverflow.com/questions/9009043/android-nfc-intercept-all-tags
                        var extras = i.getExtras();
                        var ks = extras.keySet();
                        var iterator = ks.iterator();
                        while (iterator.hasNext())
                        {
                            var current = (string)iterator.next();

                            Console.WriteLine("AtNewIntent " + new { action, current });



                            // I/System.Console(29237): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG, p = TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.Ndef], FullName = android.nfc.Tag }
                            // http://stackoverflow.com/questions/5968896/listing-all-extras-of-an-intent
                            extras.get(current).With(
                                p =>
                                {
                                    Console.WriteLine("AtNewIntent " + new { action, current, p, p.GetType().FullName });

                                    (p as Tag).With(
                                       tag =>
                                       {
                                           var id = (byte[])(object)tag.getId();

                                           Console.WriteLine("AtNewIntent " + new { action, current, id = id.ToHexString(), Thread.CurrentThread.ManagedThreadId });

                                           //I/System.Console(32331): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG, p = TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.Ndef], id = fdccd727, tech = android.nfc.tech.MifareClassic }
                                           //I/System.Console(32331): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG, p = TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.Ndef], id = fdccd727, tech = android.nfc.tech.NfcA }
                                           //I/System.Console(32331): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG, p = TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.Ndef], id = fdccd727, tech = android.nfc.tech.Ndef }

                                           //I/System.Console(32331): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG, p = TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.NdefFormatable], id = fc4969f9, tech = android.nfc.tech.MifareClassic }
                                           //I/System.Console(32331): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG, p = TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.NdefFormatable], id = fc4969f9, tech = android.nfc.tech.NfcA }
                                           //I/System.Console(32331): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG, p = TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.NdefFormatable], id = fc4969f9, tech = android.nfc.tech.NdefFormatable }

                                           tag.getTechList().WithEach(
                                               tech =>
                                               {
                                                   Console.WriteLine("AtNewIntent " + new { action, current, id = id.ToHexString(), tech });

                                                   if (tech == typeof(android.nfc.tech.MifareClassic).FullName)
                                                   {
                                                       android.nfc.tech.MifareClassic.get(tag).With(
                                                           m =>
                                                           {


                                                           }
                                                       );
                                                   }


                                                   if (tech == typeof(android.nfc.tech.NfcA).FullName)
                                                   {
                                                       android.nfc.tech.NfcA.get(tag).With(
                                                           m =>
                                                           {

                                                           }
                                                       );
                                                   }

                                                   if (tech == typeof(android.nfc.tech.IsoDep).FullName)
                                                   {
                                                       android.nfc.tech.IsoDep.get(tag).With(
                                                           m =>
                                                           {
                                                               try
                                                               {
                                                                   Console.WriteLine("Isodep exists");

                                                                   //AID A0 A1 A2 A3 A4 00 03 01
                                                                   byte[] AID = {0x00, 0xA4, 0x04, 0x00, 0x08, //Applet selection APDU
                                                                                    0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0x00, 0x03, 0x01 }; //Applet AID
                                                                   var sByteArr = (sbyte[])(object)AID;
                                                                   m.connect();
                                                                   var res = m.transceive(sByteArr);
                                                                   //Console.WriteLine("Result " + Convert.ToBase64String((byte[])(object)res));

                                                                   var resString = ((byte[])(object)res).ToHexString();

                                                                   Console.WriteLine("Result = " + resString);

                                                                   //Console.WriteLine("Result[0] = " + res[0].ToString());
                                                                   //Console.WriteLine("Result[1] = " + res[1].ToString());
                                                                   Console.WriteLine("Result lenght = " + res.Length);

                                                                    //I/System.Console( 9340): Isodep exists
                                                                    //I/System.Console( 9340): Result [B@427ebd50
                                                                    //I/System.Console( 9340): Result = 9000
                                                                    //I/System.Console( 9340): Result lenght = 2
                                                                    //I/System.Console( 9340): Applet select failed

                                                                   if (resString == "9000")
                                                                   {
                                                                        //I/System.Console(10829): Isodep exists
                                                                        //I/System.Console(10829): Result = 9000
                                                                        //I/System.Console(10829): Result lenght = 2
                                                                        //I/System.Console(10829): Succsessful applet selection
                                                                        //I/System.Console(10829): Last name =6f00
                                                                        //I/System.Console(10829): Last name len =2
                                                                        //I/System.Console(10829): First name =6f00
                                                                        //I/System.Console(10829): First name len =2


                                                                       Console.WriteLine("Succsessful applet selection");

                                                                       byte[] lastName = { 0x00, 0xB2, 0x01, 0x04, 0x00 };
                                                                       byte[] firstName = { 0x00, 0xB2, 0x02, 0x04, 0x00 };

                                                                       var t1 = (sbyte[])(object)lastName;
                                                                       var t2 = (sbyte[])(object)firstName;
                                                                       var lastN = m.transceive(t1);
                                                                       Console.WriteLine("Last name =" + ((byte[])(object)lastN).ToHexString());
                                                                       Console.WriteLine("Last name len =" + lastN.Length);
                                                                       

                                                                       var firstN = m.transceive(t2);
                                                                       Console.WriteLine("First name =" + ((byte[])(object)firstN).ToHexString());
                                                                       Console.WriteLine("First name len =" + firstN.Length);

                                                                        //I/System.Console(11937): Isodep exists
                                                                        //I/System.Console(11937): Result = 9000
                                                                        //I/System.Console(11937): Result lenght = 2
                                                                        //I/System.Console(11937): Succsessful applet s
                                                                        //I/System.Console(11937): Last name =6b6969766
                                                                        //I/System.Console(11937): Last name len =8
                                                                        //I/System.Console(11937): First name =6a6f6e61
                                                                        //I/System.Console(11937): First name len =7
                                                                   }
                                                                   else
                                                                   {
                                                                       Console.WriteLine("Applet select failed");
                                                                   }
                                                               }
                                                               catch (Exception e)
                                                               {
                                                                   Console.WriteLine("Exception ="+e.Message);

                                                               }
                                                               
                                                           }
                                                       );
                                                   }

                                               }
                                           );

                                           //tag.
                                       }
                                    );

                                    (p as byte[]).With(
                                        bytes =>
                                        {
                                            var HexString = bytes.ToHexString();

                                            Console.WriteLine("AtNewIntent " + new { action, current, p, p.GetType().FullName, HexString });
                                        }
                                    );

                                    // https://android.googlesource.com/platform/packages/apps/Nfc/+/android-4.2.1_r1.2/nci/src/com/android/nfc/dhimpl/NativeNfcTag.java

                                    //(p as android.os.Parcelable[]).With(
                                    //     m =>
                                    //     {

                                    //         Console.WriteLine("AtNewIntent " + new { action, current, records = m.getRecords().Length });

                                    //         m.getRecords().WithEach(
                                    //             r =>
                                    //             {
                                    //                 Console.WriteLine("AtNewIntent " + new { action, current, id = ((byte[])(object)r.getId()).ToHexString() });

                                    //             }
                                    //         );
                                    //     }
                                    // );
                                }
                            );

                        }

                        //                        I/System.Console(29527): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED }
                        //I/System.Console(29527): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG }
                        //I/System.Console(29527): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG, p = TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.Ndef], FullName = android.nfc.Tag }
                        //I/System.Console(29527): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.ID }
                        //I/System.Console(29527): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.ID, p = [B@42156c88, FullName = [B }
                        //I/System.Console(29527): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.NDEF_MESSAGES }
                        //I/System.Console(29527): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.NDEF_MESSAGES, p = [Landroid.os.Parcelable;@42156e98, FullName = [Landroid.os.Parcelable; }
                        //I/System.Console(29527): AtResume





                        //                        I/System.Console(28867): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED }
                        //I/System.Console(28867): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG }
                        //I/System.Console(28867): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.ID }
                        //I/System.Console(28867): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.NDEF_MESSAGES }




                        //var id = tag.getId();

                        //Console.WriteLine("AtNewIntent " + new { action, tag, id.Length, id = ((byte[])(object)id).ToHexString() });

                        //tag.getTechList().WithEach(
                        //    tech =>
                        //    {
                        //        Console.WriteLine("AtNewIntent " + new { action, tech });
                        //    }
                        //);
                        //tag.get
                    }
                    #endregion
                };

            // who is using it?
            activity.AtResume +=
                delegate
                {

                    Console.WriteLine("AndroidNFCIsoDepTest AtResume");
                    adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
                };

            //     Caused by: java.lang.IllegalStateException: Foreground dispatch can only be enabled when your activity is resumed
            //at android.nfc.NfcAdapter.enableForegroundDispatch(NfcAdapter.java:1135)

            Console.WriteLine("before AndroidNFCIsoDepTest enableForegroundDispatch ?");
            //adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);


            activity.AtPause +=
               delegate
               {
                   Console.WriteLine("AndroidNFCIsoDepTest AtPause");
                   adapter.disableForegroundDispatch(activity);
               };
        }
        // inspired by http://baroqueworksdev.blogspot.com/2012/09/how-to-handle-screen-onoff-and-keygurad.html



        protected override void onCreate(global::android.os.Bundle savedInstanceState)
        {
            base.onCreate(savedInstanceState);

            var sv = new ScrollView(this);
            var ll = new LinearLayout(this);
            ll.setOrientation(LinearLayout.VERTICAL);
            sv.addView(ll);


            this.setContentView(sv);


            new Button(this).WithText("register").AttachTo(ll).AtClick(
                btn =>
                {
                    btn.setEnabled(false);

                    // get KeyGuardManager
                    var mKeyguard = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE);

                    var mReceiver = new MyBroadcastReceiver();

                    mReceiver.AtReceive +=
                        (Context context, Intent intent) =>
                        {
                            #region Notify
                            int counter = 0;
                            Action<string> Notify =
                                Title =>
                                {
                                    counter++;

                                    var nm = (NotificationManager)this.getSystemService(Activity.NOTIFICATION_SERVICE);

                                    // see http://developer.android.com/reference/android/app/Notification.html
                                    var notification = new Notification(
                                        android.R.drawable.star_on,
                                        Title,
                                         java.lang.System.currentTimeMillis()
                                    );

                                    // ToClass is like GetTypeInfo
                                    var notificationIntent = new Intent(this, typeof(AndroidUnlockActivity).ToClass());
                                    var contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);


                                    notification.setLatestEventInfo(
                                        this,
                                        Title,
                                        "",
                                        contentIntent);

                                    // http://stackoverflow.com/questions/10402686/how-to-have-led-light-notification
                                    notification.defaults |= Notification.DEFAULT_VIBRATE;
                                    notification.defaults |= Notification.DEFAULT_SOUND;
                                    //notification.defaults |= Notification.DEFAULT_LIGHTS;
                                    notification.defaults |= Notification.FLAG_SHOW_LIGHTS;
                                    // http://androiddrawableexplorer.appspot.com/
                                    nm.notify(counter, notification);

                                    //context.ToNotification(
                                    //      Title: Title,
                                    //      Content: Title,

                                    //      id: (int)java.lang.System.currentTimeMillis(),
                                    //        icon: android.R.drawable.star_on,
                                    //      uri: "http://my.jsc-solutions.net"
                                    //  );
                                };
                            #endregion

                            var action = intent.getAction();
                            if (action == Intent.ACTION_SCREEN_OFF)
                            {
                                // Screen is off
                                Notify("ACTION_SCREEN_OFF");
                            }
                            else if (action == Intent.ACTION_SCREEN_ON)
                            {
                                // Intent.ACTION_USER_PRESENT will be broadcast when the screen
                                // is
                                // unlocked.

                                // if API Level 16
                                /*
                                 * if(mKeyguard.isKeyguardLocked()){ // the keyguard is
                                 * currently locked. Log.e("","ACTION_SCREEN_ON : locked"); }
                                 */
                                if (mKeyguard.inKeyguardRestrictedInputMode())
                                {
                                    // the keyguard is currently locked.
                                    Notify("ACTION_SCREEN_ON : locked");
                                }
                                else
                                {
                                    // unlocked
                                    Notify("ACTION_SCREEN_ON : unlocked");
                                }

                            }
                            else if (action == Intent.ACTION_USER_PRESENT)
                            {
                                // The user has unlocked the screen. Enabled!
                                Notify("ACTION_USER_PRESENT");


                            }
                        };


                    // IntetFilter with Action
                    IntentFilter intentFilter = new IntentFilter();
                    intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
                    intentFilter.addAction(Intent.ACTION_SCREEN_ON);
                    intentFilter.addAction(Intent.ACTION_USER_PRESENT);// Keyguard is GONE

                    // register BroadcastReceiver and IntentFilter
                    registerReceiver(mReceiver, intentFilter);
                }
            );

            //this.ShowToast("http://jsc-solutions.net");
        }
        static ApplicationWebService_poll_onnfc()
        {
            // http://lifehacker.com/run-an-action-when-you-remove-your-phone-from-an-nfc-ta-1208446359
            // https://groups.google.com/forum/#!topic/android-developers/8-17f6ZLYJY

            //  enter ApplicationWebService { ManagedThreadId = 2029 }
            Console.WriteLine("enter ApplicationWebService_poll_onnfc " + new { Thread.CurrentThread.ManagedThreadId });

            // http://mobile.tutsplus.com/tutorials/android/reading-nfc-tags-with-android/
            // http://stackoverflow.com/questions/10848134/android-on-nfc-read-close-activity-not-the-main-activity
            // http://stackoverflow.com/questions/17989055/nfc-not-able-to-detect-a-tag
            // http://stackoverflow.com/questions/5685946/nfc-broadcastreceiver-problem

            var activity = ScriptCoreLib.Android.ThreadLocalContextReference.CurrentContext as ScriptCoreLib.Android.CoreAndroidWebServiceActivity;

            var adapter = android.nfc.NfcAdapter.getDefaultAdapter(
                activity
            );

            var isEnabled = adapter.isEnabled();

            Console.WriteLine(new { isEnabled });




            var intent = new Intent(
                activity,
                activity.GetType().ToClass()
                );

            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

            var pendingIntent = PendingIntent.getActivity(
                activity,
                0,
                intent,
                0
            );

            var filters = new IntentFilter[1];
            var techList = new[]
            { 
                //  [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.Ndef]
                //  dispatch tag: TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.NdefFormatable] message: null
                new [] { typeof(android.nfc.tech.MifareClassic).FullName },
                new [] { typeof(android.nfc.tech.NfcA).FullName},
                new [] { typeof(android.nfc.tech.Ndef).FullName},
                new [] { typeof(android.nfc.tech.NdefFormatable).FullName },

				// current javacards? (ISO 14443-4)
				new [] {     typeof(android.nfc.tech.IsoDep).FullName },
			};

            // http://124.16.139.131:24080/lxr/source/packages/apps/Nfc/src/com/android/nfc/NfcDispatcher.java?v=android-4.0.4


            //String[][] techList = new String[][] { new String[] { NfcA.class.getName(),
            //NfcB.class.getName(), NfcF.class.getName(),
            //NfcV.class.getName(), IsoDep.class.getName(),
            //MifareClassic.class.getName(),
            //MifareUltralight.class.getName(), Ndef.class.getName() } };



            // Notice that this is the same filter as in our manifest.
            filters[0] = new IntentFilter();

            // https://code.google.com/p/android/issues/detail?id=37673
            // http://www.xda-developers.com/android/activate-actions-upon-removal-of-nfc-tags/
            //filters[0].addAction(NfcAdapter.ACTION_TAG_LOST);

            // https://android.googlesource.com/platform/frameworks/base.git/+/android-4.2.2_r1/core/java/android/nfc/NfcAdapter.java
            filters[0].addAction("android.nfc.action.TAG_LOST");

            filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
            filters[0].addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
            filters[0].addAction(NfcAdapter.ACTION_TECH_DISCOVERED);


            filters[0].addCategory(Intent.CATEGORY_DEFAULT);

            //V:\src\AndroidNFCExperiment\ApplicationWebService.java:57: unreported exception android.content.IntentFilter.MalformedMimeTypeException; must be caught or declared to be thrown
            try
            {
                filters[0].addDataType("*/*");
            }
            catch
            {
                throw;
            }

            activity.AtNewIntent +=
                i =>
                {
                    var action = i.getAction();

                    Console.WriteLine("AtNewIntent " + new { action });

                    //I/System.Console(25300): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED }

                    if (action == NfcAdapter.ACTION_TECH_DISCOVERED)
                    {
                        //                    U:\src\AndroidNFCExperiment\ApplicationWebService___c__DisplayClass4.java:93: <identifier> expected
                        //private static Tag _<.cctor>b__0_Isinst_0064(Object _0064)
                        //                     ^

                        //                        I/System.Console(26970): AtPause
                        //D/NfcDispatcher(  747): Set Foreground Dispatch
                        //I/System.Console(26970): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED }
                        //I/System.Console(26970): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, tag =  }
                        //D/AndroidRuntime(26970): Shutting down VM
                        //W/dalvikvm(26970): threadid=1: thread exiting with uncaught exception (group=0x419dc700)
                        //I/ActivityManager(  440): START u0 {act=android.nfc.action.TECH_DISCOVERED flg=0x20000000 cmp=AndroidNFCExperiment.Activities/.ApplicationWebServiceActivity (has extras)} from pid -1
                        //W/ActivityManager(  440): startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { act=android.nfc.action.TECH_DISCOVERED flg=0x20000000 cmp=AndroidNFCExperiment.Activities/.ApplicationWebServiceActivity (has extras) }

                        //var tag = (Tag)intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

                        //Console.WriteLine("AtNewIntent " + new { action, tag });

                        // D/NfcDispatcher(  747): dispatch tag: TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.Ndef] 
                        // message: NdefMessage 
                        // [NdefRecord tnf=4 type=70696C65742E65653A656B616172743A32 payload=66195F26063133303130385904202020205F28033233335F2701316E1B5A13333038363439303039303030333032313336315304FDCCD727, 
                        //  NdefRecord tnf=1 type=536967 payload=01020080B489DEDA8C2271386B7962250063A7C7C8612C3D58C8CD44D674F9D1615E80C72D961F8AC822C3188D48EFC7DA9DA3FF5C306E1EF54E0610F66D1C891CC59428A27CAA4211D4040527CF9BCD16F20E0B3116966AFC2390B7EF30CCC877B8532281CA3CBE286D295AECEA4447FD62874872A46099D6CEED99ED6766B829FD3FDF800025687474703A2F2F70696C65742E65652F6372742F33303836343930302D303030312E637274
                        // ]



                        //                        I/ActivityManager(  440): START u0 {act=android.nfc.action.TECH_DISCOVERED flg=0x20000000 cmp=AndroidNFCExperiment.Activities/.ApplicationWebServiceActivity (has extras)} from pid -1
                        //W/ActivityManager(  440): startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { act=android.nfc.action.TECH_DISCOVERED flg=0x20000000 cmp=AndroidNFCExperiment.Activities/.ApplicationWebServiceActivity (has extras) }
                        //I/System.Console(30978): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED }
                        //I/NfcDispatcher(  747): matched TECH override
                        //I/System.Console(30978): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG }
                        //I/System.Console(30978): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG, p = TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.NdefFormatable], FullName = android.nfc.Tag }
                        //I/System.Console(30978): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.ID }
                        //I/System.Console(30978): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.ID, p = [B@4212cfc8, FullName = [B }
                        //I/System.Console(30978): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.ID, p = [B@4212cfc8, FullName = [B, HexString = fc4969f9 }
                        //I/System.Console(30978): AtResume

                        // https://groups.google.com/forum/#!topic/android-developers/8-17f6ZLYJY
                        //http://stackoverflow.com/questions/9009043/android-nfc-intercept-all-tags
                        var extras = i.getExtras();
                        var ks = extras.keySet();
                        var iterator = ks.iterator();
                        while (iterator.hasNext())
                        {
                            var current = (string)iterator.next();

                            Console.WriteLine("AtNewIntent " + new { action, current });



                            // I/System.Console(29237): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG, p = TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.Ndef], FullName = android.nfc.Tag }
                            // http://stackoverflow.com/questions/5968896/listing-all-extras-of-an-intent
                            extras.get(current).With(
                                p =>
                                {
                                    Console.WriteLine("AtNewIntent " + new { action, current, p, p.GetType().FullName });

                                    (p as Tag).With(
                                       tag =>
                                       {
                                           var id = (byte[])(object)tag.getId();

                                           Console.WriteLine("AtNewIntent " + new { action, current, id = id.ToHexString(), Thread.CurrentThread.ManagedThreadId });

                                           History.Add(
                                                id.ToHexString()
                                            );

                                           //I/System.Console(32331): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG, p = TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.Ndef], id = fdccd727, tech = android.nfc.tech.MifareClassic }
                                           //I/System.Console(32331): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG, p = TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.Ndef], id = fdccd727, tech = android.nfc.tech.NfcA }
                                           //I/System.Console(32331): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG, p = TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.Ndef], id = fdccd727, tech = android.nfc.tech.Ndef }

                                           //I/System.Console(32331): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG, p = TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.NdefFormatable], id = fc4969f9, tech = android.nfc.tech.MifareClassic }
                                           //I/System.Console(32331): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG, p = TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.NdefFormatable], id = fc4969f9, tech = android.nfc.tech.NfcA }
                                           //I/System.Console(32331): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG, p = TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.NdefFormatable], id = fc4969f9, tech = android.nfc.tech.NdefFormatable }

                                           tag.getTechList().WithEach(
                                               tech =>
                                               {
                                                   Console.WriteLine("AtNewIntent " + new { action, current, id = id.ToHexString(), tech });

                                                   if (tech == typeof(android.nfc.tech.MifareClassic).FullName)
                                                   {
                                                       android.nfc.tech.MifareClassic.get(tag).With(
                                                           m =>
                                                           {


                                                           }
                                                       );
                                                   }


                                                   if (tech == typeof(android.nfc.tech.NfcA).FullName)
                                                   {
                                                       android.nfc.tech.NfcA.get(tag).With(
                                                           m =>
                                                           {

                                                           }
                                                       );
                                                   }
                                               }
                                           );

                                           //tag.
                                       }
                                    );

                                    (p as byte[]).With(
                                        bytes =>
                                        {
                                            var HexString = bytes.ToHexString();

                                            Console.WriteLine("AtNewIntent " + new { action, current, p, p.GetType().FullName, HexString });
                                        }
                                    );

                                    // https://android.googlesource.com/platform/packages/apps/Nfc/+/android-4.2.1_r1.2/nci/src/com/android/nfc/dhimpl/NativeNfcTag.java

                                    //(p as android.os.Parcelable[]).With(
                                    //     m =>
                                    //     {

                                    //         Console.WriteLine("AtNewIntent " + new { action, current, records = m.getRecords().Length });

                                    //         m.getRecords().WithEach(
                                    //             r =>
                                    //             {
                                    //                 Console.WriteLine("AtNewIntent " + new { action, current, id = ((byte[])(object)r.getId()).ToHexString() });

                                    //             }
                                    //         );
                                    //     }
                                    // );
                                }
                            );

                        }

                        //                        I/System.Console(29527): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED }
                        //I/System.Console(29527): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG }
                        //I/System.Console(29527): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG, p = TAG: Tech [android.nfc.tech.MifareClassic, android.nfc.tech.NfcA, android.nfc.tech.Ndef], FullName = android.nfc.Tag }
                        //I/System.Console(29527): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.ID }
                        //I/System.Console(29527): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.ID, p = [B@42156c88, FullName = [B }
                        //I/System.Console(29527): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.NDEF_MESSAGES }
                        //I/System.Console(29527): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.NDEF_MESSAGES, p = [Landroid.os.Parcelable;@42156e98, FullName = [Landroid.os.Parcelable; }
                        //I/System.Console(29527): AtResume





                        //                        I/System.Console(28867): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED }
                        //I/System.Console(28867): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.TAG }
                        //I/System.Console(28867): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.ID }
                        //I/System.Console(28867): AtNewIntent { action = android.nfc.action.TECH_DISCOVERED, current = android.nfc.extra.NDEF_MESSAGES }




                        //var id = tag.getId();

                        //Console.WriteLine("AtNewIntent " + new { action, tag, id.Length, id = ((byte[])(object)id).ToHexString() });

                        //tag.getTechList().WithEach(
                        //    tech =>
                        //    {
                        //        Console.WriteLine("AtNewIntent " + new { action, tech });
                        //    }
                        //);
                        //tag.get
                    }
                };

            // who is using it?
            activity.AtResume +=
                delegate
                {
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine("AtResume");
                    Console.WriteLine();
                    adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
                };

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("before enableForegroundDispatch");
            adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);


            activity.AtPause +=
               delegate
               {
                   Console.WriteLine();
                   Console.WriteLine();
                   Console.WriteLine("AtPause");
                   adapter.disableForegroundDispatch(activity);
               };
        }
Exemple #18
0
 // X:\jsc.svn\examples\javascript\android\com.abstractatech.battery\com.abstractatech.battery\ApplicationWebService.cs
 public abstract Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter);