コード例 #1
0
        public static void InstallApkFile(Context context, string urlString, string PackName)
        {
            string         Err;
            ProgressDialog pd = ProgressDialog.Show(context, new Java.Lang.String("提示"), new Java.Lang.String("正在更新版本,請稍後……"), true);

            Java.Lang.Thread th = new Java.Lang.Thread(() =>
            {
                try
                {
                    downloadFile(context, urlString, PackName);
                }
                catch (Exception ex)
                {
                    pd.Dismiss();
                    Err = ex.Message;
                }
                finally
                {
                    pd.Dismiss();
                    try
                    {
                        openFile(context, setMkdir(context), PackName);
                    }
                    catch
                    {
                        Err = "安裝程序打開錯誤";
                    }
                }
            });
            th.Start();
        }
コード例 #2
0
ファイル: LibVpxCom.cs プロジェクト: billy-lokal/Dateifi_Old
 static LibVpxCom()
 {
     try
     {
         var block = new Object();
         var thread = new Java.Lang.Thread(() =>
         {
             Java.Lang.JavaSystem.LoadLibrary("vpx");
             Java.Lang.JavaSystem.LoadLibrary("vpxJNI");
             lock (block)
             {
                 System.Threading.Monitor.Pulse(block);
             }
         });
         lock (block)
         {
             thread.Start();
             System.Threading.Monitor.Wait(block);
         }
     }
     catch (Exception ex)
     {
         Log.Error("Could not load libvpx. Make sure libvpx.so and libvpxJNI.so are present.", ex);
     }
 }
コード例 #3
0
        public void startTracking()
        {
            if (mTracking)
            {
                return;
            }
            mTracker.reset();

            mSensorEventListener = new SensorEventListener(this);

            Java.Lang.Thread sensorThread = new Java.Lang.Thread(() =>
            {
                Looper.Prepare();

                mSensorLooper   = Looper.MyLooper();
                Handler handler = new Handler();

                SensorManager sensorManager = mContext.GetSystemService(Context.SensorService) as SensorManager;

                foreach (var item in INPUT_SENSORS)
                {
                    var sensor = sensorManager.GetDefaultSensor(item);
                    if (sensor != null)
                    {
                        sensorManager.RegisterListener(mSensorEventListener, sensor, SensorDelay.Fastest, handler);
                    }
                }

                Looper.Loop();
            });

            sensorThread.Start();
            mTracking = true;
        }
コード例 #4
0
        public bool Initialize()
        {
            _initialized = false;
            if (!StopDecoder())
            {
                return(_initialized);
            }

            _mediaFormat = GetMediaFormat(_mimeType, _sampleRate, _channels);
            _mediaCodec  = MediaCodec.CreateDecoderByType(_mimeType);
            _mediaCodec.Configure(
                format: _mediaFormat,
                surface: null,
                crypto: null,
                flags: MediaCodecConfigFlags.None);

            _audioTrack = GetAudioTrack();
            _audioTrack.Play();
            _mediaCodec.Start();


            _encoderThread = GetEncoderThread();
            _encoderThread.Start();

            _decoderThread = GetDecoderThread();
            _decoderThread.Start();

            _initialized = true;
            return(_initialized);
        }
コード例 #5
0
        // static Java.Lang.Thread downloadThread;
        public static void DownloadFromLink(string url, string title, string toast = "", string ending = "", bool openFile = false, string descripts = "")
        {
            try {
                print("DOWNLOADING: " + url);

                DownloadManager.Request request = new DownloadManager.Request(Android.Net.Uri.Parse(url));
                request.SetTitle(title);
                request.SetDescription(descripts);
                string mainPath = Android.OS.Environment.DirectoryDownloads;
                string subPath  = title + ending;
                string fullPath = mainPath + "/" + subPath;

                print("PATH: " + fullPath);

                request.SetDestinationInExternalPublicDir(mainPath, subPath);
                request.SetVisibleInDownloadsUi(true);
                request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);

                DownloadManager manager;
                manager = (DownloadManager)MainActivity.activity.GetSystemService(Context.DownloadService);

                long downloadId = manager.Enqueue(request);

                // AUTO OPENS FILE WHEN DONE DOWNLOADING
                if (openFile || toast != "")
                {
                    Java.Lang.Thread downloadThread = new Java.Lang.Thread(() => {
                        try {
                            bool exists = false;
                            while (!exists)
                            {
                                try {
                                    string p = manager.GetUriForDownloadedFile(downloadId).Path;
                                    exists   = true;
                                }
                                catch (System.Exception) {
                                    Java.Lang.Thread.Sleep(100);
                                }
                            }
                            Java.Lang.Thread.Sleep(1000);
                            if (toast != "")
                            {
                                App.ShowToast(toast);
                            }
                            if (openFile)
                            {
                                print("OPEN FILE");
                                string truePath = (Android.OS.Environment.ExternalStorageDirectory + "/" + fullPath);
                                OpenFile(truePath);
                            }
                        }
                        catch { }
                    });
                    downloadThread.Start();
                }
            }
            catch (Exception _ex) {
                error(_ex);
            }
        }
コード例 #6
0
        /// <summary>
        /// Este evento inicia el proceso de envio de datos, que al usar hilos
        /// ejecuta en segundo plano la funcion Run(), para que envie las respuestas.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnEnviar_Click(object sender, EventArgs e)
        {
            bandera = 1;//Envia Datos
            //progress = ProgressDialog.Show(this, "Progreso de envio de datos", "Enviando datos al servidor....", true, true);

            threadEnviaDatos = new Java.Lang.Thread(this);
            threadEnviaDatos.Start();
        }
コード例 #7
0
        /// <summary>
        /// Este metodo verifica si existe la base de datos para el almacenamiento de información en el dispositivo
        /// Si no existe la crea
        /// </summary>
        public void ConfiguraDB()
        {
            //Buscamos el directorio personal en el dispositivo
            var personalFolderPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
            //Buscamos el directorio database en la carpeta personal
            var databaseFolderPath = string.Format(@"{0}/database", personalFolderPath.Substring(0, personalFolderPath.LastIndexOf('/')));

            if (!Directory.Exists(databaseFolderPath))
            {
                Directory.CreateDirectory(databaseFolderPath);//Si no existe la creamos
            }
            if (!Directory.Exists(databaseFolderPath))
            {
                throw new Exception(string.Format("{0} no existe!", databaseFolderPath));//Si no existe quiere decir que en el paso anterior no se creo correctamente el dir
            }
            //var paths = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim).ToString() + "/Encuestas.db3";

            string dbPath = Path.Combine(databaseFolderPath, "Encuestadb.db3");

            //Verifica si existe el archivo mencionado en la parte de arriba
            exists = File.Exists(dbPath);
            if (!exists)
            {
                SqliteConnection.CreateFile(dbPath);                    //Si no existe crea la base de datos
            }
            connection = new SqliteConnection("Data Source=" + dbPath); //Abre la cadena de conexion con la base de datos creado anteriormente

            if (connection.State == System.Data.ConnectionState.Open)
            {
                connection.Close();
            }

            connection.Open();//Abre la conexion a la base de datos creado con anterioridad

            if (!exists)
            {
                //Por cada comando se realiza la accion en la base de datos (Creacion de tablas, insertar, actualizar, eliminar)
                using (SqliteCommand c = connection.CreateCommand())
                {
                    c.CommandText = "CREATE TABLE [DatosEncuesta] (IdEncuesta ntext, DescEncuesta ntext,IdPregunta ntext,DescPregunta ntext,Respuestas ntext);";
                    c.ExecuteNonQuery();
                }
                using (SqliteCommand cc = connection.CreateCommand())
                {
                    cc.CommandText = "CREATE TABLE [DatosEncuestaEnvia] (IdDispositivo ntext,IdEncuesta ntext,IdsPreguntaRespuesta ntext);";
                    cc.ExecuteNonQuery();
                }
                using (SqliteCommand ccc = connection.CreateCommand())
                {
                    ccc.CommandText = "CREATE TABLE [DatosDispositivo] (NumTel ntext, IMEI ntext);";
                    ccc.ExecuteNonQuery();
                }
                configuraInicio = ProgressDialog.Show(this, "Configurando aplicación", "Instalando y configurando las herramientas" +
                                                      " necesarias para el buen funcionamiento del sistema, espere unos momentos por favor....", true, true);
                threadConfiguraInicial = new Java.Lang.Thread(this);
                threadConfiguraInicial.Start();
            }
        }
コード例 #8
0
            public void Load(EmojiCompat.MetadataRepoLoaderCallback loaderCallback)
            {
                var runnable = new InitRunnable(mContext, loaderCallback, assetName);
                var thread   = new JThread(runnable)
                {
                    Daemon = false
                };

                thread.Start();
            }
コード例 #9
0
 /// <exception cref="System.IO.IOException"></exception>
 public virtual NeoDatis.Odb.Core.Server.Connection.ClientServerConnection WaitForRemoteConnection
     ()
 {
     System.Net.Sockets.TcpClient connection = socketServer.Accept();
     connection.SetTcpNoDelay(true);
     NeoDatis.Odb.Core.Server.Connection.DefaultConnectionThread connectionThread = new
                                                                                    NeoDatis.Odb.Core.Server.Connection.DefaultConnectionThread(this, connection, automaticallyCreateDatabase
                                                                                                                                                );
     Java.Lang.Thread thread = new Java.Lang.Thread(connectionThread);
     connectionThread.SetName(thread.GetName());
     thread.Start();
     return(connectionThread);
 }
コード例 #10
0
        public void TakeScreenShot()
        {
            Java.Lang.Thread thread = new Java.Lang.Thread(() =>
            {
                var bitMap = Bitmap.CreateBitmap(containerView.Width,
                                                 containerView.Height, Bitmap.Config.Argb8888);
                Canvas canvas = new Canvas(bitMap);
                containerView.Draw(canvas);
                bitmap = bitMap;
            });

            thread.Start();
        }
コード例 #11
0
        public void InicializarPagina()
        {
            // Carga los pokemons iniciales
            GlobalVar.friendCoach.pokemons.Add(rep.ObtenerPokemon(GlobalVar.friendCoach.user.pokemons[0].name));
            GlobalVar.enemyCoach.pokemons.Add(rep.ObtenerPokemon(GlobalVar.enemyCoach.user.pokemons[0].name));

            // Pone a cargar el resto de pokemons de forma secundaria
            CargarPokemonsThread.Start();

            // Genero y gestiono los grids de la página
            GlobalGrid.InicializarGrids();
            GlobalGrid.DimensionarGrids();
            GlobalGrid.EstructurarGrids();
        }
コード例 #12
0
        public void ScanNetworks()
        {
            if (_cts != null)
            {
                _cts.Cancel();
            }
            _thread = null;

            _cts = new CancellationTokenSource();

            _run    = new ReadingRun(_usbConnection, _usbReadEndpoint, _usbWriteEndpoint, _handler, _cts.Token);
            _thread = new Java.Lang.Thread(_run);
            _thread.Start();
        }
コード例 #13
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.proximity_status);
            _viewModel = new ProximityStatusViewModel();
            _viewModel.GetAndParseDevices();
            InitView();

            Thread thread = new Thread(ResizeDevider);

            thread.Start();

            StartBluetoothIfHasPermissions();
        }
コード例 #14
0
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            Toast.MakeText(this, "Started", ToastLength.Long).Show();
            var t = new Java.Lang.Thread(async() =>
            {
                while (true)
                {
                    try
                    {
                        var address = $"http://192.168.1.103:5166?id=1234&timestamp={DateTime.UtcNow}&lat=1.2&lon=2.3&altitude=1&speed=0&bearing=0&accuracy=0";
                        var client  = new HttpClient();
                        //client.BaseAddress = new Uri(address);
                        var content = new StringContent("", Encoding.UTF8, "application/json");
                        HttpResponseMessage response = await client.PostAsync(address, content);
                        var result = await response.Content.ReadAsStringAsync();
                    }catch (Exception e)
                    {
                    }
                    Thread.Sleep(30000);
                }
                //_cts = new CancellationTokenSource();

                //Task.Run(() =>
                //{
                //    try
                //    {
                //        var cloud = new CloudUploader();
                //        cloud.ExecutePost(_cts.Token).Wait();
                //    }
                //    catch (Android.Accounts.OperationCanceledException)
                //    {
                //    }
                //    finally
                //    {
                //        if (_cts.IsCancellationRequested)
                //        {

                //        }
                //    }

                //}, _cts.Token);
            });

            t.Start();
            return(StartCommandResult.Sticky);
        }
コード例 #15
0
        public void CastVideoStart()
        {
            print("START");

            updateThred = new Java.Lang.Thread(() =>
            {
                try {
                    while (castingVideo)
                    {
                        Java.Lang.Thread.Sleep(1000);
                        RunOnUiThread(() => UpdateTime());
                    }
                }
                finally {
                    updateThred.Join();
                }
            });
            updateThred.Start();
        }
コード例 #16
0
        public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
        {
            var t = new Java.Lang.Thread(() =>
            {
                Task.Run(() =>
                {
                    try
                    {
                        databaseService.CreateDataBase();
                        activityManager = (ActivityManager)GetSystemService(Context.ActivityService);
                        ExecuteSpentTimehecking().Wait();
                    }
                    catch (Exception exception)
                    {
                    }
                });
            }
                                         );

            t.Start();
            return(StartCommandResult.Sticky);
        }
コード例 #17
0
        public static Java.Lang.Thread StartThread(Java.Lang.Runnable runnable)
        {
            if (runnable == null)
            {
                return(null);
            }

            Java.Lang.Thread thread = new Java.Lang.Thread(runnable);

            if (thread != null)
            {
                try
                {
                    thread.Start();
                }
                catch (Java.Lang.IllegalThreadStateException)
                {
                    thread = null;
                }
            }

            return(thread);
        }
コード例 #18
0
 public void start()
 {
     mDetectorThread = new Java.Lang.Thread(mDetector);
     mDetectorThread.Start();
 }
コード例 #19
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            // Use this to return your custom view for this Fragment
            // return inflater.Inflate(Resource.Layout.YourFragment, container, false);
            View view = inflater.Inflate(Resource.Layout.ax_Settings, container, false);

            ax_settings = this;

            // --------- SET VARS ---------

            var cbookmarks = view.FindViewById(Resource.Id.clearbookmarks);
            var chistory   = view.FindViewById(Resource.Id.clearhistory);

            msearch    = view.FindViewById <CheckBox>(Resource.Id.msearch);
            hdasearch  = view.FindViewById <CheckBox>(Resource.Id.hdasearch);
            asearch    = view.FindViewById <CheckBox>(Resource.Id.asearch);
            basearch   = view.FindViewById <CheckBox>(Resource.Id.basearch);
            tvasearch  = view.FindViewById <CheckBox>(Resource.Id.tvasearch);
            htvasearch = view.FindViewById <CheckBox>(Resource.Id.htvasearch);
            bmsearch   = view.FindViewById <CheckBox>(Resource.Id.bmsearch);
            hdbasearch = view.FindViewById <CheckBox>(Resource.Id.hdbasearch);

            savelinks  = view.FindViewById <CheckBox>(Resource.Id.savelinks);
            savetitles = view.FindViewById <CheckBox>(Resource.Id.savetitles);
            savem3u    = view.FindViewById <CheckBox>(Resource.Id.savem3u);

            Button updatebtt = view.FindViewById <Button>(Resource.Id.update);

            updatebtt.Visibility = ViewStates.Gone;


            // --------- PING DATA ---------

            seachBoxes = new List <CheckBox> {
                msearch, hdasearch, asearch, basearch, tvasearch, bmsearch, htvasearch, hdbasearch
            };
            for (int i = 0; i < seachBoxes.Count; i++)
            {
                searchTxts[i] = seachBoxes[i].Text;
            }

            Button pingBtt = view.FindViewById <Button>(Resource.Id.pingProviders);

            pingBtt.Click += (o, e) =>
            {
                for (int i = 0; i < providersCount; i++)
                {
                    DelegateWithParameters_int ping =
                        new DelegateWithParameters_int(Ping);

                    IAsyncResult tag =
                        ping.BeginInvoke(i, null, null);
                }
            };

            Button showBtt = view.FindViewById <Button>(Resource.Id.showProviders);

            showBtt.Click += (o, e) =>
            {
                showSites = !showSites;
                for (int i = 0; i < providersCount; i++)
                {
                    seachBoxes[i].Text = searchTxts[i] + (showSites ? (" (" + pingLinks[i] + ")") : "");
                }
            };

            // --------- AUTO UPDATE ---------

            version = Context.PackageManager.GetPackageInfo(Context.PackageName, 0).VersionName;
            TextView versionTxt = view.FindViewById <TextView>(Resource.Id.versionTxt);

            versionTxt.Text = "v" + version;
            sThred          = new Java.Lang.Thread(() =>
            {
                try {
                    WebClient client = new WebClient();
                    string d         = client.DownloadString("https://github.com/LagradOst/CloudStream/releases");
                    string look      = "/LagradOst/CloudStream/releases/tag/";
                    //   float bigf = -1;
                    //     string bigUpdTxt = "";
                    // while (d.Contains(look)) {
                    string tag     = FindHTML(d, look, "\"");
                    string updText = FindHTML(d, look + tag + "\">", "<");

                    /*
                     *  try {
                     *      float tagf = float.Parse(tag.Replace("v", ""));
                     *      print("" + tagf);
                     *      if(tagf > bigf) {
                     *          bigf = tagf;
                     *          bigUpdTxt = updText;
                     *      }
                     *  }
                     *  catch (Exception) {
                     *
                     *  }
                     *  d = d.Substring(d.IndexOf(look) + 1, d.Length - d.IndexOf(look) - 1);
                     */
                    updatebtt.Click += (o, e) =>
                    {
                        if (version != updateTo && updateTo != "-1")
                        {
                            string downloadLink = "https://github.com/LagradOst/CloudStream/releases/download/" + updateTo + "/CloudStream.CloudStream.apk";
                            DownloadFromLink(downloadLink, "CloudStream-" + updateTo, "Downloading APK", this, ".apk", true);
                            updatebtt.Visibility = ViewStates.Gone;
                        }
                    };

                    if (tag != "")
                    {
                        Activity.RunOnUiThread(new Action(() =>
                        {
                            updateTo = tag;
                            if (tag == "v" + version)
                            {
                                versionTxt.Text      = "v" + version + " (Up to date)";
                                updatebtt.Visibility = ViewStates.Gone;
                            }
                            else
                            {
                                versionTxt.Text      = "v" + version + " -> " + tag + " (" + updText + ")";
                                updatebtt.Visibility = ViewStates.Visible;
                                updatebtt.Text       = "Update to " + tag;
                            }
                        }));
                    }
                }
                finally {
                    sThred.Join();
                }
            });
            if (searchForUpdates)
            {
                sThred.Start();
            }
            //  var sdownloads =  view.FindViewById(Resource.Id.showdownloads);

            // sdownloads.Click += (o,e) => MainActivity.mainActivity.ShowDownloads();



            // --------- DEF DATA ---------

            var set = Application.Context.GetSharedPreferences("Settings", FileCreationMode.Private);

            msearch.Checked    = set.GetBoolean("msearch", true);
            hdasearch.Checked  = set.GetBoolean("hdasearch", haveAnimeEnabled);
            asearch.Checked    = set.GetBoolean("asearch", false);
            basearch.Checked   = set.GetBoolean("basearch", false);
            tvasearch.Checked  = set.GetBoolean("tvasearch", false);
            bmsearch.Checked   = set.GetBoolean("bmsearch", false);
            htvasearch.Checked = set.GetBoolean("htvasearch", true);
            hdbasearch.Checked = set.GetBoolean("hdbasearch", false);
            savem3u.Checked    = set.GetBoolean("savem3u", false);

            if (!haveAnimeEnabled)
            {
                hdasearch.Visibility  = ViewStates.Gone;
                asearch.Visibility    = ViewStates.Gone;
                basearch.Visibility   = ViewStates.Gone;
                hdbasearch.Visibility = ViewStates.Gone;
            }


            // --------- SAVE DATA ---------

            savelinks.Checked  = set.GetBoolean("savelinks", true);
            savetitles.Checked = set.GetBoolean("savetitles", true);

            msearch.Click    += (o, e) => SaveBool("msearch", msearch.Checked);
            hdasearch.Click  += (o, e) => SaveBool("hdasearch", hdasearch.Checked);
            asearch.Click    += (o, e) => SaveBool("asearch", asearch.Checked);
            basearch.Click   += (o, e) => SaveBool("basearch", basearch.Checked);
            tvasearch.Click  += (o, e) => SaveBool("tvasearch", tvasearch.Checked);
            bmsearch.Click   += (o, e) => SaveBool("bmsearch", bmsearch.Checked);
            htvasearch.Click += (o, e) => SaveBool("htvasearch", htvasearch.Checked);
            hdbasearch.Click += (o, e) => SaveBool("hdbasearch", hdbasearch.Checked);

            savelinks.Click  += (o, e) => SaveBool("savelinks", savelinks.Checked);
            savetitles.Click += (o, e) => SaveBool("savetitles", savetitles.Checked);
            savem3u.Click    += (o, e) => SaveBool("savem3u", savem3u.Checked); // M3U FILE

            // --------- HISTORY ---------

            chistory.SetBackgroundColor(Color.AliceBlue);
            cbookmarks.SetBackgroundColor(Color.AliceBlue);
            //  sdownloads.SetBackgroundColor(Color.AliceBlue);

            chistory.LongClickable   = true;
            cbookmarks.LongClickable = true;

            chistory.LongClick += (o, e) =>
            {
                ShowSnackBar("Removed All Viewhistory", o);
                var localC = Application.Context.GetSharedPreferences("History", FileCreationMode.Private);
                var edit   = localC.Edit();
                edit.Clear();
                edit.Commit();
            };
            cbookmarks.LongClick += (o, e) =>
            {
                ShowSnackBar("Removed All Bookmarks", o);
                var localC = Application.Context.GetSharedPreferences("Bookmarks", FileCreationMode.Private);
                var edit   = localC.Edit();
                edit.Clear();
                edit.Commit();
                ax_Bookmarks.ax_bookmarks.UpdateList();
            };
            chistory.Click += (o, e) =>
            {
                ShowSnackBar("Hold To Remove History", o);
            };
            cbookmarks.Click += (o, e) =>
            {
                ShowSnackBar("Hold To Remove Bookmarks", o);
            };

            // --------- ACTIONS ---------

            var defAct = view.FindViewById <Spinner>(Resource.Id.DefSpinner);
            var secAct = view.FindViewById <Spinner>(Resource.Id.SecSpinner);


            var adapter = new ArrayAdapter <string>(Context, Android.Resource.Layout.SimpleSpinnerItem, defChecks);

            defAct.Adapter = adapter;
            secAct.Adapter = adapter;

            defActions[0] = SettingsGetDef(0); // set.GetInt("defAct", 0);
            defActions[1] = SettingsGetDef(1); // set.GetInt("secAct", 1);

            defAct.SetSelection(defActions[0]);
            secAct.SetSelection(defActions[1]);

            defAct.ItemSelected += (o, e) => { SaveInt("defAct", e.Position); defActions[0] = e.Position; };
            secAct.ItemSelected += (o, e) => { SaveInt("secAct", e.Position); defActions[1] = e.Position; };

            return(view);
        }
コード例 #20
0
ファイル: ODBServerImpl.cs プロジェクト: ekicyou/pasta
		/// <exception cref="System.IO.IOException"></exception>
		public virtual NeoDatis.Odb.Core.Server.Connection.ClientServerConnection WaitForRemoteConnection
			()
		{
			System.Net.Sockets.TcpClient connection = socketServer.Accept();
			connection.SetTcpNoDelay(true);
			NeoDatis.Odb.Core.Server.Connection.DefaultConnectionThread connectionThread = new 
				NeoDatis.Odb.Core.Server.Connection.DefaultConnectionThread(this, connection, automaticallyCreateDatabase
				);
			Java.Lang.Thread thread = new Java.Lang.Thread(connectionThread);
			connectionThread.SetName(thread.GetName());
			thread.Start();
			return connectionThread;
		}
コード例 #21
0
        //protected override void OnHandleWork(Intent p0)
        //{

        //}
        public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
        {
            var t = new Java.Lang.Thread(() => {
                _cts = new CancellationTokenSource();

                Task.Run(() =>
                {
                    try
                    {
                        _bleServer = new BleServer(this.ApplicationContext);
                    }
                    catch (Android.Accounts.OperationCanceledException)
                    {
                    }
                    finally
                    {
                        if (_cts.IsCancellationRequested)
                        {
                        }
                    }
                }, _cts.Token);
            }
                                         );

            t.Start();
            Task.Run(async() =>
            {
                bleScannerService = BleScannerService.GetInstance;
                //    while (true)
                //{
                //    using (var notificationManager = NotificationManager.FromContext(ApplicationContext))
                //    {
                //        var title = "Title";
                //        var channelName = "TestChannel";
                //        if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
                //        {
                //            NotificationChannel channel = null;
                //            if (channel == null)
                //            {
                //                channel = new NotificationChannel(channelName, channelName, NotificationImportance.Low)
                //                {
                //                    LockscreenVisibility = NotificationVisibility.Public
                //                };
                //                channel.SetShowBadge(true);
                //                notificationManager.CreateNotificationChannel(channel);
                //            }
                //            channel.Dispose();
                //        }
                //        // var bitMap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.notification_template_icon_bg);
                //        var notificationBuilder = new NotificationCompat.Builder(ApplicationContext)
                //                                                                .SetContentTitle(title)
                //                                                                .SetContentText("test")
                //                                                                .SetSmallIcon(Android.Resource.Drawable.IcDialogInfo)
                //                                                                .SetShowWhen(false)
                //                                                                .SetChannelId(channelName);

                //        var notification = notificationBuilder.Build();
                //        notificationManager.Notify(0, notification);
                //    }
                Thread.Sleep(60000);
            });
            return(StartCommandResult.Sticky);
        }
コード例 #22
0
ファイル: thread.cs プロジェクト: guojianbin/fastCSharp
 public static void start(this Java.Lang.Thread thread)
 {
     thread.Start();
 }