コード例 #1
0
        public string GetDeviceUUID()
        {
            System.Diagnostics.Debug.WriteLine("[IMEI] Acquiring...");
            TelephonyManager imeiNo = (TelephonyManager)mactivity.GetSystemService(Context.TelephonyService);

            Permission permissionChecking = ContextCompat.CheckSelfPermission(mactivity.ApplicationContext, Android.Manifest.Permission.ReadPhoneState);

            string[] Permissive = { Manifest.Permission.ReadPhoneState };

            if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
            {
                var rationale = mactivity.ShouldShowRequestPermissionRationale(Manifest.Permission.ReadPhoneState);

                if (rationale)
                {
                    System.Diagnostics.Debug.WriteLine("[IMEI] IMEI Permission not granted. Retrying request...");

                    AlertDialog.Builder alert = new AlertDialog.Builder(mactivity)
                                                .SetTitle("Penerangan")
                                                .SetMessage("Khije memerlukan sedikit maklumat telefon anda untuk membolehkan urusan masuk dan keluar rekod anda.")
                                                .SetPositiveButton("OK", (sender, e) => {
                        mactivity.RequestPermissions(Permissive, 0);
                    });
                    alert.Show();
                }

                /*
                 * else if(!rationale)
                 * {
                 *  System.Diagnostics.Debug.WriteLine("[IMEI] IMEI Permission not granted permanently.");
                 *
                 *  AlertDialog.Builder alert = new AlertDialog.Builder(mactivity)
                 *              .SetTitle("Penerangan")
                 *              .SetMessage("Anda telah memilih untuk tidak membenarkan Khije mendapatkan sedikit maklumat telefon anda. Ini menyebabkan Khije gagal mendapatkan akses log masuk. Sila hubungi [email protected] untuk maklumat lanjut.")
                 *              .SetPositiveButton("OK", (sender, e) => {
                 *
                 *              });
                 *  alert.Show();
                 *
                 * }
                 */
                else
                {
                    System.Diagnostics.Debug.WriteLine("[IMEI] IMEI Permission not granted. Requesting...");
                    mactivity.RequestPermissions(Permissive, 0);
                }
            }

            // final gateway
            if (permissionChecking != (int)Permission.Granted)
            {
                System.Diagnostics.Debug.WriteLine("[IMEI] IMEI Permission not granted.");

                return("IMEI_PERMISSION_DENIED");
            }
            else
            {
                if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
                {
                    System.Diagnostics.Debug.WriteLine("[IMEI] Is more than jellybean...");

                    return(imeiNo.Imei);
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("[IMEI] Below than jellybean...");
                    try
                    {
                        System.Diagnostics.Debug.WriteLine($"[IMEI] From Device ID {imeiNo.DeviceId}...");
                        return(imeiNo.DeviceId);
                    }
                    catch (Java.Lang.Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine($"[IMEI] From Serial {Android.OS.Build.Serial}...");
                        return(Android.OS.Build.Serial);
                    }
                }
            }
        }
コード例 #2
0
        protected async override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            //Pregunta por permisos de camera
            await TryToGetPermissions();

            //Se configura el logueo de errores
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;

            //Se registra el reporte de errores de hockeyapp
            HockeyApp.Android.CrashManager.Register(this, "ded4af869e434fc3a04cdf3269d86680");
            HockeyApp.Android.Metrics.MetricsManager.Register(this, Application, "ded4af869e434fc3a04cdf3269d86680");

            MessagingCenter.Subscribe <StartLongRunningTaskMessage>(this, "StartLongRunningTaskMessage", message => {
                var intent = new Intent(this, typeof(LongRunningTaskService));
                StartService(intent);
            });

            DisplayCrashReport();

            MessagingCenter.Subscribe <StopLongRunningTaskMessage>(this, "StopLongRunningTaskMessage", message => {
                var intent = new Intent(this, typeof(LongRunningTaskService));
                StopService(intent);
            });

            // Start the location service:
            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) == (int)Permission.Granted)
            {
                Log.Debug(TAG, "User already has granted permission.");
                AppLS.StartLocationService();
            }
            //else {
            //    Log.Debug(TAG, "Have to request permission from the user. ");
            //    RequestLocationPermission();
            //}

            //Notification Opened Delegate
            Com.OneSignal.OneSignal.NotificationOpened exampleNotificationOpenedDelegate = delegate(string message, System.Collections.Generic.Dictionary <string, object> additionalData, bool isActive) {
                try {
                    System.Console.WriteLine("OneSignal Notification opened:\nMessage: {0}", message);

                    if (additionalData != null)
                    {
                        if (additionalData.ContainsKey("customKey"))
                        {
                            System.Console.WriteLine("customKey: {0}", additionalData["customKey"]);
                        }

                        System.Console.WriteLine("additionalData: {0}", additionalData);
                    }
                } catch (System.Exception e) {
                    System.Console.WriteLine(e.StackTrace);
                }
            };



            global::Xamarin.Forms.Forms.Init(this, bundle);
            DevExpress.Mobile.Forms.Init();
            Com.OneSignal.OneSignal.Init();
            LoadApplication(new App());

            var container = new SimpleContainer();

            container.Register <IDevice>(t => AndroidDevice.CurrentDevice);
            container.Register <IDisplay>(t => t.Resolve <IDevice>().Display);
            container.Register <INetwork>(t => t.Resolve <IDevice>().Network);

            //20191007 - Se comenta para que no salga notificacion de gps siempre
            //No estaba incluido en version anteror
            //StartService(new Intent(this, typeof(GPSService)));
            //// register GPS Service
            //RegisterService();
        }
コード例 #3
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            RequestedOrientation = ScreenOrientation.Portrait;
            Context        applicationContext     = Application.Context;
            AppPreferences applicationPreferences = new AppPreferences(applicationContext);

            // Check application Preferences have been saved previously if not open Settings Activity and wait there.
            if (
                string.IsNullOrEmpty(applicationPreferences.GetAccessKey("submitDataUrl")) ||
                string.IsNullOrEmpty(applicationPreferences.GetAccessKey("loadConfigUrl")) ||
                string.IsNullOrEmpty(applicationPreferences.GetAccessKey("applicationKey")) ||
                string.IsNullOrEmpty(applicationPreferences.GetAccessKey("retentionPeriod"))
                )
            {
                // No, well start the setting activity
                StartActivity(typeof(SettingsActivity));
            }
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_main);
            Android.Support.V7.Widget.Toolbar toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);
            // We only want to create a batch number here once when the app first starts and not everytime the activity loads
            if (batch == Guid.Empty)
            {
                SetBatchNumber(false);
            }
            databasePath = System.IO.Path.Combine(
                System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
                "localscandata.db3");
            databaseConnection = new SQLiteConnection(databasePath);
            // Create the ParcelScans table
            databaseConnection.CreateTable <DespatchBayExpressDataBase.ParcelScans>();
            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) == (int)Permission.Granted)
            {
                mediaPlayer = MediaPlayer.Create(this, Resource.Raw.beep_07);
                TrackingNumberDataProvider();

                // We have permission, go ahead and use the GPS.
                Log.Debug("GPS", "We have permission, go ahead and use the GPS.");
                InitializeLocationManager();

                coordinates = FindViewById <TextView>(Resource.Id.footer_text);


                TrackingScan = FindViewById <EditText>(Resource.Id.txtentry);

                TrackingScan.Text = "";
                TrackingScan.RequestFocus();

                TrackingScan.KeyPress += (object sender, View.KeyEventArgs e) =>
                {
                    if ((e.Event.Action == KeyEventActions.Down) && (e.KeyCode == Keycode.Enter))
                    {
                        if (e.Event.RepeatCount == 0)
                        {
                            /// need to regex the scan against the Tracking Patterns
                            ///
                            TableQuery <TrackingNumberPatterns> trackingPatterns = databaseConnection.Table <TrackingNumberPatterns>();

                            bool patternFound = false;
                            try
                            {
                                foreach (var trackingPattern in trackingPatterns)
                                {
                                    Match m = Regex.Match(@TrackingScan.Text, @trackingPattern.Pattern, RegexOptions.IgnoreCase);
                                    if (m.Success)
                                    {
                                        patternFound = true;
                                    }
                                }
                            }
                            catch { }

                            if (patternFound)
                            {
                                var newScan = new DespatchBayExpressDataBase.ParcelScans
                                {
                                    TrackingNumber = TrackingScan.Text.ToUpper(),
                                    ScanTime       = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss"),
                                    Batch          = batchnumber,
                                    Sent           = null
                                };
                                try
                                {
                                    newScan.Longitude = currentLocation.Longitude;
                                }
                                catch
                                {
                                    newScan.Longitude = null;
                                }
                                try
                                {
                                    newScan.Latitude = currentLocation.Latitude;
                                }
                                catch
                                {
                                    newScan.Latitude = null;
                                }
                                try
                                {
                                    databaseConnection.Insert(newScan);
                                    mBarcodeScannerList.FetchUnCollected();
                                    mAdapter.NotifyDataSetChanged();
                                    mRecyclerView.RefreshDrawableState();
                                    mediaPlayer.Start();
                                }
                                catch (SQLiteException ex)
                                {
                                    Toast.MakeText(this, "Scan Error : Duplicated Barcode Scan", ToastLength.Long).Show();
                                    Log.Info("SCANNER", "Scan Error : " + ex.Message);
                                }
                            }
                            else
                            {
                                Toast.MakeText(this, "Barcode format not recognised", ToastLength.Short).Show();
                            }

                            TrackingScan.RequestFocus();
                            TrackingScan.Text = "";
                        }
                    }
                };
            }
            else
            {
                // GPS permission is not granted. If necessary display rationale & request.
                Log.Debug("GPS", "GPS permission is not granted");

                if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessFineLocation))
                {
                    // Provide an additional rationale to the user if the permission was not granted
                    // and the user would benefit from additional context for the use of the permission.
                    // For example if the user has previously denied the permission.
                    Log.Info("GPS", "Displaying GPS permission rationale to provide additional context.");
                    var rootView = FindViewById <CoordinatorLayout>(Resource.Id.root_view);


                    var requiredPermissions = new String[] { Manifest.Permission.AccessFineLocation };
                    ActivityCompat.RequestPermissions(this, requiredPermissions, REQUEST_LOCATION);
                }
                else
                {
                    ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.AccessFineLocation }, REQUEST_LOCATION);
                }
            }
        }
コード例 #4
0
        private async void InitTwilioCall()
        {
            try
            {
                bool granted =
                    ContextCompat.CheckSelfPermission(ApplicationContext, Manifest.Permission.Camera) ==
                    Permission.Granted &&
                    ContextCompat.CheckSelfPermission(ApplicationContext, Manifest.Permission.RecordAudio) ==
                    Permission.Granted;

                CheckVideoCallPermissions(granted);

                UserId = Intent?.GetStringExtra("UserID");
                Avatar = Intent?.GetStringExtra("avatar");
                Name   = Intent?.GetStringExtra("name");

                var dataCallId = Intent?.GetStringExtra("CallID") ?? "Data not available";
                if (dataCallId != "Data not available" && !string.IsNullOrEmpty(dataCallId))
                {
                    CallId = dataCallId;

                    TwilioAccessToken      = Intent?.GetStringExtra("access_token");
                    TwilioAccessTokenUser2 = Intent?.GetStringExtra("access_token_2");
                    FromId   = Intent?.GetStringExtra("from_id");
                    Active   = Intent?.GetStringExtra("active");
                    Time     = Intent?.GetStringExtra("time");
                    Status   = Intent?.GetStringExtra("status");
                    RoomName = Intent?.GetStringExtra("room_name");
                    CallType = Intent?.GetStringExtra("type");
                }

                switch (CallType)
                {
                case "Twilio_video_call":
                {
                    if (!string.IsNullOrEmpty(TwilioAccessToken))
                    {
                        if (!string.IsNullOrEmpty(UserId))
                        {
                            Load_userWhenCall();
                        }

                        TwilioVideo = TwilioVideoHelper.GetOrCreate(this, TypeCall.Video);
                        UpdateState();
                        NoteTextView.Text = GetText(Resource.String.Lbl_Waiting_for_answer);

                        var(apiStatus, respond) = await RequestsAsync.Call.AnswerCallAsync(UserDetails.UserId, CallId, TypeCall.Video);

                        if (apiStatus == 200)
                        {
                            ConnectToRoom();

                            var ckd = GlobalContext?.LastCallsTab?.MAdapter?.MCallUser?.FirstOrDefault(a => a.Id == CallId);         // id >> Call_Id
                            if (ckd == null)
                            {
                                Classes.CallUser cv = new Classes.CallUser
                                {
                                    Id        = CallId,
                                    UserId    = UserId,
                                    Avatar    = Avatar,
                                    Name      = Name,
                                    FromId    = FromId,
                                    Active    = Active,
                                    Time      = "Answered call",
                                    Status    = Status,
                                    RoomName  = RoomName,
                                    Type      = CallType,
                                    TypeIcon  = "Accept",
                                    TypeColor = "#008000"
                                };

                                GlobalContext?.LastCallsTab?.MAdapter?.Insert(cv);

                                SqLiteDatabase dbDatabase = new SqLiteDatabase();
                                dbDatabase.Insert_CallUser(cv);
                            }
                        }
                        //else Methods.DisplayReportResult(this, respond);
                    }

                    break;
                }

                case "Twilio_video_calling_start":
                    NoteTextView.Text = GetText(Resource.String.Lbl_Calling_video);
                    TwilioVideo       = TwilioVideoHelper.GetOrCreate(this, TypeCall.Video);

                    Methods.AudioRecorderAndPlayer.PlayAudioFromAsset("mystic_call.mp3", "left");

                    StartApiService();

                    UpdateState();
                    break;
                }
            }
            catch (Exception e)
            {
                Methods.DisplayReportResultTrack(e);
            }
        }
コード例 #5
0
 public bool IsPermissionGranted(string[] permissionsIds)
 {
     return(permissionsIds.All(x =>
                               ContextCompat.CheckSelfPermission(Singleton.GetService <ICurrentContext>().Context, x)
                               == Android.Content.PM.Permission.Granted));
 }
コード例 #6
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.TestSelection);
            pref   = GetSharedPreferences("login", FileCreationMode.Private);
            edit   = pref.Edit();
            banned = pref.GetBoolean("banned", false);


            //if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted)
            //{
            //    if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.WriteExternalStorage))
            //    {

            //    }
            //    else
            //    {
            //        ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.WriteExternalStorage }, 101);
            //    }
            //}
            //if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted)
            //{
            //    if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.ReadExternalStorage))
            //    {

            //    }
            //    else
            //    {
            //        ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.ReadExternalStorage }, 102);
            //    }
            //}


            Utility.intalizejson();
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Converters       = { new StringEnumConverter() }
            };

            toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);
            //For showing back button
            SupportActionBar.SetDisplayHomeAsUpEnabled(true);
            SupportActionBar.SetHomeButtonEnabled(true);
            toolbar.SetTitle(Resource.String.MyRequest);
            mRecycleView   = FindViewById <RecyclerView>(Resource.Id.mytestselectionlist);
            mLayoutManager = new GridLayoutManager(this, 3);
            mRecycleView.SetLayoutManager(mLayoutManager);
            cp = new CustomProgressDialog(this);
            cp.SetCancelable(false);
            cp.Show();

            if (Utility.IsNetworkConnected(this))
            {
                Callapi();
            }
            else
            {
                cp.Dismiss();
                Toast.MakeText(this, "Check your internet connection", ToastLength.Short).Show();
            }

            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted)
            {
                if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.WriteExternalStorage))
                {
                }
                else
                {
                    ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.WriteExternalStorage }, 101);
                }
            }
            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) != (int)Permission.Granted)
            {
                if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.ReadExternalStorage))
                {
                }
                else
                {
                    ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.ReadExternalStorage }, 102);
                }
            }

            // Create your application here
        }
コード例 #7
0
 private bool CheckPermissionLibrary()
 {
     if ((ContextCompat.CheckSelfPermission(ApplicationContext, Manifest.Permission.WriteExternalStorage) != Permission.Granted) && (ContextCompat.CheckSelfPermission(ApplicationContext, Manifest.Permission.ReadExternalStorage) != Permission.Granted))
     {
         return(false);
     }
     else
     {
         return(true);
     }
 }
コード例 #8
0
 public Permission CheckPermission(string permission)
 => ContextCompat.CheckSelfPermission(this, permission);
コード例 #9
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);
            //    Download("Songs", null);
            // Set Status Bar Color
            Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);
            // Window.SetStatusBarColor(Android.Graphics.Color.Black);
            notificationManager = NotificationManagerCompat.From(this);



            mediaSession = new MediaSessionCompat(this, "tag");

            // CarouselViewRenderer.();

            CachedImageRenderer.Init(true);
            //  RegisterReceiver(savedInstanceState, new IntentFilter("com.companyname.IncomingCall"));

            //// FFImageLoading
            //CachedImageRenderer.Init();

            //// AudioService setup
            Instance = this;
            System.Threading.Tasks.Task.Run(() =>
            {
                Intent AudioServiceIntent = new Intent(this, typeof(AudioService));
                this.StartService(AudioServiceIntent);
                _connection = new AudioServiceConnection(this);
                bool binded = BindService(AudioServiceIntent, _connection, Bind.AutoCreate);
            });


            Xamarin.Essentials.Platform.Init(this, savedInstanceState);

            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this, savedInstanceState);

            //// FlowListView
            FlowListView.Init();

            Rg.Plugins.Popup.Popup.Init(this, savedInstanceState);

            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) != Permission.Granted || ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadPhoneState) != Permission.Granted)
            {
                // We have permission, go ahead and use the camera.
                if (ActivityCompat.ShouldShowRequestPermissionRationale(activity: this, Manifest.Permission.ReadExternalStorage) ||
                    ActivityCompat.ShouldShowRequestPermissionRationale(activity: this, Manifest.Permission.ReadPhoneState))
                {
                    ActivityCompat.RequestPermissions(activity: this, new String[] { Manifest.Permission.ReadExternalStorage, Manifest.Permission.WriteExternalStorage, Manifest.Permission.ReadPhoneState }, STORAGE_PERMISSION_CODE);
                }

                else
                {
                    ActivityCompat.RequestPermissions(activity: this, new String[] { Manifest.Permission.ReadExternalStorage, Manifest.Permission.WriteExternalStorage, Manifest.Permission.ReadPhoneState }, STORAGE_PERMISSION_CODE);
                }
            }
            else
            {
                if (ActivityCompat.ShouldShowRequestPermissionRationale(activity: this, Manifest.Permission.ReadExternalStorage) ||
                    ActivityCompat.ShouldShowRequestPermissionRationale(activity: this, Manifest.Permission.ReadPhoneState))
                {
                    ActivityCompat.RequestPermissions(activity: this, new String[] { Manifest.Permission.ReadExternalStorage, Manifest.Permission.WriteExternalStorage, Manifest.Permission.ReadExternalStorage }, STORAGE_PERMISSION_CODE);
                }
                else
                {
                    ActivityCompat.RequestPermissions(activity: this, new String[] { Manifest.Permission.ReadExternalStorage, Manifest.Permission.ReadPhoneState }, STORAGE_PERMISSION_CODE);
                }
            }
            LoadApplication(new App());
        }
コード例 #10
0
        public bool CheckPermission(Android.Content.Context context)
        {
            bool permission = (ContextCompat.CheckSelfPermission(context, Manifest.Permission.WriteExternalStorage) == (int)Permission.Granted);

            return(permission);
        }
コード例 #11
0
 public Task <bool> HasLocationPrivileges()
 {
     return(Task.FromResult(ContextCompat.CheckSelfPermission(_locationProvider.ApplicationContext, Manifest.Permission.AccessFineLocation) == Permission.Granted));
 }
コード例 #12
0
 public bool HasPermissions(Context context)
 {
     return(ContextCompat.CheckSelfPermission(context, Manifest.Permission.AccessFineLocation) == Permission.Granted);
 }
コード例 #13
0
        /// <summary>
        /// This will check to see if the current Context has been granted the custom permission to use the
        /// TachoSerice
        /// </summary>
        /// <returns><c>true</c>, if the current app has been granted permission to use the TachoService, <c>false</c> otherwise.</returns>
        /// <param name="context">Context.</param>
        private bool HasPermissionToRunTachoService()
        {
            Permission permissionCheck = ContextCompat.CheckSelfPermission(Application.Context.ApplicationContext, Constants.TachoService_Permission);

            return(permissionCheck == Permission.Granted);
        }
コード例 #14
0
        /// <summary>
        /// 位置情報の利用が許可されているのか確認します。
        /// </summary>
        /// <returns><c>true</c>, if permissions was checked, <c>false</c> otherwise.</returns>
        bool CheckLocationPermissions()
        {
            var permissionState = ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation);

            return(permissionState == (int)Permission.Granted);
        }
コード例 #15
0
 private bool AllPermissionsGranted()
 {
     return(ContextCompat.CheckSelfPermission(this, Manifest.Permission.Camera) == Permission.Granted);
 }
コード例 #16
0
        private async Task <bool> UpdateLocation()
        {
            bool locationChanged = false;

            if (Settings.FollowGPS && (location == null || location.locationType == LocationType.GPS))
            {
                if (AppCompatActivity != null && ContextCompat.CheckSelfPermission(AppCompatActivity, Manifest.Permission.AccessFineLocation) != Permission.Granted &&
                    ContextCompat.CheckSelfPermission(AppCompatActivity, Manifest.Permission.AccessCoarseLocation) != Permission.Granted)
                {
                    ActivityCompat.RequestPermissions(AppCompatActivity, new String[] { Manifest.Permission.AccessCoarseLocation, Manifest.Permission.AccessFineLocation },
                                                      PERMISSION_LOCATION_REQUEST_CODE);
                    return(false);
                }

                LocationManager locMan       = AppCompatActivity?.GetSystemService(Context.LocationService) as LocationManager;
                bool            isGPSEnabled = (bool)locMan?.IsProviderEnabled(LocationManager.GpsProvider);
                bool            isNetEnabled = (bool)locMan?.IsProviderEnabled(LocationManager.NetworkProvider);

                Android.Locations.Location location = null;

                if (isGPSEnabled || isNetEnabled)
                {
                    Criteria locCriteria = new Criteria()
                    {
                        Accuracy = Accuracy.Coarse, CostAllowed = false, PowerRequirement = Power.Low
                    };
                    string provider = locMan.GetBestProvider(locCriteria, true);
                    location = locMan.GetLastKnownLocation(provider);

                    if (location == null)
                    {
                        locMan.RequestSingleUpdate(provider, mLocListnr, null);
                    }
                    else
                    {
                        LocationData lastGPSLocData = await Settings.GetLastGPSLocData();

                        // Check previous location difference
                        if (lastGPSLocData.query != null &&
                            mLocation != null && ConversionMethods.CalculateGeopositionDistance(mLocation, location) < 1600)
                        {
                            return(false);
                        }

                        if (lastGPSLocData.query != null &&
                            Math.Abs(ConversionMethods.CalculateHaversine(lastGPSLocData.latitude, lastGPSLocData.longitude,
                                                                          location.Latitude, location.Longitude)) < 1600)
                        {
                            return(false);
                        }

                        LocationQueryViewModel view = null;

                        await Task.Run(async() =>
                        {
                            view = await wm.GetLocation(location);

                            if (String.IsNullOrEmpty(view.LocationQuery))
                            {
                                view = new LocationQueryViewModel();
                            }
                        });

                        if (String.IsNullOrWhiteSpace(view.LocationQuery))
                        {
                            // Stop since there is no valid query
                            return(false);
                        }

                        // Save oldkey
                        string oldkey = lastGPSLocData.query;

                        // Save location as last known
                        lastGPSLocData.SetData(view, location);
                        Settings.SaveLastGPSLocData(lastGPSLocData);

                        App.Context.StartService(
                            new Intent(App.Context, typeof(WearableDataListenerService))
                            .SetAction(WearableDataListenerService.ACTION_SENDLOCATIONUPDATE));

                        this.location = lastGPSLocData;
                        mLocation     = location;

                        // Update widget ids for location
                        if (oldkey != null && WidgetUtils.Exists(oldkey))
                        {
                            WidgetUtils.UpdateWidgetIds(oldkey, lastGPSLocData);
                        }

                        locationChanged = true;
                    }
                }
                else
                {
                    AppCompatActivity?.RunOnUiThread(() =>
                    {
                        Toast.MakeText(AppCompatActivity, Resource.String.error_retrieve_location, ToastLength.Short).Show();
                    });
                }
            }

            return(locationChanged);
        }
コード例 #17
0
        public AccessState GetCurrentAccessState(string androidPermission)
        {
            var result = ContextCompat.CheckSelfPermission(this.AppContext, androidPermission);

            return(result == Permission.Granted ? AccessState.Available : AccessState.Denied);
        }
コード例 #18
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            first  = inflater.Inflate(Resource.Layout.NewPost, null);
            second = inflater.Inflate(Resource.Layout.NewPost2, null);

            userId = new UserSettings(this.Activity).getUserID();

            if (!activeSecond)
            {
                if (ContextCompat.CheckSelfPermission(this.Activity, Manifest.Permission.ReadExternalStorage) == (int)Permission.Granted)
                {
                    addViewModel = new AddViewModel();

                    ImageButton takePctrBtn  = first.FindViewById <ImageButton>(Resource.Id.takePictureBtn);
                    ImageButton chooseFewBtn = first.FindViewById <ImageButton>(Resource.Id.fewPictures);

                    takePctrBtn.Click  += (sender, e) => StartCameraActivity();
                    chooseFewBtn.Click += (sender, e) => ShowCheckCircles();

                    recView = first.FindViewById <AndroidX.RecyclerView.Widget.RecyclerView>(Resource.Id.recView);

                    var galleryPhotos = getPhotosFromGallery();

                    var imgAdapter = new ImageShortCutAdapter(this.Activity, galleryPhotos);

                    var grid = new AndroidX.RecyclerView.Widget.GridLayoutManager(this.Activity, 3);

                    recView.HasFixedSize = true;
                    recView.SetLayoutManager(grid);
                    recView.SetAdapter(imgAdapter);

                    imgAdapter.ItemClick += (sender, e) =>
                    {
                        int position = e;

                        if (imgAdapter.fewSelectActive)
                        {
                            var view = recView.GetChildAt(position);
                            var vh   = recView.FindViewHolderForLayoutPosition(position);

                            if (view == null)
                            {
                                view = vh.ItemView;
                            }

                            if (!imgAdapter.CheckedPositions.Contains(position))
                            {
                                if (imgAdapter.CheckedPositions.Count >= 10)
                                {
                                    Toast.MakeText(this.Activity, "You could clip up to 10 photos", ToastLength.Short).Show();
                                }
                                else
                                {
                                    imgAdapter.CheckedPositions.Add(position);
                                }
                            }
                            else
                            {
                                imgAdapter.CheckedPositions.Remove(position);
                            }
                            imgAdapter.BindViewHolder(vh, position);
                        }
                        else
                        {
                            SelectedImgsFromGallery(new List <string>()
                            {
                                galleryPhotos[position]
                            });
                        }
                    };
                }
                else
                {
                    ActivityCompat.RequestPermissions(this.Activity, new string[] { Manifest.Permission.ReadExternalStorage }, 200);
                    OnCreateView(inflater, container, savedInstanceState);
                }

                return(first);
            }
            else
            {
                return(second);
            }
        }
コード例 #19
0
        private async void BotonCifrar_Click(object sender, System.EventArgs e)
        {
            if (campoContrasena.Text.Length < 8)
            {
                Toast.MakeText(this, "La contraseña debe tener una longitud mínima de 8 caracteres", ToastLength.Long).Show();
            }
            else if (adaptador.archivos.Count > 0)
            {
                if (ContextCompat.CheckSelfPermission(this, PermisosAlmacenamiento[0]) == (int)Permission.Granted && ContextCompat.CheckSelfPermission(this, PermisosAlmacenamiento[1]) == (int)Permission.Granted)
                {
                    string contrasena  = campoContrasena.Text;
                    byte[] keyMaterial = Crypto.DerivarClaveDeContrasena(contrasena, 256);
                    bool   eliminarArchivosOriginales = await ConfirmarEliminacionArchivos();
                    await CifrarArchivos(keyMaterial, eliminarArchivosOriginales);

                    Toast.MakeText(this, "Tarea completada", ToastLength.Long).Show();
                    adaptador.LimpiarLista();
                    campoContrasena.Text = "";
                }
                else if (ActivityCompat.ShouldShowRequestPermissionRationale(this, PermisosAlmacenamiento[0]) || ActivityCompat.ShouldShowRequestPermissionRationale(this, PermisosAlmacenamiento[1]))
                {
                    ActivityCompat.RequestPermissions(this, PermisosAlmacenamiento, 0);
                }
            }
            else
            {
                Toast.MakeText(this, "Actualmente no hay archivos en la lista", ToastLength.Long).Show();
            }
        }
 public bool CheckPermissionsToWriteExternalStorage()
 {
     return(ContextCompat.CheckSelfPermission(activity, Android.Manifest.Permission.WriteExternalStorage) == Android.Content.PM.Permission.Granted);
 }
コード例 #21
0
 /// <summary>
 /// Validate if a given permission was granted to the app but not request it to the user
 /// <remarks>
 /// This should not be invoked directly from the application code.
 /// You should use the extension methods in <see cref="PermissionsServiceExtensions"/>.
 /// </remarks>
 /// </summary>
 /// <param name="ct">Cancellation Token</param>
 /// <param name="permissionIdentifier">A permission identifier defined in Manifest.Permission.</param>
 /// <returns>A <see cref="Task"/> representing the asynchronous operation</returns>
 public static async Task <bool> CheckPermission(CancellationToken ct, string permissionIdentifier)
 => ContextCompat.CheckSelfPermission(BaseActivity.Current, permissionIdentifier) == Permission.Granted;
コード例 #22
0
 //проверка наличия разрешения на доступ к памяти смартфона
 private void CheckPermissionForStorage()
 {
     try
     {
         if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) == (int)Permission.Granted && ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) == (int)Permission.Granted)
         {
             HasPermissionToReadWriteExternalStorage = true;
         }
         else
         {
             var requestPermission = new string[] { Manifest.Permission.WriteExternalStorage, Manifest.Permission.ReadExternalStorage };
             ActivityCompat.RequestPermissions(this, requestPermission, REQUEST_STORAGE);
         }
     }
     catch (Exception er)
     {
         Log.Logger.Error("CheckPermissionForStorage", er.Message);
     }
 }
コード例 #23
0
 public static Permission CheckPermission(Context context, string permission)
 {
     return(ContextCompat.CheckSelfPermission(context, permission));
 }
コード例 #24
0
 public Permission CheckPermission(string permission)
 => ContextCompat.CheckSelfPermission(Activity, permission);
コード例 #25
0
ファイル: MainActivity.cs プロジェクト: wade1990/NmeaParser
        private async void Start()
        {
            startButton.Enabled = false;
            status = FindViewById <TextView>(Resource.Id.output);
            var devicePicker = FindViewById <Spinner>(Resource.Id.device_picker);
            var id           = devicePicker.SelectedItem.ToString();
            var btAddress    = devices[id];

            if (btAddress == null)
            {
                if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) != Permission.Granted)
                {
                    ActivityCompat.RequestPermissions(this, new[] { Manifest.Permission.AccessFineLocation }, 1000);
                    return;
                }
                if (launched)
                {
                    return;
                }

                launched = true;
                listener = new NmeaParser.SystemNmeaDevice();
            }
            else //Bluetooth
            {
                try
                {
                    status.Text = "Opening bluetooth...";
                    var            adapter     = Android.Bluetooth.BluetoothAdapter.DefaultAdapter;
                    var            bt          = Android.Bluetooth.BluetoothAdapter.DefaultAdapter.GetRemoteDevice(btAddress);
                    Java.Util.UUID SERIAL_UUID = Java.Util.UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"); //UUID for Serial Device Service
                    socket = bt.CreateRfcommSocketToServiceRecord(SERIAL_UUID);
                    try
                    {
                        await socket.ConnectAsync();
                    }
                    catch (Java.IO.IOException)
                    {
                        // This sometimes fails. Use fallback approach to open socket
                        // Based on https://stackoverflow.com/a/41627149
                        socket.Dispose();
                        var m = bt.Class.GetMethod("createRfcommSocket", new Java.Lang.Class[] { Java.Lang.Integer.Type });
                        socket = m.Invoke(bt, new Java.Lang.Object[] { 1 }) as Android.Bluetooth.BluetoothSocket;
                        socket.Connect();
                    }
                    listener = new NmeaParser.StreamDevice(socket.InputStream);
                }
                catch (System.Exception ex)
                {
                    socket?.Dispose();
                    socket       = null;
                    status.Text += "\nError opening Bluetooth device:\n" + ex.Message;
                }
            }

            if (listener != null)
            {
                listener.MessageReceived += Listener_MessageReceived;
                status.Text += "\nOpening device...";
                await listener.OpenAsync();

                status.Text        += "\nConnected!";
                startButton.Enabled = !(stopButton.Enabled = true);
            }
            else
            {
                startButton.Enabled = !(stopButton.Enabled = false);
            }
        }
コード例 #26
0
        void ContinueInit()
        {
            var list = Application.Context.GetExternalFilesDirs(null);

            list.ForEach(a => Log.Info("MP", "External dir option: " + a.AbsolutePath));

            var list2 = Application.Context.GetExternalFilesDirs(Environment.DirectoryDownloads);

            list2.ForEach(a => Log.Info("MP", "External DirectoryDownloads option: " + a.AbsolutePath));

            var pref = this.GetSharedPreferences("pref", FileCreationMode.Private);


            Settings.CustomUserDataDirectory = Application.Context.GetExternalFilesDir(null).ToString();
            //pref.GetString("Directory", Application.Context.GetExternalFilesDir(null).ToString());
            Log.Info("MP", "Settings.CustomUserDataDirectory " + Settings.CustomUserDataDirectory);

            WinForms.BundledPath = Application.Context.ApplicationInfo.NativeLibraryDir;
            Log.Info("MP", "WinForms.BundledPath " + WinForms.BundledPath);

            Test.BlueToothDevice = new BTDevice();
            Test.UsbDevices      = new USBDevices();
            Test.Radio           = new Radio();
            Test.GPS             = new GPS();

            androidvideo = new AndroidVideo();
            //disable
            //androidvideo.Start();
            AndroidVideo.onNewImage += (e, o) =>
            {
                WinForms.SetHUDbg(o);
            };


            //ConfigFirmwareManifest.ExtraDeviceInfo

            /*
             * var intent = new global::Android.Content.Intent(Intent.ActionOpenDocumentTree);
             *
             * intent.AddFlags(ActivityFlags.GrantWriteUriPermission | ActivityFlags.GrantReadUriPermission);
             * intent.PutExtra(DocumentsContract.ExtraInitialUri, "Mission Planner");
             *
             * StartActivityForResult(intent, 1);
             */

            UserDialogs.Init(this);

            AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironment_UnhandledExceptionRaiser;

            {
                if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) !=
                    (int)Permission.Granted ||
                    ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) !=
                    (int)Permission.Granted ||
                    ContextCompat.CheckSelfPermission(this, Manifest.Permission.Bluetooth) !=
                    (int)Permission.Granted)
                {
                    ActivityCompat.RequestPermissions(this,
                                                      new String[]
                    {
                        Manifest.Permission.AccessFineLocation, Manifest.Permission.LocationHardware,
                        Manifest.Permission.WriteExternalStorage, Manifest.Permission.ReadExternalStorage,
                        Manifest.Permission.Bluetooth
                    }, 1);
                }

                while (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) !=
                       (int)Permission.Granted)
                {
                    Thread.Sleep(1000);
                    var text = "Checking Permissions - " + DateTime.Now.ToString("T");

                    DoToastMessage(text);
                }
            }

            try {
                // print some info
                var pm   = this.PackageManager;
                var name = this.PackageName;

                var pi = pm.GetPackageInfo(name, PackageInfoFlags.Activities);

                Console.WriteLine("pi.ApplicationInfo.DataDir " + pi?.ApplicationInfo?.DataDir);
                Console.WriteLine("pi.ApplicationInfo.NativeLibraryDir " + pi?.ApplicationInfo?.NativeLibraryDir);

                // api level 24 - android 7
                Console.WriteLine("pi.ApplicationInfo.DeviceProtectedDataDir " +
                                  pi?.ApplicationInfo?.DeviceProtectedDataDir);
            } catch {}


            {
                // clean start, see if it was an intent/usb attach
                //if (savedInstanceState == null)
                {
                    DoToastMessage("Init Saved State");
                    proxyIfUsbAttached(this.Intent);

                    Console.WriteLine(this.Intent?.Action);
                    Console.WriteLine(this.Intent?.Categories);
                    Console.WriteLine(this.Intent?.Data);
                    Console.WriteLine(this.Intent?.DataString);
                    Console.WriteLine(this.Intent?.Type);
                }
            }

            GC.Collect();
            Task.Run(() =>
            {
                var gdaldir = Settings.GetRunningDirectory() + "gdalimages";
                Directory.CreateDirectory(gdaldir);

                MissionPlanner.Utilities.GDAL.GDALBase = new GDAL.GDAL();

                GDAL.GDAL.ScanDirectory(gdaldir);

                GMap.NET.MapProviders.GMapProviders.List.Add(GDAL.GDALProvider.Instance);
            });


            DoToastMessage("Launch App");

            LoadApplication(new App());
        }
コード例 #27
0
 private bool HasPermission(string permission)
 {
     return(ContextCompat.CheckSelfPermission(
                CrossCurrentActivity.Current.Activity, permission) == Permission.Granted);
 }
コード例 #28
0
        //App Loading screen
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_main); SetTitle(Resource.String.app_name);
            AppCenter.Start("c8e96422-f89a-45cf-b331-0c3bc585ee00",
                            typeof(Analytics), typeof(Crashes));
            SetTheme(Resource.Style.AppTheme);
            SearchView search = FindViewById <SearchView>(Resource.Id.searchView1);

            search.SetImeOptions(Android.Views.InputMethods.ImeAction.Go);
            search.QueryTextSubmit += Search_QueryTextSubmit;
            string[] permissions = new string[2];
            permissions[0] = Manifest.Permission.WriteExternalStorage;
            permissions[1] = Manifest.Permission.ReadExternalStorage;

            // Set our view from the "main" layout resource

            Spinner spinner1 = FindViewById <Spinner>(Resource.Id.spinner1), spinner2 = FindViewById <Spinner>(Resource.Id.spinner2);

            //ActivityCompat.RequestPermissions(this, permissions, 1);

            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) == (int)Permission.Granted)
            {
                if (!File.Exists(dbPath))
                {
                    using (BinaryReader binreader = new BinaryReader(Android.App.Application.Context.Assets.Open(dbName)))
                    {
                        using (BinaryWriter binwriter = new BinaryWriter(new FileStream(dbPath, FileMode.Create)))
                        {
                            byte[] buffer = new byte[2048];
                            int    len    = 0;
                            while ((len = binreader.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                binwriter.Write(buffer, 0, len);
                            }
                        }
                    }
                }

                using (var conn = new SQLite.SQLiteConnection(dbPath))
                {
                    var cmd = new SQLite.SQLiteCommand(conn);
                    cmd.CommandText = "select * from DocumentType";
                    var docTypes = cmd.ExecuteQuery <DocumentType>();
                    cmd.CommandText = "select * from DocumentTitle";
                    var           r     = cmd.ExecuteQuery <DocumentTitle>();
                    List <string> items = new List <string>();
                    items.Add("All");
                    foreach (var item in docTypes)
                    {
                        items.Add(item.DocumentTypeName);
                    }
                    var adapter1 = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleSpinnerItem, items);
                    adapter1.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
                    spinner1.ItemSelected += Spinner1_ItemSelected;
                    spinner1.Adapter       = adapter1;

                    items = new List <string>();
                    foreach (var item in r)
                    {
                        items.Add(item.Title);
                    }
                    var adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleSpinnerItem, items);
                    adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
                    spinner2.ItemSelected += Spinner2_ItemSelected;
                    spinner2.Adapter       = adapter;
                    search.SetImeOptions(Android.Views.InputMethods.ImeAction.Go);
                    search.QueryTextSubmit += Search_QueryTextSubmit;
                    FindViewById(Resource.Id.helpButton).Click += delegate
                    {
                        SetContentView(Resource.Layout.main);
                        creedOpen = false; catechismOpen = false; confessionOpen = false; helpOpen = true;
                        // SetContentView(Resource.Layout.main);
                        FindViewById <TextView>(Resource.Id.appTitle).Text      = "Help Page";
                        FindViewById <TextView>(Resource.Id.searchByLabel).Text = GetString(Resource.String.catechism_help);
                        FindViewById <TextView>(Resource.Id.catechismPgh).Text  = "Hitting the No Answers Checkbox will remove answers from your search results, '\n"
                                                                                  + "thus affecting the overall search results on the page.\n"
                                                                                  + " Hit the No proofs checkbox to exclude proofs from the search results\n";
                        FindViewById <TextView>(Resource.Id.confessionHelp).Text = GetString(Resource.String.confession_help);
                        FindViewById <TextView>(Resource.Id.confessionPgh).Text  = GetString(Resource.String.confessionPgh);
                        FindViewById <TextView>(Resource.Id.creedHelp).Text      = "Creed Help:";
                        FindViewById <TextView>(Resource.Id.creedPgh).Text       = GetString(Resource.String.creedPgh);
                        FindViewById <TextView>(Resource.Id.otherStuff).Text     = "Other Stuff:";
                        FindViewById <TextView>(Resource.Id.otherPgh).Text       = GetString(Resource.String.other_pgh);
                        FindViewById <TextView>(Resource.Id.sourceTV).Text       = "All documents listed below are public domain, the websites below helped me with collecting them. \n A big thanks for inspiration for this app came from this website." +

                                                                                   "\n\nApostle's Creed: https://reformed.org/documents/apostles_creed.html " +
                                                                                   "\n1618 Belgic Confession: https://reformed.org/documents/BelgicConfession.html " +
                                                                                   "\n1646 Westminster Confession of Faith: https://reformed.org/documents/wcf_with_proofs/index.html" +
                                                                                   "\n1689 London Baptist Confession of Faith: https://reformed.org/documents/baptist_1689.html" +
                                                                                   "\n1658 Savoy Declaration of Faith and Order: https://reformed.org/documents/Savoy_Declaration/index.html" +
                                                                                   "\nWestminster Shorter Catechism: https://reformed.org/documents/wsc/index.html" +
                                                                                   " \nWestminster Larger Catechism: https://reformed.org/documents/wlc_w_proofs/index.html " +
                                                                                   "\nHeidelberg Catechism: https://reformed.org/documents/heidelberg.html " +
                                                                                   "\nNicean Creed: https://reformed.org/documents/nicene.html " +
                                                                                   "\nAthanasian Creed: https://reformed.org/documents/athanasian.html  ";

                        FindViewById(Resource.Id.floatingActionButton).Click += delegate { this.Recreate(); };
                    };
                }
            }
            else
            {
                ActivityCompat.RequestPermissions(this, permissions, 1); this.Recreate();
            }
            FindViewById <FloatingActionButton>(Resource.Id.searchFAB).Click += delegate { Search(FindViewById <SearchView>(Resource.Id.searchView1).Query); };
        }
コード例 #29
0
 private bool IsLocationPermissionEnabled()
 {
     return(ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) == Permission.Granted);
 }
コード例 #30
0
        // Public methods
        public async Task <bool> Initialize(Activity activity, Context context, BLECommandsParser.cmdTableDel_t action)
        {
            bool ret = false;

            try
            {
                g_activity = activity;
                g_context  = context;

                // Initialize bluetooth adapter
                BluetoothLowEnergyAdapter.Init(activity);

                // Obtain bluetooth adapter handler
                g_BLEAdapterObj = BluetoothLowEnergyAdapter.ObtainDefaultAdapter(context);

                // Enable BLE adapter in case it is disabled. Close application if user denie
                if (g_BLEAdapterObj.AdapterCanBeEnabled && g_BLEAdapterObj.CurrentState.IsDisabledOrDisabling())
                {
                    await g_BLEAdapterObj.EnableAdapter();

                    if (true == g_BLEAdapterObj.CurrentState.IsDisabledOrDisabling())
                    {
                        Library.CloseApplication(activity);
                    }
                }

                // Suscribe to receive BLE adapter state changes
                g_BLEAdapterObj_stateChangeObserver = OnBLEAdapter_StateChange;
                g_BLEAdapterObj.CurrentState.Subscribe(Observer.Create <EnabledDisabledState>(g_BLEAdapterObj_stateChangeObserver, null, null));

                // Suscribe to receive Location adapter state changes
                g_LocationAdapterStateChangeObserver = new OnLocationAdapterStateChange();
                activity.RegisterReceiver(g_LocationAdapterStateChangeObserver, new IntentFilter(LocationManager.ProvidersChangedAction));

                // Enable location service permissions. Needed to make BLE device scan
                Permission permissionCheck = ContextCompat.CheckSelfPermission(activity, Manifest.Permission.AccessFineLocation);

                if (permissionCheck != Permission.Granted)
                {
                    if (true == Android.Support.V4.App.ActivityCompat.ShouldShowRequestPermissionRationale(activity, Manifest.Permission.AccessFineLocation))
                    {
                        Toast.MakeText(activity, "The permission to get BLE location data is required", ToastLength.Short).Show();
                    }
                    else
                    {
                        activity.RequestPermissions(new String[] { Manifest.Permission.AccessCoarseLocation, Manifest.Permission.AccessCoarseLocation }, 1);
                    }
                }
                else
                {
                    Toast.MakeText(activity, "Location permissions already granted", ToastLength.Short).Show();
                }

                // Get Location Manager and check for GPS & Network location services. Ask user to enable them if needed
                LocationManager lm = (LocationManager)context.GetSystemService(Context.LocationService);

                if (!lm.IsProviderEnabled(LocationManager.GpsProvider) || !lm.IsProviderEnabled(LocationManager.NetworkProvider))
                {
                    EventHandler <DialogClickEventArgs> ButtonClickCb = OnLocationMsgButtonClick;

                    // Build the alert dialog
                    Android.Support.V7.App.AlertDialog.Builder builder = new Android.Support.V7.App.AlertDialog.Builder(activity);
                    builder.SetTitle("Location Services Not Active");
                    builder.SetMessage("Please enable Location Services and GPS");
                    builder.SetPositiveButton("OK", ButtonClickCb);

                    Dialog alertDialog = builder.Create();
                    alertDialog.SetCanceledOnTouchOutside(false);
                    alertDialog.Show();
                }

                // Initialize BLE Commands Parser
                g_BLECommandsParserObj = new BLECommandsParser();
                Library.cmdTable      += action;

                ret = true;
            }
            catch (Exception)
            {
            }

            return(ret);
        }