Esempio n. 1
0
        /// <summary>
        /// Gets the location compat async.
        /// </summary>
        /// <returns>The location compat async.</returns>
        async Task GetLocationCompatAsync()
        {
            const string permission = Manifest.Permission.AccessFineLocation;

            if (ContextCompat.CheckSelfPermission(this, permission) == (int)Permission.Granted)
            {
                return;
            }

            if (ActivityCompat.ShouldShowRequestPermissionRationale(this, permission))
            {
                var dialog = new Android.Support.V7.App.AlertDialog.Builder(this)
                             .SetTitle("Acción requerida")
                             .SetMessage("Esta aplicación necesita acceso a la localización del dispositivo")
                             .SetPositiveButton("Aceptar", (senderAlert, args) =>
                {
                    RequestPermissions(PermissionsLocation, RequestLocationId);
                })
                             .Show();
                return;
            }

            RequestPermissions(PermissionsLocation, RequestLocationId);
        }
Esempio n. 2
0
 public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
 {
     if (requestCode != 100)
     {
         foreach (var item in permissions)
         {
             if (ContextCompat.CheckSelfPermission(this, item) == Permission.Denied)
             {
                 if (ActivityCompat.ShouldShowRequestPermissionRationale(this, permissions[0]) || ActivityCompat.ShouldShowRequestPermissionRationale(this, permissions[1]))
                 {
                     Snackbar.Make(FindViewById <RelativeLayout>(Resource.Id.rl_main), "You need to grant permission to use awareness services.", Snackbar.LengthLong).SetAction("Ask again", v => RequestPermissions()).Show();
                 }
                 else
                 {
                     Toast.MakeText(this, "You need to grant location permissions in settings.", ToastLength.Long).Show();
                 }
             }
         }
     }
     else
     {
         base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
     }
 }
Esempio n. 3
0
        async Task GetLocationCompatAsync()
        {
            const string permission = Manifest.Permission.AccessFineLocation;

            if (ContextCompat.CheckSelfPermission(this, permission) == (int)Permission.Granted)
            {
                await GetLocationAsync();

                return;
            }

            if (ActivityCompat.ShouldShowRequestPermissionRationale(this, permission))
            {
                //Explain to the user why we need to read the contacts
                Snackbar.Make(layout, "Location access is required to show coffee shops nearby.",
                              Snackbar.LengthIndefinite)
                .SetAction("OK", v => RequestPermissions(PermissionsLocation, RequestLocationId))
                .Show();

                return;
            }

            RequestPermissions(PermissionsLocation, RequestLocationId);
        }
Esempio n. 4
0
        private void CheckPermissions()
        {
            if (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) == (int)Permission.Granted)
            {
                return;
            }

            if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.ReadExternalStorage))
            {
                Log.Info("MainActivity", "Displaying camera permission rationale to provide additional context.");
                var requiredPermissions = new String[] { Manifest.Permission.ReadExternalStorage };
                Snackbar.Make(Layout, "Permission message", Snackbar.LengthIndefinite).SetAction("OK",
                                                                                                 new Action <View>(delegate(View obj)
                {
                    ActivityCompat.RequestPermissions(this, requiredPermissions, 0);
                }
                                                                                                                   )
                                                                                                 ).Show();
            }
            else
            {
                ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.ReadExternalStorage }, 0);
            }
        }
        private void AskForLocationPermission()
        {
            // Only check if permission hasn't been granted yet.
            if (ContextCompat.CheckSelfPermission(this, LocationService) != Permission.Granted)
            {
                // The Fine location permission will be requested.
                var requiredPermissions = new[] { Manifest.Permission.AccessFineLocation };

                // Only prompt the user first if the system says to.
                if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessFineLocation))
                {
                    // A snackbar is a small notice that shows on the bottom of the view.
                    Snackbar.Make(_myMapView,
                                  "Location permission is needed to display location on the map.",
                                  Snackbar.LengthIndefinite)
                    .SetAction("OK",
                               delegate
                    {
                        // When the user presses 'OK', the system will show the standard permission dialog.
                        // Once the user has accepted or denied, OnRequestPermissionsResult is called with the result.
                        ActivityCompat.RequestPermissions(this, requiredPermissions, LocationPermissionRequestCode);
                    }
                               ).Show();
                }
                else
                {
                    // When the user presses 'OK', the system will show the standard permission dialog.
                    // Once the user has accepted or denied, OnRequestPermissionsResult is called with the result.
                    this.RequestPermissions(requiredPermissions, LocationPermissionRequestCode);
                }
            }
            else
            {
                HandleLocationReady();
            }
        }
Esempio n. 6
0
 public static void CheckGetPermission(string permission, Activity context, int requestId, string title, string message)
 {
     if (ContextCompat.CheckSelfPermission(context, permission) != Permission.Granted)
     {
         // Show an explanation of why it's needed if necessary
         if (ActivityCompat.ShouldShowRequestPermissionRationale(context, permission))
         {
             global::Android.Support.V7.App.AlertDialog dialog = new global::Android.Support.V7.App.AlertDialog.Builder(context)
                                                                 .SetTitle(title)
                                                                 .SetMessage(message)
                                                                 .SetPositiveButton("Got it", (s, e) =>
             {
                 ActivityCompat.RequestPermissions(context, new string[] { permission }, requestId);
             })
                                                                 .Create();
             dialog.Show();
         }
         else
         {
             // No explanation needed, just ask
             ActivityCompat.RequestPermissions(context, new string[] { permission }, requestId);
         }
     }
 }
Esempio n. 7
0
        /**
         * this is called after the ActivityCompat.requestPermissions() to get the result for the request permissions
         */

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
        {
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            switch (requestCode)
            {
            case UtilityClass.PERMISSION_ALL:
                if (grantResults.Length > 0 &&
                    grantResults[0] == (int)Android.Content.PM.Permission.Granted)
                {
                    permissionGranted = true;
                }
                else
                {
                    if (grantResults[0] != (int)Android.Content.PM.Permission.Granted)
                    {
                        if (!ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessFineLocation))
                        {
                            Toast.MakeText(this, "The app was not allowed some permissions, some of the app functionality might not work", ToastLength.Long).Show();
                        }
                    }
                }
                break;
            }
        }
Esempio n. 8
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            const int REQUEST_LOCATION = 1;

            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());

            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(TAG, "Displaying camera permission rationale to provide additional context.");

                var requiredPermissions = new String[] { Manifest.Permission.AccessFineLocation };
                Snackbar.Make(this.CurrentFocus,
                              "Möchte Berechtigung haben!",
                              Snackbar.LengthIndefinite)
                .SetAction("OK",
                           new Action <View>(delegate(View obj) {
                    ActivityCompat.RequestPermissions(this, requiredPermissions, REQUEST_LOCATION);
                }
                                             )
                           ).Show();
            }
            else
            {
                ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.Camera }, REQUEST_LOCATION);
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Request Permissions to android OS
        /// </summary>
        private void RequestReadWirtePermission()
        {
            Log.Info(this.Title.ToString(), "READWRITE permission has NOT been granted. Requesting permission.");

            if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.ReadExternalStorage))
            {
                // 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(this.Title.ToString(), "Displaying READWRITE permission rationale to provide additional context.");

                // Snackbar.Make(layout, "Contacts permissions are needed to demonstrate access",
                //  Snackbar.LengthIndefinite).SetAction("OK", new Action<View>(delegate (View obj) {
                //ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.ReadExternalStorage }, REQUEST_ReadExternalStorage);
                ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.WriteExternalStorage, Manifest.Permission.Camera }, REQUEST_WriteExternalStorage);
                //  })).Show();
            }
            else
            {
                // Camera permission has not been granted yet. Request it directly.
                //ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.ReadExternalStorage }, REQUEST_ReadExternalStorage);
                ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.WriteExternalStorage, Manifest.Permission.Camera }, REQUEST_WriteExternalStorage);
            }
        }
Esempio n. 10
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            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);

            listView = FindViewById <ListView>(Resource.Id.listView);

            listAdapter      = new ActivityListAdapter(this);
            listView.Adapter = listAdapter;

            //adapt height of listView so it fits.
            Util.SetListViewHeightBasedOnChildren(listView, this);

            listView.ItemClick -= ListView_ItemClick;
            listView.ItemClick += ListView_ItemClick;

            int REQUEST_CAMERA = 0;

            if (ContextCompat.CheckSelfPermission(this, Android.Manifest.Permission.Camera) != Permission.Granted)
            {
                // Should we show an explanation?
                if (!ActivityCompat.ShouldShowRequestPermissionRationale(this, Android.Manifest.Permission.Camera))
                {
                    // No explanation needed, we can request the permission.
                    ActivityCompat.RequestPermissions(this, new string[] { Android.Manifest.Permission.Camera }, REQUEST_CAMERA);
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Permission Granted!");
            }
        }
Esempio n. 11
0
 /// <summary>
 /// Check if you have arleady shown the reason why you need this permission.
 /// </summary>
 /// <param name="permission">Permission strings provided from the <see cref="Manifest.Permission"/> properties.</param>
 public bool ShouldShowRequestPermissionRationale(string permission)
 {
     return(ActivityCompat.ShouldShowRequestPermissionRationale(ThisActivity, permission));
 }
Esempio n. 12
0
        protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (resultCode == Result.Ok)
            {
                bm = (Bitmap)data.Extras.Get("data");
                cameraView.SetImageBitmap(bm);
                takePic.SetImageResource(Resource.Drawable.baseline_mail_outline_24);
                takePic.Tag = mailTag;
            }
            else
            {
                takePic.Tag = photoTag;
                cameraView.SetImageBitmap(null);
                cameraView.SetImageResource(Resource.Drawable.baseline_speaker_phone_24);
            }

            /*********** Obtain the location ***********/

            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) == (int)Permission.Granted)
            {
                // We have permission, go ahead and use the location.

                Location lastKnownLocation = locationManager.GetLastKnownLocation(locationProvider);

                if (lastKnownLocation != null)
                {
                    locationManager.RequestLocationUpdates(locationProvider, 5000, 2, this);
                    latitude  = lastKnownLocation.Latitude.ToString();
                    longitude = lastKnownLocation.Longitude.ToString();
                    t.Text    = "N: " + latitude + ", W: " + longitude;
                }
                else
                {
                    Toast.MakeText(this, "Couldn't get last know location", ToastLength.Long).Show();
                }
            }
            else
            {
                // Location permission is not granted. If necessary display rationale & request.
                if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessFineLocation))
                {
                    Log.Info("@string/log_debug_tag", "Displaying camera permission rationale to provide additional context.");

                    var requiredPermissions = new String[] { Manifest.Permission.AccessFineLocation };

                    try
                    {
                        Snackbar.Make(FindViewById <LinearLayout>(Resource.Id.linearLayout1), "Location access is required", Snackbar.LengthIndefinite).SetAction("OK", new Action <View>(delegate(View obj) {
                            ActivityCompat.RequestPermissions(this, requiredPermissions, REQUEST_LOCATION);
                        }
                                                                                                                                                                                          )
                                                                                                                                                                  ).Show();
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(this, "Location access is required", ToastLength.Long).Show();
                        Log.Debug("@string/log_debug_tag", ex.Message);
                    }
                }
                else
                {
                    ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.AccessFineLocation }, REQUEST_LOCATION);
                }
            }
        }
Esempio n. 13
0
        /*************** Camera ***************/


        private void TakeAPicture(object sender, EventArgs eventArgs)
        {
            string msg = string.Empty;
            int    result;
            Intent intent;

            switch (takePic.Tag.ToString())
            {
            case photoTag:

                intent = new Intent(MediaStore.ActionImageCapture);

                if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.Camera) == (int)Permission.Granted)
                {
                    // We have permission, go ahead and use the camera.

                    Intent i = new Intent(MediaStore.ActionImageCapture);
                    StartActivityForResult(i, 0);
                }
                else
                {
                    // Camera permission is not granted. If necessary display rationale & request.
                    if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.Camera))
                    {
                        // Provide an additional rationale to the user if the permission was not granted
                        Log.Info("TAG", "Displaying camera permission rationale to provide additional context.");

                        var requiredPermissions = new String[] { Manifest.Permission.Camera };
                        Snackbar.Make(FindViewById <LinearLayout>(Resource.Id.linearLayout1), "Camera access is required", Snackbar.LengthIndefinite).SetAction("OK",
                                                                                                                                                                new Action <View>(delegate(View obj) {
                            ActivityCompat.RequestPermissions(this, requiredPermissions, REQUEST_CAMERA);
                        }
                                                                                                                                                                                  )
                                                                                                                                                                ).Show();
                    }
                    else
                    {
                        ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.Camera }, REQUEST_CAMERA);
                    }
                }

                break;

            case mailTag:

                Android.App.AlertDialog.Builder dialog = new Android.App.AlertDialog.Builder(this);
                dialog.SetIcon(Resource.Drawable.baseline_mail_outline_24);
                dialog.SetTitle("Enviando...");
                dialog.SetMessage("Tu alerta se enviará por correo en breve.");
                dialog.SetNeutralButton("OK", NeutralAction);
                dialog.Show();

                Task.Factory.StartNew(() => {
                    try
                    {
                        number = mTelephonyMgr.Line1Number.ToString();
                    }
                    catch (Exception ex)
                    {
                        number = "The user rejected [READ_PHONE_STATE] permission";
                        Log.Debug("DEBUG", ex.Message);
                    }

                    SendEmail(bm, number);

                    result = lh.InsertLocation(number, float.Parse(latitude), float.Parse(longitude), DateTime.Now, out msg);

                    if (result > 0)
                    {
                        try
                        {
                            Snackbar.Make(linearLayout, "Se ha actualizado la base de datos", Snackbar.LengthIndefinite).SetAction("OK", (view) => { }).Show();
                        }
                        catch
                        {
                            Toast.MakeText(this, "Se ha actualizado la base de datos", ToastLength.Long).Show();
                        }
                    }
                    else
                    {
                        try
                        {
                            Snackbar.Make(linearLayout, "No se pudo conectar con la BD.", Snackbar.LengthIndefinite).SetAction("OK", (view) => { }).Show();
                        }
                        catch
                        {
                            Toast.MakeText(this, "No se pudo conectar con la BD.", ToastLength.Long).Show();
                        }
                    }
                });

                takePic.SetImageResource(Resource.Drawable.baseline_linked_camera_24);
                takePic.Tag = photoTag;
                cameraView.SetImageBitmap(null);
                cameraView.SetImageResource(Resource.Drawable.baseline_speaker_phone_24);

                break;

            case doneTag:
                break;
            }
        }
Esempio n. 14
0
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            BluetoothLowEnergyAdapter.InitActivity(this);
            UserDialogs.Init(this);
            Forms.Init(this, bundle);

            new Timer().Schedule(
                new TimerAction(
                    () =>
            {
                RunOnUiThread(
                    () =>
                {
                    if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.Bluetooth) !=
                        Permission.Granted)
                    {
                        if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.Bluetooth))
                        {
                            UserDialogs.Instance.Alert(
                                "Yes should show rationale for Bluetooth",
                                "ShouldShowRequestPermissionRationale");
                        }
                        else
                        {
                            Log.Info("Requesting permission for Bluetooth");
                            ActivityCompat.RequestPermissions(this, new[] { Manifest.Permission.Bluetooth }, 24112);
                        }
                    }
                    else
                    {
                        Log.Info("Already have permission for Bluetooth");
                    }

                    if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.BluetoothAdmin) !=
                        Permission.Granted)
                    {
                        if (ActivityCompat.ShouldShowRequestPermissionRationale(
                                this,
                                Manifest.Permission.BluetoothAdmin))
                        {
                            UserDialogs.Instance.Alert(
                                "Yes should show rationale for BluetoothAdmin",
                                "ShouldShowRequestPermissionRationale");
                        }
                        else
                        {
                            Log.Info("Requesting permission for BluetoothAdmin");
                            ActivityCompat.RequestPermissions(
                                this,
                                new[] { Manifest.Permission.BluetoothAdmin },
                                24113);
                        }
                    }
                    else
                    {
                        Log.Info("Already have permission for BluetoothAdmin");
                    }
                });
            }),
                12000);

            LoadApplication(new FormsApp(BluetoothLowEnergyAdapter.ObtainDefaultAdapter(ApplicationContext)));
        }
Esempio n. 15
0
 private void GetGpsAccess(Activity activity, View view)
 {
     if (ActivityCompat.ShouldShowRequestPermissionRationale(activity, Manifest.Permission.AccessCoarseLocation) || ActivityCompat.ShouldShowRequestPermissionRationale(activity, Manifest.Permission.AccessFineLocation))
     {
         var requiredPermissions = new String[] { Manifest.Permission.AccessCoarseLocation, Manifest.Permission.AccessFineLocation };
         Snackbar.Make(view,
                       Resource.String.permission_location_rationale,
                       Snackbar.LengthIndefinite)
         .SetAction(Resource.String.ok,
                    new Action <View>(delegate(View obj)
         {
             ActivityCompat.RequestPermissions(activity, requiredPermissions, 100);
         }
                                      )
                    ).Show();
     }
     else
     {
         ActivityCompat.RequestPermissions(activity, new String[] { Manifest.Permission.AccessCoarseLocation, Manifest.Permission.AccessFineLocation }, 100);
     }
 }
Esempio n. 16
0
 public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
 {
     if (requestCode == 1)
     {
         // Check if the only required permission has been granted
         if ((grantResults.Length == 2) && (grantResults[0] == Permission.Granted) && (grantResults[1] == Permission.Granted))
         {
             // Location permission has been granted, okay to retrieve the location of the device
             GetLastLocation();
         }
         else
         {
             //Location permission was NOT granted
             //DENY
             if (ActivityCompat.ShouldShowRequestPermissionRationale(this, permissions[0]) || ActivityCompat.ShouldShowRequestPermissionRationale(this, permissions[1]))
             {
                 Snackbar.Make(FindViewById <LinearLayout>(Resource.Id.mainLayout), "You need to grant permission to use location services.", Snackbar.LengthLong).SetAction("Ask again", v => RequestPermissions()).Show();
             }
             else //DENY & DON'T ASK AGAIN
             {
                 Toast.MakeText(this, "You need to grant location permissions in settings.", ToastLength.Long).Show();
             }
         }
     }
     else
     {
         base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
     }
 }
        public async Task <bool> CheckEventLocationPermission()
        {
            try
            {
                Activity        activity        = MainActivity.ThisActivity;
                LocationManager locationManager = (LocationManager)activity.GetSystemService(Context.LocationService);
                bool            isGPSEnabled    = locationManager.IsProviderEnabled(LocationManager.GpsProvider);

                //If Version greater than Marshallow need to give run time permission
                if (isGPSEnabled)
                {
                    if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
                    {
                        if (ContextCompat.CheckSelfPermission(activity, Manifest.Permission.AccessFineLocation) == (int)Permission.Granted)
                        {
                            // We have been given permission.
                            return(true);
                        }
                        else
                        {
                            // If necessary display rationale & request.
                            if (ActivityCompat.ShouldShowRequestPermissionRationale(activity, 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("Location", "Displaying Location permission rationale to provide additional context.");

                                var requiredPermissions = new String[] { Manifest.Permission.AccessFineLocation };
                                ActivityCompat.RequestPermissions(activity, requiredPermissions, 200);
                                return(false);
                            }
                            else
                            {
                                //Show alertbox to prompt user to enable location services in app level
                                AlertDialog.Builder alert = new AlertDialog.Builder(activity);
                                alert.SetTitle("Location Permission");
                                alert.SetCancelable(false);
                                alert.SetMessage("App needs location permission to access your current location");

                                alert.SetPositiveButton("OK", (senderAlert, args) =>
                                {
                                    MainActivity.FormsContext.StartActivity(new Intent(Android.Provider.Settings.ActionApplicationDetailsSettings, Android.Net.Uri.Parse("package:com.xamarinlife.locationpermissions")));
                                });

                                alert.SetNegativeButton("Cancel", (senderAlert, args) =>
                                {
                                    //MessagingCenter.Send<object>("EVENTLOCATION", "REJECTED");
                                });

                                Dialog dialog = alert.Create();
                                dialog.Show();
                                return(false);
                            }
                        }
                    }
                    //Less than Marshmallow version so we can request directly
                    else
                    {
                        ActivityCompat.RequestPermissions(activity, new String[] { Manifest.Permission.AccessFineLocation }, 200);
                        return(false);
                    }
                }
                else
                {
                    //show popup to redirect to settings page to enable GPS
                    AlertDialog.Builder alert = new AlertDialog.Builder(activity);
                    alert.SetTitle("GPS ");
                    alert.SetCancelable(false);
                    alert.SetMessage("GPS is disabled. Please enable GPS to access full feature.");

                    alert.SetPositiveButton("OK", (senderAlert, args) =>
                    {
                        MainActivity.FormsContext.StartActivity(new Intent(Android.Provider.Settings.ActionSettings));
                    });

                    alert.SetNegativeButton("Cancel", (senderAlert, args) =>
                    {
                        //MessagingCenter.Send<object>("EVENTLOCATION", "REJECTED");
                    });

                    Dialog dialog = alert.Create();
                    dialog.Show();
                    return(false);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 18
0
 static bool ShowRationale(Activity context, string permission)
 {
     return(ActivityCompat.ShouldShowRequestPermissionRationale(context, permission));
 }
Esempio n. 19
0
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
        {
            //("MainActivity.OnRequestPermissionsResult requestCode:" + requestCode + " len:" + permissions.Length);
            if (permissions.Length == 0)
            {
                //("MainActivity.OnRequestPermissionsResult no permissions returned, RETURNING");
                return;
            }
            string text = Java.Util.Locale.Default.Language.Substring(0, 2);
            //("OnRequestPermissionsResult Language Code:" + text);
            string message;
            string message2;

            switch (text)
            {
            case "de":
                message  = "Du musst die Erlaubnis zum Lesen/Schreiben auf dem externen Speicher geben, um das Spiel zu speichern und Speicherstände auf andere Plattformen übertragen zu können. Bitte gib diese Genehmigung, um spielen zu können.";
                message2 = "Bitte geh in die Handy-Einstellungen > Apps > Stardew Valley > Berechtigungen und aktiviere den Speicher, um das Spiel zu spielen.";
                break;

            case "es":
                message  = "Para guardar la partida y transferir partidas guardadas a y desde otras plataformas, se necesita permiso para leer/escribir en almacenamiento externo. Concede este permiso para poder jugar.";
                message2 = "En el teléfono, ve a Ajustes > Aplicaciones > Stardew Valley > Permisos y activa Almacenamiento para jugar al juego.";
                break;

            case "ja":
                message  = "外部機器への読み込み/書き出しの許可が、ゲ\u30fcムのセ\u30fcブデ\u30fcタの保存や他プラットフォ\u30fcムとの双方向のデ\u30fcタ移行実行に必要です。プレイを続けるには許可をしてください。";
                message2 = "設定 > アプリ > スタ\u30fcデュ\u30fcバレ\u30fc > 許可の順に開いていき、ストレ\u30fcジを有効にしてからゲ\u30fcムをプレイしましょう。";
                break;

            case "pt":
                message  = "Para salvar o jogo e transferir jogos salvos entre plataformas é necessário permissão para ler/gravar em armazenamento externo. Forneça essa permissão para jogar.";
                message2 = "Acesse Configurar > Aplicativos > Stardew Valley > Permissões e ative Armazenamento para jogar.";
                break;

            case "ru":
                message  = "Для сохранения игры и переноса сохранений с/на другие платформы нужно разрешение на чтение-запись на внешнюю память. Дайте разрешение, чтобы начать играть.";
                message2 = "Перейдите в меню Настройки > Приложения > Stardew Valley > Разрешения и дайте доступ к памяти, чтобы начать играть.";
                break;

            case "ko":
                message  = "게임을 저장하려면 외부 저장공간에 대한 읽기/쓰기 권한이 필요합니다. 또한 저장 데이터 이전 기능을 허용해 다른 플랫폼에서 게임 진행상황을 가져올 때에도 권한이 필요합니다. 게임을 플레이하려면 권한을 허용해 주십시오.";
                message2 = "휴대전화의 설정 > 어플리케이션 > 스타듀 밸리 > 권한 에서 저장공간을 활성화한 뒤 게임을 플레이해 주십시오.";
                break;

            case "tr":
                message  = "Oyunu kaydetmek ve kayıtları platformlardan platformlara taşımak için harici depolamada okuma/yazma izni gereklidir. Lütfen oynayabilmek için izin verin.";
                message2 = "Lütfen oyunu oynayabilmek için telefonda Ayarlar > Uygulamalar > Stardew Valley > İzinler ve Depolamayı etkinleştir yapın.";
                break;

            case "fr":
                message  = "Une autorisation de lecture / écriture sur un stockage externe est requise pour sauvegarder le jeu et vous permettre de transférer des sauvegardes vers et depuis d'autres plateformes. Veuillez donner l'autorisation afin de jouer.";
                message2 = "Veuillez aller dans les Paramètres du téléphone> Applications> Stardew Valley> Autorisations, puis activez Stockage pour jouer.";
                break;

            case "hu":
                message  = "A játék mentéséhez, és ahhoz, hogy a különböző platformok között hordozhasd a játékmentést, engedélyezned kell a külső tárhely olvasását/írását, Kérjük, a játékhoz engedélyezd ezeket.";
                message2 = "Lépje be a telefonodon a Beállítások > Alkalmazások > Stardew Valley > Engedélyek menübe, majd engedélyezd a Tárhelyet a játékhoz.";
                break;

            case "it":
                message  = "È necessaria l'autorizzazione a leggere/scrivere su un dispositivo di memorizzazione esterno per salvare la partita e per consentire di trasferire i salvataggi da e su altre piattaforme. Concedi l'autorizzazione per giocare.";
                message2 = "Nel telefono, vai su Impostazioni > Applicazioni > Stardew Valley > Autorizzazioni e attiva Memoria archiviazione per giocare.";
                break;

            case "zh":
                message  = "保存游戏进度,以及授权与其它平台交换游戏进度文件,都需要对外部存储器进行读 / 写的权限。要正常游戏,请授予权限。";
                message2 = "请转到手机的设置 > 应用 > Stardew Valley > 权限里,启用“存储”,以正常游戏。";
                break;

            default:
                message  = "Read/write to external storage permission is required to save the game, and to allow to you transfer saves to and from other platforms. Please give permission in order to play.";
                message2 = "Please go into phone Settings > Apps > Stardew Valley > Permissions, and enable Storage to play the game.";
                break;
            }
            int num = 0;

            if (requestCode == 0)
            {
                for (int i = 0; i < grantResults.Length; i++)
                {
                    //("MainActivity.OnRequestPermissionsResult permission:" + permissions[i] + ", granted:" + grantResults[i]);
                    if (grantResults[i] == Permission.Granted)
                    {
                        num++;
                    }
                    else if (grantResults[i] == Permission.Denied)
                    {
                        //("MainActivity.OnRequestPermissionsResult PERMISSION " + permissions[i] + " DENIED!");
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        if (ActivityCompat.ShouldShowRequestPermissionRationale(this, permissions[i]))
                        {
                            builder.SetMessage(message);
                            builder.SetPositiveButton("OK", delegate
                            {
                                this.PromptForPermissions();
                            });
                        }
                        else
                        {
                            builder.SetMessage(message2);
                            builder.SetPositiveButton("OK", delegate
                            {
                                this.FinishAffinity();
                            });
                        }
                        Dialog dialog = builder.Create();
                        if (!this.IsFinishing)
                        {
                            dialog.Show();
                        }
                        return;
                    }
                }
            }
            if (num == permissions.Length)
            {
                if (this._callback != null)
                {
                    //("MainActivity.OnRequestPermissionsResult permissions granted, calling callback");
                    this._callback();
                    this._callback = null;
                }
                else
                {
                    //("MainActivity.OnRequestPermissionsResult " + num + "/" + permissions.Length + " granted, check for licence...");
                    this.OnCreatePartTwo();
                }
            }
        }
Esempio n. 20
0
 public static bool ShouldShowUserPermissionRationle(Activity activity) =>
 ActivityCompat.ShouldShowRequestPermissionRationale(activity, Manifest.Permission.RecordAudio) &&
 ActivityCompat.ShouldShowRequestPermissionRationale(activity, Manifest.Permission.WriteExternalStorage);
        protected bool GetPermission(PermissionType permission, Action onPermissionDenied = null)
        {
            var permissionType = "";
            var permissionId   = 0;

            switch (permission)
            {
            case PermissionType.Camera:
            {
                permissionType = Manifest.Permission.Camera;
                permissionId   = PERMISSIONS_REQUEST_CAMERA;
            }
            break;

            case PermissionType.ReadPhoneState:
            {
                permissionType = Manifest.Permission.ReadPhoneState;
                permissionId   = PERMISSIONS_REQUEST_READ_PHONE_STATE;
            }
            break;

            case PermissionType.WriteExternalStorage:
            {
                permissionType = Manifest.Permission.WriteExternalStorage;
                permissionId   = PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE;
            }
            break;

            case PermissionType.Microphone:
            {
                permissionType = Manifest.Permission.RecordAudio;
                permissionId   = PERMISSIONS_REQUEST_MICROPHONE;
            }
            break;

            case PermissionType.Location:
            {
                permissionType = Manifest.Permission.AccessFineLocation;
                permissionId   = PERMISSIONS_REQUEST_LOCATION;
            }
            break;
            }
            if (string.IsNullOrEmpty(permissionType))
            {
                return(false);
            }

            var permissionCheck = ContextCompat.CheckSelfPermission(this, permissionType);

            if (permissionCheck == Permission.Denied)
            {
                if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.CallPhone))
                {
                    onPermissionDenied?.Invoke();
                }
                else
                {
                    ActivityCompat.RequestPermissions(this, new[] { permissionType }, permissionId);
                }
                ActivityPermissions[permission] = false;
                return(ActivityPermissions[permission]);
            }

            ActivityPermissions[permission] = true;
            return(ActivityPermissions[permission]);
        }
Esempio n. 22
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
            {
                Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);
                Window.SetStatusBarColor(Color.White.ToAndroid());
                Window.SetNavigationBarColor(Color.White.ToAndroid());
            }
            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            Forms.SetFlags("CollectionView_Experimental");
            Forms.Init(this, savedInstanceState);

            /**
             * Subscribe to the "AuthenticatePhone" message, and start/handle firebase phone authentication
             */
            MessagingCenter.Subscribe <FirebaseAuthFunctions, string>(this, "AuthenticatePhone", (sender, phoneNumber) =>
            {
                var phoneVerificationCallbacks       = new PhoneAuthOnVerificationStateChangedCallbacks();
                phoneVerificationCallbacks.CodeSent += PhoneVerificationCodeSent;
                phoneVerificationCallbacks.VerificationCompleted += PhoneVerificationCompleted;
                phoneVerificationCallbacks.VerificationFailed    += PhoneVerificationFailed;

                PhoneAuthProvider.GetInstance(Auth).VerifyPhoneNumber(phoneNumber, 30, TimeUnit.Seconds, this, phoneVerificationCallbacks);
            });

            MessagingCenter.Subscribe <SignupPage>(this, "showingSocialOptions", (sender) =>
            {
                InitFirebaseAuth();
                if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
                {
                    Window.SetStatusBarColor(Android.Graphics.Color.ParseColor("#E81945"));
                    Window.SetNavigationBarColor(Android.Graphics.Color.ParseColor("#191919"));
                    Window.DecorView.SystemUiVisibility = StatusBarVisibility.Visible;
                }
            });

            MessagingCenter.Subscribe <ContinueSignup>(this, "RequestLocation", (sender) =>
            {
                if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
                {
                    string lastPermission = "";
                    foreach (string permission in PermissionsLocation)
                    {
                        if (ContextCompat.CheckSelfPermission(this, permission) != (int)Permission.Granted)
                        {
                            if (ActivityCompat.ShouldShowRequestPermissionRationale(this, lastPermission))
                            {
                                Android.Views.View layout = FindViewById(Android.Resource.Id.Content);
                                Snackbar
                                .Make(layout, "Allow location access or manually select your preferred Country and State", Snackbar.LengthLong)
                                .SetAction("OK", v => ActivityCompat.RequestPermissions(this, PermissionsLocation, RequestLocationId))
                                .Show();
                            }
                            else
                            {
                                ActivityCompat.RequestPermissions(this, PermissionsLocation, RequestLocationId);
                            }
                            break;
                        }
                    }
                }
            });

            Window.SetBackgroundDrawable(new ColorDrawable(Color.White.ToAndroid()));

            App app = new App();

            LoadApplication(app);
        }
Esempio n. 23
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            //first check if there are permsions to access files ext
            bool checks = true;

            _context = this;

            #region << Check For Permisions >>

            // Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) || ActivityCompat.CheckSelfPermission(this, Manifest.Permission.AccessWifiState) || Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.Internet)

            if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this,
                                                                             Manifest.Permission.Internet) != (int)Permission.Granted)
            {
                if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.Internet))
                {
                    ActivityCompat.RequestPermissions(this,
                                                      new String[] { Manifest.Permission.Internet, Manifest.Permission.Internet }, 1);
                    //  })).Show();
                }

                while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.Internet) !=
                       (int)Permission.Granted)
                {
                    Thread.Sleep(100);
                }
            }


            if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this,
                                                                             Manifest.Permission.AccessWifiState) != (int)Permission.Granted)
            {
                if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessWifiState))
                {
                    ActivityCompat.RequestPermissions(this,
                                                      new String[] { Manifest.Permission.AccessWifiState, Manifest.Permission.AccessWifiState }, 1);
                    //  })).Show();
                }

                while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.AccessWifiState) !=
                       (int)Permission.Granted)
                {
                    Thread.Sleep(100);
                }
            }

            if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this,
                                                                             Manifest.Permission.AccessNetworkState) != (int)Permission.Granted)
            {
                if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessNetworkState))
                {
                    ActivityCompat.RequestPermissions(this,
                                                      new String[] { Manifest.Permission.AccessNetworkState, Manifest.Permission.AccessNetworkState },
                                                      1);
                    //  })).Show();
                }

                while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.AccessNetworkState) !=
                       (int)Permission.Granted)
                {
                    Thread.Sleep(100);
                }
            }

            if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this,
                                                                             Manifest.Permission.ReadExternalStorage) !=
                (int)Permission.Granted)
            {
                // Camera permission has not been granted
                RequestReadWirtePermission();
                while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) !=
                       (int)Permission.Granted)
                {
                    Thread.Sleep(100);
                }
            }

            #endregion << Check For Permisions  >>

            base.OnCreate(savedInstanceState);



            //request the app to be full screen

            RequestWindowFeature(WindowFeatures.NoTitle);
            this.Window.ClearFlags(Android.Views.WindowManagerFlags.Fullscreen); //to hide

            Rebex.Licensing.Key = "==AnKxIZnJ2NXyRRk/MrXLh5vsLbImP/JhMGERReY23qIk==";

            SetContentView(Resource.Layout.plugin);

            refreshui();
            retrieveset();


            SendPayloadBtn.Click += delegate
            {
                new Thread(new ThreadStart(delegate
                {
                    using (Ftp client = new Ftp())
                    {
                        Rebex.Licensing.Key = "==AnKxIZnJ2NXyRRk/MrXLh5vsLbImP/JhMGERReY23qIk==";
                        try
                        {
                            // TextView IPAddressTextBox = FindViewById<TextView>(Resource.Id.IPAddressTextBox);
                            if (IPAddressTextBox.Text == "")
                            {
                                RunOnUiThread(() => { MessageBox.Show("Enter an IP Address"); });
                                return;
                            }


                            saveset();


                            // connect and login to the FTP
                            client.Connect(IPAddressTextBox.Text);
                            //TextView FTPPassword = FindViewById<TextView>(Resource.Id.FTPPassword);
                            //TextView FTPUsername = FindViewById<TextView>(Resource.Id.FTPUsername);
                            if (FTPPassword.Text == "" && FTPUsername.Text == "")
                            {
                                client.Login("anonymous", "DONT-LOOK@MYCODE");
                            }
                            else
                            {
                                client.Login(FTPUsername.Text, FTPPassword.Text);
                            }


                            client.Traversing += Traversing;
                            client.TransferProgressChanged += TransferProgressChanged;
                            client.DeleteProgressChanged   += DeleteProgressChanged;
                            client.ProblemDetected         += ProblemDetected;

                            string path = System.IO.Path.Combine(ApplicationContext.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads).AbsolutePath + @"/PayloadPlugin.prx");

                            //  RunOnUiThread(() => { MessageBox.Show(path); });
                            bool exists = System.IO.Directory.Exists(System.IO.Path.Combine(ApplicationContext.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads).AbsolutePath));

                            if (!exists)
                            {
                                System.IO.Directory.CreateDirectory(System.IO.Path.Combine(ApplicationContext.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads).AbsolutePath));
                            }

                            System.Console.WriteLine(path);

                            SetTex("Downloading Plugin from DKS");

                            using (var clients = new WebClient())
                            {
                                if (System.IO.Directory.Exists(path))
                                {
                                    System.IO.File.Delete(path);
                                }

                                clients.DownloadFile("https://psarchive.darksoftware.xyz/PayloadPlugin.prx", path);
                            }



                            if (!client.DirectoryExists(@"/user/app/"))
                            {
                                client.CreateDirectory(@"/user/app/");
                            }

                            if (client.FileExists(@"/user/app/PayloadPlugin.prx"))
                            {
                                client.Delete(@"/user/app/PayloadPlugin.prx", TraversalMode.NonRecursive);
                            }

                            client.ChangeDirectory(@"/user/app/");


                            client.PutFile(path, @"PayloadPlugin.prx");

                            SetTex("Plugin Installed Successfully");
                        }


                        catch (Exception ex)
                        {
                            RunOnUiThread(() => { MessageBox.Show(ex.Message); });
                        }


                        RunOnUiThread(() =>
                        {
                            Toast.MakeText(Application.Context, "Installed!", ToastLength.Short).Show();
                        });

                        client.Disconnect();
                    }
                })).Start();
            };

            /* }
             * else
             * {
             *   SendPayloadBtn.Visibility = ViewStates.Invisible;
             *   LoadPkg.Visibility = ViewStates.Invisible;
             * }*/
        }
Esempio n. 24
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 <ScanSKUDataBase.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 ScanSKUDataBase.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);
                }
            }
        }
Esempio n. 25
0
 // this method is only valid if request status = Denied
 public bool IsRetryAllowedForDeniedMicrophone()
 => ActivityCompat.ShouldShowRequestPermissionRationale(MainActivity.Instance, Manifest.Permission.RecordAudio);
        protected override void OnCreate(Bundle savedInstanceState)
        {
            //first check if there are permsions to access files ext
            bool checks = true;


            #region << Check For Permisions >>

            // Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) || ActivityCompat.CheckSelfPermission(this, Manifest.Permission.AccessWifiState) || Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.Internet)

            if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this,
                                                                             Manifest.Permission.Internet) != (int)Permission.Granted)
            {
                if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.Internet))
                {
                    ActivityCompat.RequestPermissions(this,
                                                      new String[] { Manifest.Permission.Internet, Manifest.Permission.Internet }, 1);
                    //  })).Show();
                }

                while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.Internet) !=
                       (int)Permission.Granted)
                {
                    Thread.Sleep(100);
                }
            }


            if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this,
                                                                             Manifest.Permission.AccessWifiState) != (int)Permission.Granted)
            {
                if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessWifiState))
                {
                    ActivityCompat.RequestPermissions(this,
                                                      new String[] { Manifest.Permission.AccessWifiState, Manifest.Permission.AccessWifiState }, 1);
                    //  })).Show();
                }

                while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.AccessWifiState) !=
                       (int)Permission.Granted)
                {
                    Thread.Sleep(100);
                }
            }

            if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this,
                                                                             Manifest.Permission.AccessNetworkState) != (int)Permission.Granted)
            {
                if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessNetworkState))
                {
                    ActivityCompat.RequestPermissions(this,
                                                      new String[] { Manifest.Permission.AccessNetworkState, Manifest.Permission.AccessNetworkState },
                                                      1);
                    //  })).Show();
                }

                while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.AccessNetworkState) !=
                       (int)Permission.Granted)
                {
                    Thread.Sleep(100);
                }
            }

            if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this,
                                                                             Manifest.Permission.ReadExternalStorage) !=
                (int)Permission.Granted)
            {
                // Camera permission has not been granted
                RequestReadWirtePermission();
                while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) !=
                       (int)Permission.Granted)
                {
                    Thread.Sleep(100);
                }
            }

            #endregion << Check For Permisions  >>

            base.OnCreate(savedInstanceState);


            //request the app to be full screen

            RequestWindowFeature(WindowFeatures.NoTitle);
            this.Window.ClearFlags(Android.Views.WindowManagerFlags.Fullscreen); //to hide

            Rebex.Licensing.Key = "==AnKxIZnJ2NXyRRk/MrXLh5vsLbImP/JhMGERReY23qIk==";

            SetContentView(Resource.Layout.selectui);
            this.Title = "Package Installer"; //set the title



            refreshui();

            SelectPackageUI.Click += async delegate
            {
                Intent Next = new Intent(this, typeof(installer));
                StartActivity(Next);
            };

            SelectPluginUI.Click += async delegate
            {
                Intent Next = new Intent(this, typeof(plugin));
                StartActivity(Next);
            };
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            _context = this;
            //first check if there are permsions to access files ext
            bool checks = true;


            #region << Check For Permisions >>

            // Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) || ActivityCompat.CheckSelfPermission(this, Manifest.Permission.AccessWifiState) || Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Manifest.Permission.Internet)

            if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this,
                                                                             Manifest.Permission.Internet) != (int)Permission.Granted)
            {
                if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.Internet))
                {
                    ActivityCompat.RequestPermissions(this,
                                                      new String[] { Manifest.Permission.Internet, Manifest.Permission.Internet }, 1);
                    //  })).Show();
                }

                while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.Internet) !=
                       (int)Permission.Granted)
                {
                    Thread.Sleep(100);
                }
            }


            if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this,
                                                                             Manifest.Permission.AccessWifiState) != (int)Permission.Granted)
            {
                if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessWifiState))
                {
                    ActivityCompat.RequestPermissions(this,
                                                      new String[] { Manifest.Permission.AccessWifiState, Manifest.Permission.AccessWifiState }, 1);
                    //  })).Show();
                }

                while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.AccessWifiState) !=
                       (int)Permission.Granted)
                {
                    Thread.Sleep(100);
                }
            }

            if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this,
                                                                             Manifest.Permission.AccessNetworkState) != (int)Permission.Granted)
            {
                if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessNetworkState))
                {
                    ActivityCompat.RequestPermissions(this,
                                                      new String[] { Manifest.Permission.AccessNetworkState, Manifest.Permission.AccessNetworkState },
                                                      1);
                    //  })).Show();
                }

                while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.AccessNetworkState) !=
                       (int)Permission.Granted)
                {
                    Thread.Sleep(100);
                }
            }

            if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this,
                                                                             Manifest.Permission.ReadExternalStorage) !=
                (int)Permission.Granted)
            {
                // Camera permission has not been granted
                RequestReadWirtePermission();
                while (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) !=
                       (int)Permission.Granted)
                {
                    Thread.Sleep(100);
                }
            }

            #endregion << Check For Permisions  >>

            base.OnCreate(savedInstanceState);



            //request the app to be full screen

            RequestWindowFeature(WindowFeatures.NoTitle);
            this.Window.ClearFlags(Android.Views.WindowManagerFlags.Fullscreen); //to hide

            Rebex.Licensing.Key = "==AnKxIZnJ2NXyRRk/MrXLh5vsLbImP/JhMGERReY23qIk==";

            SetContentView(Resource.Layout.installer);

            refreshui();
            retrieveset();



            LoadPkg.Click += async delegate
            {
                try
                {
                    String[] types    = new String[] { ".pkg" };
                    FileData fileData = await CrossFilePicker.Current.PickFile(types);

                    if (fileData == null)
                    {
                        return; // user canceled file picking
                    }
                    //com.android.externalstorage.documents



                    System.Console.WriteLine("File name " + fileData.FileName);

                    new Thread(new ThreadStart(delegate
                    {
                        RunOnUiThread(() =>
                        {
                            progress = new ProgressDialog(this);
                            progress.Indeterminate = true;
                            progress.SetProgressStyle(Android.App.ProgressDialogStyle.Spinner);
                            progress.SetMessage("Loading... Getting Path...");
                            progress.SetCancelable(false);
                            progress.Show();
                        });

                        FindFileByName(fileData.FileName);

                        System.Console.WriteLine("Found File, Path= " + PKGLocation);

                        RunOnUiThread(() =>
                        {
                            progress.Hide();
                            try
                            {
                                var pkgfile     = PS4_Tools.PKG.SceneRelated.Read_PKG(PKGLocation);
                                ImageView pbPkg = FindViewById <ImageView>(Resource.Id.PKGIcon);
                                pbPkg.SetImageBitmap(BytesToBitmap(pkgfile.Icon));
                                TextView lblPackageInfo = FindViewById <TextView>(Resource.Id.txtPKGInfo);
                                lblPackageInfo.Text     =
                                    pkgfile.PS4_Title + "\n" + pkgfile.PKG_Type.ToString() + "\n" +
                                    pkgfile.Param.TitleID;
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Invaild Package! or Path\n\n Location: " + PKGLocation);
                                // MessageBox.Show("Exception choosing file: " + ex.ToString() + "    " + PKGLocation);
                            }
                        });
                    })).Start();
                }

                catch (Exception ex)
                {
                    MessageBox.Show("Invaild Package! or Path\n\n Location: " + PKGLocation);
                    // MessageBox.Show("Exception choosing file: " + ex.ToString() + "    " + PKGLocation);
                }
            };

            set.Click += async delegate
            {
                try
                {
                    PKGLocation = manpath.Text;


                    var       pkgfile = PS4_Tools.PKG.SceneRelated.Read_PKG(PKGLocation);
                    ImageView pbPkg   = FindViewById <ImageView>(Resource.Id.PKGIcon);
                    pbPkg.SetImageBitmap(BytesToBitmap(pkgfile.Icon));
                    TextView lblPackageInfo = FindViewById <TextView>(Resource.Id.txtPKGInfo);
                    lblPackageInfo.Text =
                        pkgfile.PS4_Title + "\n" + pkgfile.PKG_Type.ToString() + "\n" +
                        pkgfile.Param.TitleID;
                }

                catch (Exception ex)
                {
                    MessageBox.Show("Invaild Package! or Path\n\n Location: " + PKGLocation);
                    // MessageBox.Show("Exception choosing file: " + ex.ToString() + "    " + PKGLocation);
                }
            };



            SendPayloadBtn.Click += delegate
            {
                new Thread(new ThreadStart(delegate
                {
                    using (Ftp client = new Ftp())
                    {
                        Rebex.Licensing.Key = "==AnKxIZnJ2NXyRRk/MrXLh5vsLbImP/JhMGERReY23qIk==";
                        try
                        {
                            // TextView IPAddressTextBox = FindViewById<TextView>(Resource.Id.IPAddressTextBox);
                            if (IPAddressTextBox.Text == "")
                            {
                                RunOnUiThread(() => { MessageBox.Show("Enter an IP Address"); });
                                return;
                            }


                            saveset();

                            //  string paths = GetPathToImage("sa");



                            // connect and login to the FTP
                            client.Connect(IPAddressTextBox.Text);
                            //TextView FTPPassword = FindViewById<TextView>(Resource.Id.FTPPassword);
                            //TextView FTPUsername = FindViewById<TextView>(Resource.Id.FTPUsername);
                            if (FTPPassword.Text == "" && FTPUsername.Text == "")
                            {
                                client.Login("anonymous", "DONT-LOOK@MYCODE");
                            }
                            else
                            {
                                client.Login(FTPUsername.Text, FTPPassword.Text);
                            }


                            client.Traversing += Traversing;
                            client.TransferProgressChanged += TransferProgressChanged;
                            client.DeleteProgressChanged   += DeleteProgressChanged;
                            client.ProblemDetected         += ProblemDetected;

                            if (!client.DirectoryExists(@"/user/app/"))
                            {
                                client.CreateDirectory(@"/user/app/");
                            }

                            if (client.FileExists(@"/user/app/temp.pkg"))
                            {
                                client.Delete(@"/user/app/temp.pkg", TraversalMode.NonRecursive);
                            }

                            client.ChangeDirectory(@"/user/app/");


                            client.PutFile(PKGLocation, "temp.pkg");

                            try
                            {
                                client.SendCommand("installpkg");
                            }
                            catch (Exception ex)
                            {
                                SetTex("installpkg Failed\n Are you sure your using Inifinx?");
                            }


                            SetTex("Package Sent");
                        }

                        catch (Exception ex)
                        {
                            RunOnUiThread(() => { MessageBox.Show(ex.Message); });
                        }



                        RunOnUiThread(() =>
                        {
                            Toast.MakeText(Application.Context, "Package Sent!", ToastLength.Short).Show();
                        });

                        client.Disconnect();
                    }
                })).Start();
            };

            /* }
             * else
             * {
             *   SendPayloadBtn.Visibility = ViewStates.Invisible;
             *   LoadPkg.Visibility = ViewStates.Invisible;
             * }*/
        }
Esempio n. 28
0
        public static bool PermissionsCheck(Activity activity, View layout, bool optional, params string[] perms)
        {
            //TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.M)
            {
                var isok     = true;
                var isdenied = false;

                foreach (var perm in perms)
                {
                    if (ContextCompat.CheckSelfPermission(activity, (string)perm) != Android.Content.PM.Permission.Granted)
                    {
                        isok = false;
                    }

                    if (ContextCompat.CheckSelfPermission(activity, (string)perm) != Android.Content.PM.Permission.Denied)
                    {
                        isdenied = true;
                    }
                }

                if (isok)
                {
                    return(true);
                }

                //if (ContextCompat.CheckSelfPermission(activity, Manifest.Permission.Camera) == Android.Content.PM.Permission.Granted &&
                //    ContextCompat.CheckSelfPermission(activity, Manifest.Permission.RecordAudio) == Android.Content.PM.Permission.Granted &&
                //    ContextCompat.CheckSelfPermission(activity, Manifest.Permission.AccessFineLocation) == Android.Content.PM.Permission.Granted &&
                //    ContextCompat.CheckSelfPermission(activity, Manifest.Permission.WriteExternalStorage) == Android.Content.PM.Permission.Granted)
                //{
                //    return true;
                //}

                var showrationale = false;

                foreach (var perm in perms)
                {
                    if (ActivityCompat.ShouldShowRequestPermissionRationale(activity, perm))
                    {
                        showrationale = true;
                    }
                }

                //if need to show rationale
                if (showrationale)
                {
                    Snackbar.Make(layout, "Location access is required to find shoots nearby.", Snackbar.LengthIndefinite)
                    .SetAction("OK", v => ActivityCompat.RequestPermissions(activity, perms, (optional) ? OPTIONAL : NON_OPTIONAL))
                    .Show();

                    return(false);
                }
                else
                {
                    //if dont neeed to show rationale
                    if ((optional && !isdenied) || !optional)
                    {
                        ActivityCompat.RequestPermissions(activity, perms, (optional) ? OPTIONAL : NON_OPTIONAL);
                    }

                    return(false);
                }
            }
            else
            {
                return(true);
                //tcs.SetResult(true);
            }
            //return tcs.Task;
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            StrictMode.VmPolicy.Builder builder1 = new StrictMode.VmPolicy.Builder();
            StrictMode.SetVmPolicy(builder1.Build());
            StrictMode.ThreadPolicy.Builder builder2 = new StrictMode.ThreadPolicy.Builder().PermitAll();
            StrictMode.SetThreadPolicy(builder2.Build());
            base.OnCreate(savedInstanceState);

            restService = new ServiceHelper();

            SetContentView(Resource.Layout.LoginLayout);

            GoogleApiClient.Builder builder = new GoogleApiClient.Builder(this);
            builder.AddConnectionCallbacks(this);
            builder.AddOnConnectionFailedListener(this);
            builder.AddApi(PlusClass.API);
            builder.AddScope(PlusClass.ScopePlusProfile);
            builder.AddScope(PlusClass.ScopePlusLogin);
            //Build our IGoogleApiClient
            mGoogleApiClient = builder.Build();

            // mGoogleApiClient.Disconnect();

            mGsignBtn = FindViewById <SignInButton>(Resource.Id.sign_in_button);
            TextView txtenglish = FindViewById <TextView>(Resource.Id.english);
            TextView txthindi   = FindViewById <TextView>(Resource.Id.hindi);

            txtenglish.SetText(Resource.String.stportal);
            txthindi.SetText(Resource.String.stportalhindi);
            pref     = GetSharedPreferences("login", FileCreationMode.Private);
            edit     = pref.Edit();
            user     = FindViewById <EditText>(Resource.Id.username);
            pass     = FindViewById <EditText>(Resource.Id.pass);
            log      = FindViewById <Button>(Resource.Id.login);
            register = FindViewById <Button>(Resource.Id.regis);

            log.Click += delegate
            {
                UserLogin();
            };

            register.Click += delegate
            {
                var intent6 = new Intent(this, typeof(Registration_Activity));
                StartActivityForResult(intent6, 106);
            };
            mGsignBtn.Click += delegate
            {
                if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.GetAccounts) != (int)Permission.Granted)
                {
                    if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.GetAccounts))
                    {
                    }

                    else
                    {
                        ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.GetAccounts }, 115);
                    }
                }
                else
                {
                    // DoAuthentication("*****@*****.**", "", "Deepanshu Mishra");
                    if (!mGoogleApiClient.IsConnecting)
                    {
                        mSignInClicked = true;
                        ResolveSignInError();
                    }
                    else if (mGoogleApiClient.IsConnected)
                    {
                        PlusClass.AccountApi.ClearDefaultAccount(mGoogleApiClient);
                        mGoogleApiClient.Disconnect();
                    }
                }
            };
        }
Esempio n. 30
0
 void requestPermissionForCameraAndMicrophone()
 {
     if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Android.Manifest.Permission.Camera) || ActivityCompat.ShouldShowRequestPermissionRationale(this, Android.Manifest.Permission.RecordAudio))
     {
         Toast.MakeText(this, "Camera and Microphone permissions needed. Please allow in App Settings for additional functionality.", ToastLength.Long).Show();
     }
     else
     {
         ActivityCompat.RequestPermissions(this, new [] { Android.Manifest.Permission.Camera, Android.Manifest.Permission.RecordAudio }, CAMERA_MIC_PERMISSION_REQUEST_CODE);
     }
 }