Beispiel #1
0
        /// <summary>
        /// 打印文本内容
        /// </summary>
        /// <param name="message">打印的内容</param>
        /// <param name="err">2:没有开启蓝牙,3:没有连接打印机,4:butmap为null,5:程序出现异常</param>
        /// <returns></returns>
        public bool SendMessage(Java.Lang.String message, out int err)
        {
            err = 0;
            if (!isopen)
            {
                err = 2;
                return(false);
            }
            if (this.chatService.GetState() != BluetoothService.STATE_CONNECTED)
            {
                err = 3;
                return(false);
            }

            if (message.Length() <= 0)
            {
                err = 4;
                return(false);
            }
            try
            {
                byte[] send = message.GetBytes();
                chatService.Write(send);
                return(true);
            }
            catch
            {
                err = 5;
                return(false);
            }

            // Get the message bytes and tell the BluetoothService to write
        }
Beispiel #2
0
        private bool WriteNFC(Ndef ndef, string mensagem)
        {
            bool retorno = false;

            try
            {
                if (ndef != null)
                {
                    ndef.Connect();
                    NdefRecord mimeRecord = null;

                    Java.Lang.String str = new Java.Lang.String(mensagem);

                    mimeRecord = NdefRecord.CreateMime
                                     ("UTF-8", str.GetBytes(Charset.ForName("UTF-8")));

                    ndef.WriteNdefMessage(new NdefMessage(mimeRecord));
                    ndef.Close();
                    retorno = true;
                }
                else
                {
                    retorno = FormatNFC(ndef);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw new System.Exception("Não foi possível ler o cartão.");
            }

            return(retorno);
        }
Beispiel #3
0
        private Boolean FormatNFC(Ndef ndef)
        {
            bool retorno = false;

            NdefFormatable ndefFormatable = NdefFormatable.Get(ndef.Tag);

            Java.Lang.String msg = new Java.Lang.String(MENSAGEM_PADRAO);
            try
            {
                if (ndefFormatable == null)
                {
                    return(retorno);
                }

                if (!ndefFormatable.IsConnected)
                {
                    ndefFormatable.Connect();
                }
                ndefFormatable.Format(new NdefMessage(NdefRecord.CreateMime
                                                          ("UTF-8", msg.GetBytes(Charset.ForName("UTF-8")))));
                ndefFormatable.Close();
                retorno = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw new System.Exception("Não foi possível ler o cartão.");
            }

            return(retorno);
        }
        private void writeData(Java.Lang.String data)
        {
            try
            {
                outStream = myConnection.thisSocket.OutputStream;
            }
            catch (System.Exception)
            {
                Toast.MakeText(this, "Error", ToastLength.Short).Show();
            }

            Java.Lang.String message = data;

            byte[] msgBuffer = message.GetBytes();


            try
            {
                outStream.Write(msgBuffer, 0, msgBuffer.Length);
            }
            catch (System.Exception e)
            {
                Toast.MakeText(this, "Error 1", ToastLength.Short).Show();
            }
        }
            public static string?Exec(string command)
            {
                var runtime = Java.Lang.Runtime.GetRuntime();

                if (runtime == null)
                {
                    throw new NullReferenceException("Java.Lang.Runtime.GetRuntime");
                }
                try
                {
                    var command2 = new Java.Lang.String(command);
                    using var process = runtime.Exec("sh");
                    if (process != null)
                    {
                        using var bufferedOutputStream = new Java.IO.BufferedOutputStream(process.OutputStream);
                        using var bufferedInputStream  = new Java.IO.BufferedInputStream(process.InputStream);
                        bufferedOutputStream.Write(command2.GetBytes());
                        bufferedOutputStream.Write('\n');
                        bufferedOutputStream.Flush();
                        bufferedOutputStream.Close();
                        process.WaitFor();
                        var outputStr = GetStrFromBufferInputSteam(bufferedInputStream);
                        return(outputStr);
                    }
                }
                catch (Java.Lang.Throwable t)
                {
                    t.PrintStackTraceWhenDebug();
                }
                return(null);
            }
Beispiel #6
0
        public void BthSend(string data)
        {
            //System.Diagnostics.Process.GetCurrentProcess().CloseMainWindow();
            //    Process.KillProcess(Process.MyPid());
            Stream outStream = null;

            //Extraemos el stream de salida
            try
            {
                outStream = BthSocket.OutputStream;
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine("Error al enviar" + e.Message);
            }

            //creamos el string que enviaremos
            Java.Lang.String message = new Java.Lang.String(data);

            //lo convertimos en bytes
            byte[] msgBuffer = message.GetBytes();

            try
            {
                //Escribimos en el buffer el arreglo que acabamos de generar
                outStream.Write(msgBuffer, 0, msgBuffer.Length);
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine("Error al enviar" + e.Message);
                Xamarin.Forms.MessagingCenter.Send <App, string>((App)Xamarin.Forms.Application.Current, "Barcode", "BT DISCONNECTED");
                _ct.Cancel();
            }
        }
        /// <summary>
        /// 打印文本内容
        /// </summary>
        /// <param name="message">打印的内容</param>
        /// <param name="err">2:没有开启蓝牙,3:没有连接打印机,4:butmap为null,5:程序出现异常</param>
        /// <returns></returns>
        public int SendMessage(Java.Lang.String message)
        {
            int err = 0;

            if (!isopen)
            {
                err = (int)PrintError.OpenFailure;
                return(err);
            }
            if (this.chatService.GetState() != BluetoothService.STATE_CONNECTED)
            {
                err = (int)PrintError.ConnectedFailure;
                return(err);
            }

            if (message.Length() <= 0)
            {
                err = (int)PrintError.SendNull;;
                return(err);
            }
            try
            {
                byte[] send = message.GetBytes("GB2312");
                chatService.Write(send);
                err = 1;
                return(err);
            }
            catch
            {
                err = (int)PrintError.SendFailure;;
                return(err);
            }

            // Get the message bytes and tell the BluetoothService to write
        }
        //Metodo de envio de datos la bluetooth
        private void writeData(Java.Lang.String data)
        {
            //Extraemos el stream de salida
            try
            {
                outStream = btSocket.OutputStream;
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine("Error al enviar" + e.Message);
            }

            //creamos el string que enviaremos
            Java.Lang.String message = new Java.Lang.String(data.Concat("\n"));

            //lo convertimos en bytes
            byte[] msgBuffer = message.GetBytes();

            try
            {
                //Escribimos en el buffer el arreglo que acabamos de generar
                outStream.Write(msgBuffer, 0, msgBuffer.Length);
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine("Error al enviar" + e.Message);
            }
        }
Beispiel #9
0
        private void WriteData(Java.Lang.String Data)
        {
            //Extraemos el stream de salida
            try
            {
                outStream = btSocket.OutputStream;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error al enviar" + e.Message);
            }
            //convertimos los datos de envio en bytes
            byte[] msgBuffer = Data.GetBytes();

            try
            {
                //Escribimos en el buffer el arreglo que acabamos de generar
                outStream.Write(msgBuffer, 0, msgBuffer.Length);
            }
            catch (System.Exception e)
            {
                Console.WriteLine("Error al enviar" + e.Message);
            }
            outStream.Close();
        }
Beispiel #10
0
        public void WriteData(string data)
        {
            if (BTSocket == null)
            {
                return;
            }

            try
            {
                outStream = BTSocket.OutputStream;
            }
            catch (System.Exception e)
            {
                UserDialogs.Instance.Alert("Error Sending Data!");
            }

            Java.Lang.String message = new Java.Lang.String(data.ToCharArray());

            byte[] msgBuffer = message.GetBytes();

            try
            {
                outStream.Write(msgBuffer, 0, msgBuffer.Length);
            }
            catch (System.Exception e)
            {
                UserDialogs.Instance.Alert("Error Sending Data!");
            }
        }
Beispiel #11
0
 private void SendData(Java.Lang.String data)
 {
     if (_socket != null)
     {
         var buffer = data.GetBytes();
         _socket.OutputStream.Write(buffer, 0, buffer.Length);
     }
 }
        public Task <OfflinePack> DownloadMap(OfflinePackRegion region, Dictionary <string, string> packInfo)
        {
            var tcs          = new TaskCompletionSource <OfflinePack>();
            var latLngBounds = new LatLngBounds.Builder()
                               .Include(region.Bounds.NorthEast.ToLatLng())                          // Northeast
                               .Include(region.Bounds.SouthWest.ToLatLng())                          // Southwest
                               .Build();
            var definition = new OfflineTilePyramidRegionDefinition(
                region.StyleURL,
                latLngBounds,
                region.MinimumZoomLevel,
                region.MaximumZoomLevel,
                Android.App.Application.Context.Resources.DisplayMetrics.Density);

            byte[] metadata = null;
            if (packInfo != null)
            {
                //var binFormatter = new BinaryFormatter();
                //var mStream = new MemoryStream();
                //binFormatter.Serialize(mStream, packInfo);
                //metadata = mStream.ToArray();
                try
                {
                    var jsonObject = new JsonObject();

                    foreach (KeyValuePair <string, string> pair in packInfo)
                    {
                        jsonObject.AddProperty(pair.Key, pair.Value);
                    }
                    var json = new Java.Lang.String(jsonObject.ToString());
                    metadata = json.GetBytes(JSON_CHARSET);
                    System.Diagnostics.Debug.WriteLine("Encoding metadata succeeded: " + metadata.Length.ToString());
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Failed to encode metadata: " + ex.Message);
                }
            }

            offlineManager.CreateOfflineRegion(
                definition,
                metadata,
                new CreateOfflineRegionCallback(
                    (reg) =>
            {
                reg.SetDownloadState(OfflineRegion.StateActive);
                tcs.TrySetResult(reg.ToFormsPack());
            },
                    (msg) =>
            {
                System.Diagnostics.Debug.WriteLine("[ERROR] Couldn't create offline pack: " + msg);
                tcs.TrySetResult(null);
            }
                    )
                );

            return(tcs.Task);
        }
Beispiel #13
0
 private void writeData(Java.Lang.String data)
 {
     Java.Lang.String message   = data;
     byte[]           msgBuffer = message.GetBytes();
     try {
         driver.Write(msgBuffer, 0);
     } catch (System.Exception e) {
         Toast.MakeText(this, e.Message, ToastLength.Short).Show();
         System.Console.WriteLine("Error al enviar" + e.Message);
     }
 }
Beispiel #14
0
        private static void writeInstallationFile(Java.IO.File installation)
        {
            FileOutputStream outFile = new FileOutputStream(installation);

            Java.Lang.String id = new Java.Lang.String(UUID.RandomUUID().ToString());
            outFile.Write(id.GetBytes());
            outFile.Close();
            //string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); //Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
            //string filename = Path.Combine(path, fileName);

            //using (var streamWriter = new StreamWriter(filename, true))
            //{
            //    streamWriter.WriteLine(UUID.RandomUUID().ToString());
            //}
        }
Beispiel #15
0
 public static void Write(OutputStream outputStream, Java.Lang.String text, string encoding)
 {
     try
     {
         outputStream.Write(text.GetBytes(encoding));
     }
     catch (IOException e)
     {
         throw new UncheckedIOException(e);
     }
     finally
     {
         CloseSilently(outputStream);
     }
 }
Beispiel #16
0
        private void writeData(Java.Lang.String data)
        {
            try {
                outStream = btSocket.OutputStream;
            } catch (System.Exception e) {
                System.Console.WriteLine("Error al enviar" + e.Message);
            }
            Java.Lang.String message   = data;
            byte[]           msgBuffer = message.GetBytes();

            try {
                outStream.Write(msgBuffer, 0, msgBuffer.Length);
            } catch (System.Exception e) {
                System.Console.WriteLine("Error al enviar" + e.Message);
            }
        }
Beispiel #17
0
        private void OnSendData(object sender, EventArgs e)
        {
            Java.Lang.String text     = new Java.Lang.String(etInput.Text);
            byte[]           byteText = text.GetBytes();

            try
            {
                mOutputStream.Write(byteText, 0, byteText.Length);
                mOutputStream.Flush();
            }
            catch (System.Exception ex)
            {
                Cancel();
                System.Console.WriteLine(ex.Message);
            }

            etInput.Text = "";
        }
Beispiel #18
0
        /// <summary>
        /// Re-sends the OBD-II request.
        /// </summary>
        /// <param name="outputBuffer"></param>
        protected void ResendCommand(OBDConnectionService connectionService)
        {
            // Check that we're actually connected before trying anything
            if (connectionService.GetState() != OBDConnectionService.STATE_CONNECTED)
            {
                Toast.MakeText(Application.Context, Resource.String.not_connected, ToastLength.Short).Show();
                return;
            }
            // adds the carriage return character
            var message = new Java.Lang.String("\r");

            // Get the message bytes and tell the BluetoothConnectionService to write
            byte[] send = message.GetBytes();
            connectionService.Write(send);
            // Sleep Thread cause it has done its job (to check)
            if (responseDelayInMs != null && responseDelayInMs.Milliseconds > 0)
            {
                Thread.Sleep(responseDelayInMs.Milliseconds);
            }
        }
Beispiel #19
0
        public DeviceUuidFactory(Context context)
        {
            if (uuid == null)
            {
                lock (_lock)
                {
                    if (uuid == null)
                    {
                        var prefs = context.GetSharedPreferences(PREFS_FILE, FileCreationMode.Private);
                        var id    = prefs.GetString(PREFS_DEVICE_ID, null);

                        if (!string.IsNullOrWhiteSpace(id))
                        {
                            // Use the ids previously computed and stored in the prefs file
                            uuid = UUID.FromString(id);
                        }
                        else
                        {
                            var androidId = Settings.Secure.GetString(context.ContentResolver, Settings.Secure.AndroidId);

                            // Use the Android ID unless it's broken, in which case fallback on deviceId,
                            // unless it's not available, then fallback on a random number which we store
                            // to a prefs file

                            if ("9774d56d682e549c" == androidId)
                            {
                                //Generate a new UUID rather than require READ_PHONE_STATE
                                var c = new Java.Lang.String(androidId);
                                uuid = UUID.NameUUIDFromBytes(c.GetBytes("utf8"));
                            }
                            else
                            {
                                uuid = UUID.RandomUUID();
                            }

                            prefs.Edit().PutString(PREFS_DEVICE_ID, uuid.ToString()).Apply();
                        }
                    }
                }
            }
        }
Beispiel #20
0
        public async Task <bool> SendInfo(Dictionary <BLECommand, string> data)
        {
            string startFlag = "<start>";
            string endFlag   = "<end>";

            StringBuilder sb = new StringBuilder();

            try
            {
                foreach (var i in data)
                {
                    sb.Append(startFlag);
                    sb.Append("/");
                    sb.Append((int)i.Key);
                    sb.Append("/");
                    sb.Append(i.Value);
                    sb.Append("/");
                    sb.Append(endFlag);

                    Java.Lang.String msg = new Java.Lang.String(sb.ToString());

                    byte[] buffer = msg.GetBytes();

                    await socket.OutputStream.WriteAsync(buffer, 0, buffer.Length);

                    sb.Clear();

                    Thread.Sleep(1000);
                }


                return(true);
            }

            catch
            {
                return(false);
            }
        }
Beispiel #21
0
        public async void DoSendStream(string data)
        {
            // if (_btSocket != null && _btSocket.IsConnected == true && data != null)
            {
                _btAdapter?.CancelDiscovery();

                try
                {
                    _outStream = _btSocket.OutputStream;
                }
                catch (Exception e1)
                {
                    await _page.DisplayAlert("Exception", $"CustomBluetoothMancager.DoSendStream => e1 => {e1}", "OK");

                    return;
                }


                byte[] msgBuffer = new Java.Lang.String(data).GetBytes();
                byte[] bytes     = Encoding.ASCII.GetBytes(data);

                Java.Lang.String javaString = new Java.Lang.String(data);
                byte[]           temp       = javaString.GetBytes();

                const int offset = 0;

                try
                {
                    _outStream.Write(temp, offset, temp.Length);
                }
                catch (Exception e2)
                {
                    await _page.DisplayAlert("Exception", $"CustomBluetoothMancager.DoSendStream => e2 => {e2}", "OK");

                    return;
                }
            }
        }
        private void WriteData(string data)
        {
            try
            {
                outStream = btSocket.OutputStream;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error al enviar" + e.Message);
            }

            Java.Lang.String message = new Java.Lang.String(data);

            byte[] msgBuffer = message.GetBytes();

            try
            {
                outStream.Write(msgBuffer, 0, msgBuffer.Length);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error al enviar" + e.Message);
            }
        }
Beispiel #23
0
        public void WriteData(string data)
        {
            try
            {
                outStream = BTSocket.OutputStream;
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine("Error Sending " + e.Message);
            }

            Java.Lang.String message = new Java.Lang.String(data);

            byte[] msgBuffer = message.GetBytes();

            try
            {
                outStream.Write(msgBuffer, 0, msgBuffer.Length);
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine("Error Sending " + e.Message);
            }
        }
Beispiel #24
0
        private string GetSha256(string key, string data)
        {
            string trimmedKey = key.Replace("-----\\w+ PRIVATE KEY-----", "").Replace("\\s", "");

            try
            {
                byte[] result = Android.Util.Base64.Decode(trimmedKey, Android.Util.Base64Flags.Default);

                var str     = new Java.Lang.String(data);
                var factory = Java.Security.KeyFactory.GetInstance("RSA");
                Java.Security.Spec.EncodedKeySpec keySpec = new Java.Security.Spec.PKCS8EncodedKeySpec(result);
                var signature = Java.Security.Signature.GetInstance("SHA256withRSA");
                var s         = factory.GeneratePrivate(keySpec);
                signature.InitSign(s);
                signature.Update(str.GetBytes());

                byte[] encrypted = signature.Sign();
                return(Android.Util.Base64.EncodeToString(encrypted, Android.Util.Base64Flags.NoWrap));
            }
            catch (Exception e)
            {
            }
            return(null);
        }
	    /**
	     * Only call this method from the main (UI) thread. The {@link OnFetchCompleteListener} callback
	     * be invoked on the UI thread, but image fetching will be done in an {@link AsyncTask}.
	     *
	     * @param cookie An arbitrary object that will be passed to the callback.
	     */
	    public static void FetchImage(Context context, Java.Lang.String url, BitmapFactory.Options decodeOptions, Java.Lang.Object cookie, Action<Bitmap> callback) 
		{
			
			Task.Factory.StartNew(() => {
				if(TextUtils.IsEmpty(url))
				{
					result = null;
					return;
				}
				
				File cacheFile = null;
				try
				{
					MessageDigest mDigest = MessageDigest.GetInstance("SHA-1");
					mDigest.Update(url.GetBytes());
					string cacheKey = BytesToHexString(mDigest.Digest());
					if(Environment.MediaMounted.Equals(Environment.ExternalStorageState))
					{
						cacheFile = new File(Environment.ExternalStorageDirectory +
						                     File.Separator + "Android " + 
						                     File.Separator + "data" +
						                     File.Separator + context.PackageName + 
						                     File.Separator + "cache" +
						                     File.Separator + "bitmap_" + cacheKey + ".tmp");
					}
				}
				catch (Exception e) 
				{
					// NoSuchAlgorithmException
					// Oh well, SHA-1 not available (weird), don't cache bitmaps.
				}
				
				if (cacheFile != null && cacheFile.Exists()) 
				{
	                Bitmap cachedBitmap = BitmapFactory.DecodeFile(cacheFile.ToString(), decodeOptions);
                    if (cachedBitmap != null) {
                        result = cachedBitmap;
						return;
                    }
                }
				
				try 
				{
				    // TODO: check for HTTP caching headers
					var client = new System.Net.WebClient();
					var image = client.DownloadData(new Uri(url.ToString()));
					if (image != null)
					{
						result = null;
						return;
					}
				
				    // Write response bytes to cache.
				    if (cacheFile != null) {
				        try {
				            cacheFile.ParentFile.Mkdirs();
				            cacheFile.CreateNewFile();
				            FileOutputStream fos = new FileOutputStream(cacheFile);
				            fos.Write(image);
				            fos.Close();
				        } catch (FileNotFoundException e) {
				            Log.Warn(TAG, "Error writing to bitmap cache: " + cacheFile.ToString(), e);
				        } catch (IOException e) {
				            Log.Warn(TAG, "Error writing to bitmap cache: " + cacheFile.ToString(), e);
				        }
				    }
				
				    // Decode the bytes and return the bitmap.
				    result = (BitmapFactory.DecodeByteArray(image, 0, image.Length, decodeOptions));
					return;
				} catch (Exception e) {
				    Log.Warn(TAG, "Problem while loading image: " + e.ToString(), e);
				}
                result = null;
			})
			.ContinueWith(task =>
				callback(result)
        	);
			
	    }
        //Metodo de envio de datos la bluetooth
        private void writeData(Java.Lang.String data)
        {
            //Extraemos el stream de salida
            try
            {
                outStream = btSocket.OutputStream;
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine("Error al enviar" + e.Message);
            }

            //creamos el string que enviaremos
            Java.Lang.String message = new Java.Lang.String(data.Concat("\n"));

            //lo convertimos en bytes
            byte[] msgBuffer = message.GetBytes();

            try
            {
                //Escribimos en el buffer el arreglo que acabamos de generar
                outStream.Write(msgBuffer, 0, msgBuffer.Length);
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine("Error al enviar" + e.Message);
            }
        }
Beispiel #27
0
		/// <summary>
		/// Send the data. The serialization is defined when connecting to the peer, will be the serialization used.
		/// </summary>
		/// <param name="data">data in string format..</param>
		public void Send (string data)
		{
			Java.Lang.String dataString = new Java.Lang.String (data);
			Java.Nio.ByteBuffer bufferData = Java.Nio.ByteBuffer.AllocateDirect (data.Length);
			bufferData.Put (dataString.GetBytes ("UTF-8"));
			bufferData.Flip ();
			DataChannel.Buffer buffer = new DataChannel.Buffer (bufferData, false);
			Channel.Send (buffer);
		}