protected override void OnActivityResult (int requestCode, Result resultCode, Intent data)
		{
			base.OnActivityResult (requestCode, resultCode, data);
			if (resultCode == Result.Ok) {
				//user is returning from capturing an image using the camera
				if(requestCode == CAMERA_CAPTURE){
					//get the Uri for the captured image
					picUri = data.Data;
					//carry out the crop operation
					performCrop();
				}
				//user is returning from cropping the image
				else if(requestCode == PIC_CROP){
					//get the returned data
					Bundle extras = data.Extras;
					//get the cropped bitmap
					Bitmap thePic = (Android.Graphics.Bitmap)extras.GetParcelable("data");
					//retrieve a reference to the ImageView
					ImageView picView = FindViewById<ImageView>(Resource.Id.picture);
					//display the returned cropped image
					picView.SetImageBitmap(thePic);
					//Store Image in Phone
					Android.Provider.MediaStore.Images.Media.InsertImage(ContentResolver,thePic,"imgcrop","Description");
				}
			}
		}
Ejemplo n.º 2
0
		protected override void OnCreate (Bundle icicle)
		{
			//base.OnCreate(icicle);
			if (!LibsChecker.CheckVitamioLibs (this))
				return;
			SetContentView (Resource.Layout.videobuffer);
			mVideoView = FindViewById<VideoView> (Resource.Id.buffer);
			pb = FindViewById<ProgressBar> (Resource.Id.probar);

			downloadRateView = FindViewById<TextView> (Resource.Id.download_rate);
			loadRateView = FindViewById<TextView> (Resource.Id.load_rate);
			if (path == "") {
				// Tell the user to provide a media file URL/path.
				Toast.MakeText (this, "Please edit VideoBuffer Activity, and set path" + " variable to your media file URL/path", ToastLength.Long).Show ();
				return;
			} else {
				//      
				//       * Alternatively,for streaming media you can use
				//       * mVideoView.setVideoURI(Uri.parse(URLstring));
				//       
				uri = Android.Net.Uri.Parse (path);
				mVideoView.SetVideoURI (uri);
				mVideoView.SetMediaController (new MediaController (this));
				mVideoView.RequestFocus ();
				mVideoView.SetOnInfoListener (this);
				mVideoView.SetOnBufferingUpdateListener (this);
				mVideoView.Prepared += (object sender, MediaPlayer.PreparedEventArgs e) => {
					e.P0.SetPlaybackSpeed(1.0f);
				};
			}
		}
Ejemplo n.º 3
0
 protected string GetPath(Uri uri)
 {
     string[] projection = { MediaStore.Images.Media.InterfaceConsts.Data };
     ICursor cursor = Activity.ManagedQuery(uri, projection, null, null, null);
     int index = cursor.GetColumnIndexOrThrow(MediaStore.Images.Media.InterfaceConsts.Data);
     cursor.MoveToFirst();
     return cursor.GetString(index);
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Sets the image to share. This can only be called once, you can only share one video or image. Not both.
        /// </summary>
        /// <param name="uri"><see cref="Android.Net.Uri"/> with the Uri to the image</param>
        /// <exception cref="ArgumentNullException">Throws if <param name="uri"/> is null.</exception>
        /// <exception cref="InvalidOperationException">Throws if an Image or Video Uri has already been set. Only one Image or Video Uri allowed</exception>
        public SocialShare Image(Android.Net.Uri uri)
        {
            if (uri == null) throw new ArgumentNullException(nameof(uri));
            if (_uri != null) throw new InvalidOperationException("Only one Image or Video Uri allowed");

            _uri = uri;
            _mimeType = Mime.AnyImage;
            return this;
        }
Ejemplo n.º 5
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult (requestCode, resultCode, data);

            if (resultCode == Result.Ok) {
                chooseButton.SetImageURI (data.Data);
                imageUri = data.Data;
            }
        }
Ejemplo n.º 6
0
		void CapturamosImagen ()
		{
			//FUNCION QUE SE ENCARGA DE CAPTURAR LA IMAGEN USANDO UN INTENT
			Intent intent = new Intent (MediaStore.ActionImageCapture);
			fileUri = GetOutputMediaFile (this.ApplicationContext, IMAGE_DIRECTORY_NAME, String.Empty);
			intent.PutExtra(MediaStore.ExtraOutput, fileUri);

			//LANZAMOS NUESTRO ITEM PARA CAPTURA LA IMAGEN
			StartActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
		}
Ejemplo n.º 7
0
      public TableFindResult Find( Expression expression )
      {
         Visit( expression );

         var result = new TableFindResult( table, mimeType );

         table = null;
         mimeType = null;

         return result;
      }
		public override void OnCreate (Bundle p0)
		{
			base.OnCreate (p0);
			
			Intent intent = BaseActivity.FragmentArgumentsToIntent (Arguments);
			mVendorUri = intent.Data;
			if (mVendorUri == null) {
				return;
			}
	
			SetHasOptionsMenu (true);
		}
Ejemplo n.º 9
0
        /// <summary>
        /// Override default OnCreate
        /// </summary>
        /// <param name="bundle"></param>
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Main);

            Button browseButton = FindViewById<Button>(Resource.Id.ButtonBrowse);

            //When "Browse" button clicked, fire an intent to select image
            browseButton.Click += delegate
            {
                Intent imageIntent = new Intent();
                imageIntent.SetType(FileType_Image);
                imageIntent.SetAction(Intent.ActionGetContent);
                StartActivityForResult(
                    Intent.CreateChooser(imageIntent, PromptText_SelectImage), PICK_IMAGE);
            };

            Button takePictureButton = FindViewById<Button>(Resource.Id.ButtonTakePicture);

            //When "Take a picture" button clicked, fire an intent to take picture
            takePictureButton.Click += delegate
            {
                Intent takePictureIntent = new Intent(MediaStore.ActionImageCapture);
                if (takePictureIntent.ResolveActivity(PackageManager) != null)
                {
                    // Create the File where the photo should go
                    Java.IO.File photoFile = null;
                    try
                    {
                        photoFile = createImageFile();
                    }
                    catch (Java.IO.IOException)
                    {
                        //TODO: Error handling
                    }  
                    // Continue only if the File was successfully created
                    if (photoFile != null)
                    {
                        takePictureIntent.PutExtra(MediaStore.ExtraOutput, 
                            Android.Net.Uri.FromFile(photoFile));

                        //Delete this temp file, only keey its Uri information
                        photoFile.Delete();

                        TempFileUri = Android.Net.Uri.FromFile(photoFile);
                        StartActivityForResult(takePictureIntent, TAKE_PICTURE);
                    }
                }
            };
                    
        }
Ejemplo n.º 10
0
        public void TakePicture(int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable,
                                Action assumeCancelled)
        {
            var intent = new Intent(MediaStore.ActionImageCapture);

            _cachedUriLocation = GetNewImageUri();
            intent.PutExtra(MediaStore.ExtraOutput, _cachedUriLocation);
            intent.PutExtra("outputFormat", Bitmap.CompressFormat.Jpeg.ToString());
            intent.PutExtra("return-data", true);

            ChoosePictureCommon(MvxIntentRequestCode.PickFromCamera, intent, maxPixelDimension, percentQuality,
                                pictureAvailable, assumeCancelled);
        }
Ejemplo n.º 11
0
		protected override void OnResume ()
		{
			base.OnResume ();

			//Used in HomeActivity to save pdf annotations
			if (Intent.Data != null) { 
				intentData = Intent.Data;
			} else if (Intent.ClipData != null) {
				clipData = Intent.ClipData;
			}
			else {
				intentData = null;
			}
		}
Ejemplo n.º 12
0
 private string GetPathToImage(Uri uri)
 {
     string path = null;
     // The projection contains the columns we want to return in our query.
     string[] projection = new[] { Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data };
     using (ICursor cursor = ManagedQuery(uri, projection, null, null, null))
     {
         if (cursor != null)
         {
             int columnIndex = cursor.GetColumnIndexOrThrow(Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data);
             cursor.MoveToFirst();
             path = cursor.GetString(columnIndex);
         }
     }
     return path;
 }
 protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
 {
     base.OnActivityResult (requestCode, resultCode, data);
     switch (requestCode) {
     case 0:{
             if (resultCode == Result.Ok) {
                 uri = data.Data;
                 videoView.SetVideoURI (uri);
                 videoView.Start ();
             }
             break;
         }
     default:
         break;
     }
 }
		public override void OnCreate (Bundle p0)
		{
			base.OnCreate (p0);
			
			Intent intent = BaseActivity.FragmentArgumentsToIntent (Arguments);
			mSessionUri = intent.Data;
			mTrackUri = ResolveTrackUri (intent);
			packageChangesReceiver = new PackageChangesReceiver (this);
			
			if (mSessionUri == null) {
				return;
			}
	
			mSessionId = ScheduleContract.Sessions.GetSessionId (mSessionUri);
			
			HasOptionsMenu = true;
		}
Ejemplo n.º 15
0
        private void PerformCrop(Uri picUri, Action<string> callbackResult, string path)
        {
            Intent cropIntent = new Intent("com.android.camera.action.CROP");
            // indicate image type and Uri
            cropIntent.SetDataAndType(picUri, "image/*");
            // set crop properties
            cropIntent.PutExtra("crop", "true");
            // indicate aspect of desired crop
            cropIntent.PutExtra("aspectX", 1);
            cropIntent.PutExtra("aspectY", 1);
            // retrieve data on return
            cropIntent.PutExtra(MediaStore.ExtraOutput, picUri);
            // start the activity - we handle returning in onActivityResult
            ActivityService.StartActivityForResult(cropIntent, (result, data) =>
            {
				callbackResult(result == Result.Ok ? path : null);
            });
        }
Ejemplo n.º 16
0
        private void doTakePhotoAction()
        {

            Intent intent = new Intent(MediaStore.ActionImageCapture);

            mImageCaptureUri = Android.Net.Uri.FromFile(new Java.IO.File(createDirectoryForPictures(), string.Format("myPhoto_{0}.jpg", System.Guid.NewGuid())));

            intent.PutExtra(MediaStore.ExtraOutput, mImageCaptureUri);

            try
            {
                intent.PutExtra("return-data", false);
                StartActivityForResult(intent, PICK_FROM_CAMERA);
            }
            catch (ActivityNotFoundException e)
            {
                e.PrintStackTrace();
            }
        }
    protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
      base.OnActivityResult(requestCode, resultCode, data);

      if (resultCode == Result.Ok)
      {
        this.imageUri = data.Data;
        try
        {
          if (this.imageBitmap != null)
            this.imageBitmap.Recycle();

          this.imageBitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, data.Data);
          this.selectedImage.SetImageBitmap(this.imageBitmap);
        }
        catch (Exception)
        {
          Toast.MakeText(this, "Image is to large for preview", ToastLength.Long).Show();
        }
      }
    }
Ejemplo n.º 18
0
 internal Album(SongCollection songCollection, string name, Artist artist, Genre genre, Android.Net.Uri thumbnail)
     : this(songCollection, name, artist, genre)
 {
     this.thumbnail = thumbnail;
 }
Ejemplo n.º 19
0
 public override Android.Net.Uri Insert(Android.Net.Uri uri, ContentValues values)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 20
0
        public static void Initialize(Context context, bool resetToken, bool createDefaultNotificationChannel = true, bool autoRegistration = true)
        {
            CrossFirebaseEssentials.Notifications.NotificationHandler = CrossFirebaseEssentials.Notifications.NotificationHandler ?? new DefaultPushNotificationHandler();
            FirebaseMessaging.Instance.AutoInitEnabled = autoRegistration;

            if (autoRegistration)
            {
                ThreadPool.QueueUserWorkItem(state => {
                    var packageInfo = Application.Context.PackageManager.GetPackageInfo(Application.Context.PackageName, PackageInfoFlags.MetaData);

                    long versionCode;
                    if (Build.VERSION.SdkInt >= BuildVersionCodes.P)
                    {
                        versionCode = packageInfo.LongVersionCode;
                    }
                    else
                    {
                        versionCode = packageInfo.VersionCode;
                    }

                    var packageName = packageInfo.PackageName;
                    var versionName = packageInfo.VersionName;
                    var prefs       = Application.Context.GetSharedPreferences(KeyGroupName, FileCreationMode.Private);

                    try {
                        var storedVersionName = prefs.GetString(AppVersionNameKey, string.Empty);
                        var storedVersionCode = prefs.GetString(AppVersionCodeKey, string.Empty);
                        var storedPackageName = prefs.GetString(AppVersionPackageNameKey, string.Empty);

                        if (resetToken || (!string.IsNullOrEmpty(storedPackageName) && (!storedPackageName.Equals(packageName, StringComparison.CurrentCultureIgnoreCase) || !storedVersionName.Equals(versionName, StringComparison.CurrentCultureIgnoreCase) || !storedVersionCode.Equals($"{versionCode}", StringComparison.CurrentCultureIgnoreCase))))
                        {
                            CleanUp(false);
                        }
                    } catch (Exception ex) {
                        _onNotificationError?.Invoke(CrossFirebaseEssentials.Notifications, new FirebasePushNotificationErrorEventArgs(FirebasePushNotificationErrorType.UnregistrationFailed, ex.ToString()));
                    } finally {
                        var editor = prefs.Edit();
                        editor.PutString(AppVersionNameKey, $"{versionName}");
                        editor.PutString(AppVersionCodeKey, $"{versionCode}");
                        editor.PutString(AppVersionPackageNameKey, $"{packageName}");
                        editor.Commit();
                    }

                    CrossFirebaseEssentials.Notifications.RegisterForPushNotifications();
                });
            }

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O && createDefaultNotificationChannel)
            {
                // Create channel to show notifications.
                string channelId   = DefaultNotificationChannelId;
                string channelName = DefaultNotificationChannelName;
                NotificationManager notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);

                Android.Net.Uri defaultSoundUri = SoundUri != null ? SoundUri : RingtoneManager.GetDefaultUri(RingtoneType.Notification);
                AudioAttributes attributes      = new AudioAttributes.Builder()
                                                  .SetContentType(AudioContentType.Sonification)
                                                  .SetUsage(AudioUsageKind.Notification)
                                                  .Build();

                NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, DefaultNotificationChannelImportance);
                notificationChannel.EnableLights(true);
                notificationChannel.SetSound(defaultSoundUri, attributes);

                notificationManager.CreateNotificationChannel(notificationChannel);
            }

            System.Diagnostics.Debug.WriteLine(CrossFirebaseEssentials.Notifications.Token);
        }
 public Task <DataItemBuffer> GetDataItemsAsync(Android.Net.Uri p0, int p1)
 {
     return(GetDataItems(p0, p1).AsAsync <DataItemBuffer> ());
 }
Ejemplo n.º 22
0
 public static void start(Context context, String filePath) {
     Intent intent = new Intent(context, typeof(ReadCHMActivity));
     intent.SetAction(Intent.ActionView);
     intent.SetData(Uri.FromFile(new Java.IO.File(filePath)));
     context.StartActivity(intent);
 }
 public Task SendFileAsync(IChannel p0, Android.Net.Uri p1, long p2, long p3)
 {
     return(SendFile(p0, p1, p2, p3).AsAsync());
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Signals event that file picking has finished
 /// </summary>
 /// <param name="args">file picker event args</param>
 private static void OnFolderPicked(Android.Net.Uri args)
 {
     FolderPicked?.Invoke(null, args);
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Gets the media file asynchronous.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="requestCode">The request code.</param>
        /// <param name="action">The action.</param>
        /// <param name="isPhoto">if set to <c>true</c> [is photo].</param>
        /// <param name="path">The path.</param>
        /// <param name="data">The data.</param>
        /// <returns>Task&lt;MediaPickedEventArgs&gt;.</returns>
        internal static Task <MediaPickedEventArgs> GetMediaFileAsync(Context context, int requestCode, string action,
                                                                      bool isPhoto, ref Uri path, Uri data)
        {
            Task <Tuple <string, bool> > pathFuture;
            Action <bool> dispose      = null;
            string        originalPath = null;

            if (action != Intent.ActionPick)
            {
                originalPath = path.Path;

                // Not all camera apps respect EXTRA_OUTPUT, some will instead
                // return a content or file uri from data.
                if (data != null && data.Path != originalPath)
                {
                    originalPath = data.ToString();
                    var currentPath = path.Path;

                    pathFuture = TryMoveFileAsync(context, data, path, isPhoto).ContinueWith(t =>
                                                                                             new Tuple <string, bool>(t.Result ? currentPath : null, false));
                }
                else
                {
                    pathFuture = TaskUtils.TaskFromResult(new Tuple <string, bool>(path.Path, false));
                }
            }
            else if (data != null)
            {
                originalPath = data.ToString();
                path         = data;
                pathFuture   = GetFileForUriAsync(context, path, isPhoto);
            }
            else
            {
                pathFuture = TaskUtils.TaskFromResult <Tuple <string, bool> >(null);
            }

            return(pathFuture.ContinueWith(t =>
            {
                string resultPath = t.Result.Item1;
                if (resultPath != null && File.Exists(t.Result.Item1))
                {
                    if (t.Result.Item2)
                    {
                        dispose = d => File.Delete(resultPath);
                    }

                    var mf = new MediaFile(resultPath, () => File.OpenRead(t.Result.Item1), dispose);

                    return new MediaPickedEventArgs(requestCode, false, mf);
                }
                return new MediaPickedEventArgs(requestCode, new MediaFileNotFoundException(originalPath));
            }));
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Called when the activity is starting.
        /// </summary>
        /// <param name="savedInstanceState">If the activity is being re-initialized after
        /// previously being shut down then this Bundle contains the data it most
        /// recently supplied in <c><see cref="M:Android.App.Activity.OnSaveInstanceState(Android.OS.Bundle)" /></c>.  <format type="text/html"><b><i>Note: Otherwise it is null.</i></b></format></param>
        /// <since version="Added in API level 1" />
        /// <altmember cref="M:Android.App.Activity.OnStart" />
        /// <altmember cref="M:Android.App.Activity.OnSaveInstanceState(Android.OS.Bundle)" />
        /// <altmember cref="M:Android.App.Activity.OnRestoreInstanceState(Android.OS.Bundle)" />
        /// <altmember cref="M:Android.App.Activity.OnPostCreate(Android.OS.Bundle)" />
        /// <remarks><para tool="javadoc-to-mdoc">Called when the activity is starting.  This is where most initialization
        /// should go: calling <c><see cref="M:Android.App.Activity.SetContentView(System.Int32)" /></c> to inflate the
        /// activity's UI, using <c><see cref="M:Android.App.Activity.FindViewById(System.Int32)" /></c> to programmatically interact
        /// with widgets in the UI, calling
        /// <c><see cref="M:Android.App.Activity.ManagedQuery(Android.Net.Uri, System.String[], System.String[], System.String[], System.String[])" /></c> to retrieve
        /// cursors for data being displayed, etc.
        /// </para>
        /// <para tool="javadoc-to-mdoc">You can call <c><see cref="M:Android.App.Activity.Finish" /></c> from within this function, in
        /// which case onDestroy() will be immediately called without any of the rest
        /// of the activity lifecycle (<c><see cref="M:Android.App.Activity.OnStart" /></c>, <c><see cref="M:Android.App.Activity.OnResume" /></c>,
        /// <c><see cref="M:Android.App.Activity.OnPause" /></c>, etc) executing.
        /// </para>
        /// <para tool="javadoc-to-mdoc">
        ///   <i>Derived classes must call through to the super class's
        /// implementation of this method.  If they do not, an exception will be
        /// thrown.</i>
        /// </para>
        /// <para tool="javadoc-to-mdoc">
        ///   <format type="text/html">
        ///     <a href="http://developer.android.com/reference/android/app/Activity.html#onCreate(android.os.Bundle)" target="_blank">[Android Documentation]</a>
        ///   </format>
        /// </para></remarks>
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            var b = (savedInstanceState ?? Intent.Extras);

            var ran = b.GetBoolean("ran", false);

            _title       = b.GetString(MediaStore.MediaColumns.Title);
            _description = b.GetString(MediaStore.Images.ImageColumns.Description);

            _tasked = b.GetBoolean(ExtraTasked);
            _id     = b.GetInt(ExtraId, 0);
            _type   = b.GetString(ExtraType);

            if (_type == "image/*")
            {
                _isPhoto = true;
            }

            _action = b.GetString(ExtraAction);
            Intent pickIntent = null;

            try
            {
                pickIntent = new Intent(_action);
                if (_action == Intent.ActionPick)
                {
                    pickIntent.SetType(_type);
                }
                else
                {
                    if (!_isPhoto)
                    {
                        _seconds = b.GetInt(MediaStore.ExtraDurationLimit, 0);
                        if (_seconds != 0)
                        {
                            pickIntent.PutExtra(MediaStore.ExtraDurationLimit, _seconds);
                        }
                    }

                    _quality = (VideoQuality)b.GetInt(MediaStore.ExtraVideoQuality, (int)VideoQuality.High);
                    pickIntent.PutExtra(MediaStore.ExtraVideoQuality, GetVideoQuality(_quality));

                    if (!ran)
                    {
                        _path = GetOutputMediaFile(this, b.GetString(ExtraPath), _title, _isPhoto);

                        Touch();
                        pickIntent.PutExtra(MediaStore.ExtraOutput, _path);
                    }
                    else
                    {
                        _path = Uri.Parse(b.GetString(ExtraPath));
                    }
                }

                if (!ran)
                {
                    if (global::Android.OS.Build.VERSION.Release == "6.0")
                    {
                        if (CheckSelfPermission(Manifest.Permission.Camera) != Android.Content.PM.Permission.Granted)
                        {
                            RequestPermissions(new string[] { Manifest.Permission.Camera }, 1);
                        }
                    }
                    StartActivityForResult(pickIntent, _id);
                }
            }
            catch (Exception ex)
            {
                RaiseOnMediaPicked(new MediaPickedEventArgs(_id, ex));
            }
            finally
            {
                if (pickIntent != null)
                {
                    pickIntent.Dispose();
                }
            }
        }
Ejemplo n.º 27
0
        public static string ToPhysicalPath(this Uri uri, Context ctx)
        {
            var isKitkat = Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat;

            var isDocumentUri = DocumentsContract.IsDocumentUri(ctx, uri);
            var isTreeUri     = DocumentsContract.IsTreeUri(uri);

            if (isKitkat && (isDocumentUri || isTreeUri))
            {
                var rootUri = isDocumentUri
                    ? DocumentsContract.GetDocumentId(uri)
                    : DocumentsContract.GetTreeDocumentId(uri);

                if (uri.Authority == "com.android.localstorage.documents")
                {
                    return(rootUri);
                }

                if (uri.Authority == "com.android.externalstorage.documents")
                {
                    var splitDocumentId = rootUri.Split(':');
                    var type            = splitDocumentId[0];

                    if (string.Compare(type, "primary", StringComparison.InvariantCultureIgnoreCase) == 0)
                    {
                        return(Path.Combine(Android.OS.Environment.ExternalStorageDirectory.Path, splitDocumentId[1]));
                    }

                    // Handle non-primary
                    //! TODO: This is absolutely disgusting but android offers no easy way to obtain a path to a directory from an Uri to a directory.
                    //! I'm not even sure this is portable.
                    var contentUri = MediaStore.Files.GetContentUri(type);
                    var cursor     = ctx.ContentResolver.Query(contentUri, null, null, null, null);
                    if (cursor != null && cursor.MoveToFirst())
                    {
                        var path = cursor.GetString(0);
                        cursor.Close();
                        return(path);
                    }
                    else
                    {
                        return("/storage/" + rootUri.Replace(':', '/'));
                    }

                    return(contentUri.ToPhysicalPath(ctx));
                }

                if (uri.Authority == "com.android.providers.downloads.documents")
                {
                    var contentUri = ContentUris.WithAppendedId(Uri.Parse("content://downloads/public_downloads"), long.Parse(rootUri));

                    return(ctx.GetDataColumn(contentUri, MediaStore.MediaColumns.Data, null, null));
                }

                if (uri.Authority == "com.android.providers.media.documents")
                {
                    var splitDocumentId = rootUri.Split(':');
                    var type            = splitDocumentId[0];

                    Uri contentUri = null;

                    if ("image" == type)
                    {
                        contentUri = MediaStore.Images.Media.ExternalContentUri;
                    }
                    else if ("video" == type)
                    {
                        contentUri = MediaStore.Video.Media.ExternalContentUri;
                    }
                    else if ("audio" == type)
                    {
                        contentUri = MediaStore.Audio.Media.ExternalContentUri;
                    }

                    return(ctx.GetDataColumn(contentUri, MediaStore.MediaColumns.Data, "_id?=", splitDocumentId[1]));
                }
            }
            // MediaStore and general
            else if (uri.Scheme == "content")
            {
                if (uri.Authority == "com.google.android.apps.photos.content")
                {
                    return(uri.LastPathSegment);
                }

                return(ctx.GetDataColumn(uri, MediaStore.MediaColumns.Data, null, null));
            }
            else if (uri.Scheme == "file")
            {
                return(uri.Path);
            }

            return("");
        }
Ejemplo n.º 28
0
        static Intent CreateIntent(string body, List <string> recipients)
        {
            Intent intent = null;

            body = body ?? string.Empty;

            if (Platform.HasApiLevel(BuildVersionCodes.Kitkat) && recipients.All(x => string.IsNullOrWhiteSpace(x)))
            {
                var packageName = Telephony.Sms.GetDefaultSmsPackage(Platform.AppContext);
                if (!string.IsNullOrWhiteSpace(packageName))
                {
                    intent = new Intent(Intent.ActionSend);
                    intent.SetType("text/plain");
                    intent.PutExtra(Intent.ExtraText, body);
                    intent.SetPackage(packageName);

                    return(intent);
                }
            }

            // Fall back to normal send
            intent = new Intent(Intent.ActionView);

            if (!string.IsNullOrWhiteSpace(body))
            {
                intent.PutExtra("sms_body", body);
            }

            var recipienturi = string.Join(smsRecipientSeparator, recipients.Select(r => AndroidUri.Encode(r)));

            var uri = AndroidUri.Parse($"smsto:{recipienturi}");

            intent.SetData(uri);

            return(intent);
        }
Ejemplo n.º 29
0
        public override void OnActivityResult(int requestCode, int resultCode, Intent data)
        {
            try
            {
                if (Build.VERSION.SdkInt >= Build.VERSION_CODES.M)
                {
                    if (Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this.Activity, Manifest.Permission.WriteExternalStorage) != (int)Permission.Granted)
                    {
                        Android.Support.V4.App.ActivityCompat.RequestPermissions(this.Activity, new String[] { Manifest.Permission.WriteExternalStorage, Manifest.Permission.ReadExternalStorage }, 53);
                    }
                    else
                    {
                        if (requestCode == 102)
                        {
                            Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
                            Uri    contentUri      = Uri.FromFile(_file);
                            mediaScanIntent.SetData(contentUri);
                            this.Activity.SendBroadcast(mediaScanIntent);
                            int height = profile_image0.Height;
                            int width  = Resources.DisplayMetrics.WidthPixels;
                            using (Android.Graphics.Bitmap bitmap = _file.Path.LoadAndResizeBitmap(width, height))
                            {
                                profile_image0.RecycleBitmap();
                                profile_image0.SetImageBitmap(bitmap);

                                try
                                {
                                    this.SetProfileImageToNavMenuHeader(this.Activity, bitmap);
                                }
                                catch { }

                                _profilepicbase64 = BitmapHelpers.BitmapToBase64(bitmap);
                                try
                                {
                                    objdb = new DBaseOperations();
                                    var lstu = objdb.selectTable();
                                    if (lstu != null && lstu.Count > default(int))
                                    {
                                        var uobj = lstu.FirstOrDefault();
                                        objdb.updateTable(new UserLoginInfo()
                                        {
                                            Id = uobj.Id, EmailId = uobj.EmailId, GoodName = uobj.GoodName, Password = uobj.Password, IsAdmin = uobj.IsAdmin, AuthToken = uobj.AuthToken, ProfilePicture = _profilepicbase64
                                        });
                                    }
                                }
                                catch { }
                            }
                        }
                    }
                }
                else
                {
                    if (requestCode == 102)
                    {
                        Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
                        Uri    contentUri      = Uri.FromFile(_file);
                        mediaScanIntent.SetData(contentUri);
                        this.Activity.SendBroadcast(mediaScanIntent);
                        int height = profile_image0.Height;
                        int width  = Resources.DisplayMetrics.WidthPixels;
                        using (Android.Graphics.Bitmap bitmap = _file.Path.LoadAndResizeBitmap(width, height))
                        {
                            profile_image0.RecycleBitmap();
                            profile_image0.SetImageBitmap(bitmap);

                            try
                            {
                                this.SetProfileImageToNavMenuHeader(this.Activity, bitmap);
                            }
                            catch { }

                            _profilepicbase64 = BitmapHelpers.BitmapToBase64(bitmap);
                            try
                            {
                                objdb = new DBaseOperations();
                                var lstu = objdb.selectTable();
                                if (lstu != null && lstu.Count > default(int))
                                {
                                    var uobj = lstu.FirstOrDefault();
                                    objdb.updateTable(new UserLoginInfo()
                                    {
                                        Id = uobj.Id, EmailId = uobj.EmailId, GoodName = uobj.GoodName, Password = uobj.Password, IsAdmin = uobj.IsAdmin, AuthToken = uobj.AuthToken, ProfilePicture = _profilepicbase64
                                    });
                                }
                            }
                            catch { }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.Activity.RunOnUiThread(() =>
                {
                    Android.App.AlertDialog.Builder alertDiag = new Android.App.AlertDialog.Builder(this.Activity);
                    alertDiag.SetTitle(Resource.String.DialogHeaderError);
                    alertDiag.SetMessage(ex.Message);
                    alertDiag.SetIcon(Resource.Drawable.alert);
                    alertDiag.SetPositiveButton(Resource.String.DialogButtonOk, (senderAlert, args) =>
                    {
                    });
                    Dialog diag = alertDiag.Create();
                    diag.Show();
                    diag.SetCanceledOnTouchOutside(false);
                });
            }
        }
Ejemplo n.º 30
0
 public override void initToolBar() {
     chmFilePath = Uri.Decode(Intent.DataString.Replace("file://", ""));
     chmFileName = chmFilePath.Substring(chmFilePath.LastIndexOf("/") + 1, chmFilePath.LastIndexOf("."));
     mCommonToolbar.Title = (chmFileName);
     mCommonToolbar.SetNavigationIcon(Resource.Drawable.ab_back);
 }
        async Task ExecuteShareBlobCommandAsync()
        {
            if (IsBusy)
            {
                return;
            }

            App.Logger.Track(AppEvent.ShareBlob.ToString());


            if (HasBlobBeenSaved)
            {
                try
                {
#if __ANDROID__
                    string          mimeType = MediaTypeMapper.GetMimeType(BlobFileExtension);
                    Android.Net.Uri uri      = Android.Net.Uri.Parse("file:///" + GetBlobFilePath());
                    Intent          intent   = new Intent(Intent.ActionView);
                    intent.SetDataAndType(uri, mimeType);
                    intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
                    try
                    {
                        Xamarin.Forms.Forms.Context.StartActivity(intent);
                    }
                    catch (Exception ex)
                    {
                        MessagingService.Current.SendMessage <MessagingServiceAlert>(MessageKeys.Message, new MessagingServiceAlert
                        {
                            Title   = "Unable to Share",
                            Message = "No applications available to open files of type " + BlobFileExtension,
                            Cancel  = "OK"
                        });
                        throw ex;
                    }
#elif __IOS__
                    var extensionClassRef = new NSString(UTType.TagClassFilenameExtension);
                    var mimeTypeClassRef  = new NSString(UTType.TagClassMIMEType);

                    var uti = NativeTools.UTTypeCreatePreferredIdentifierForTag(extensionClassRef.Handle, new NSString(BlobFileExtension).Handle, IntPtr.Zero);
                    //TODO: open file based off of type
                    var fi   = NSData.FromFile(GetBlobFilePath());
                    var item = NSObject.FromObject(fi);


                    var activityItems = new[] { item };



                    var activityController = new UIActivityViewController(activityItems, null);

                    var topController = UIApplication.SharedApplication.KeyWindow.RootViewController;

                    while (topController.PresentedViewController != null)
                    {
                        topController = topController.PresentedViewController;
                    }

                    topController.PresentViewController(activityController, true, () => { });
#endif
                }
                catch (Exception ex)
                {
                    App.Logger.Report(ex, Severity.Error);
                }
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Gets the file for URI asynchronous.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="uri">The URI.</param>
        /// <param name="isPhoto">if set to <c>true</c> [is photo].</param>
        /// <returns>Task&lt;Tuple&lt;System.String, System.Boolean&gt;&gt;.</returns>
        internal static Task <Tuple <string, bool> > GetFileForUriAsync(Context context, Uri uri, bool isPhoto)
        {
            var tcs = new TaskCompletionSource <Tuple <string, bool> >();

            var fixedUri = FixUri(uri.Path);

            if (fixedUri != null)
            {
                uri = fixedUri;
            }

            if (uri.Scheme == "file")
            {
                tcs.SetResult(new Tuple <string, bool>(new System.Uri(uri.ToString()).LocalPath, false));
            }
            else if (uri.Scheme == "content")
            {
                Task.Factory.StartNew(() =>
                {
                    ICursor cursor = null;
                    try
                    {
                        cursor = context.ContentResolver.Query(uri, null, null, null, null);
                        if (cursor == null || !cursor.MoveToNext())
                        {
                            tcs.SetResult(new Tuple <string, bool>(null, false));
                        }
                        else
                        {
                            int column         = cursor.GetColumnIndex(MediaStore.MediaColumns.Data);
                            string contentPath = null;

                            if (column != -1)
                            {
                                contentPath = cursor.GetString(column);
                            }

                            bool copied = false;

                            // If they don't follow the "rules", try to copy the file locally
//							if (contentPath == null || !contentPath.StartsWith("file"))
//							{
//								copied = true;
//								Uri outputPath = GetOutputMediaFile(context, "temp", null, isPhoto);
//
//								try
//								{
//									using (Stream input = context.ContentResolver.OpenInputStream(uri))
//									using (Stream output = File.Create(outputPath.Path))
//										input.CopyTo(output);
//
//									contentPath = outputPath.Path;
//								}
//								catch (FileNotFoundException)
//								{
//									// If there's no data associated with the uri, we don't know
//									// how to open this. contentPath will be null which will trigger
//									// MediaFileNotFoundException.
//								}
//							}

                            tcs.SetResult(new Tuple <string, bool>(contentPath, copied));
                        }
                    }
                    finally
                    {
                        if (cursor != null)
                        {
                            cursor.Close();
                            cursor.Dispose();
                        }
                    }
                }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
            }
            else
            {
                tcs.SetResult(new Tuple <string, bool>(null, false));
            }

            return(tcs.Task);
        }
Ejemplo n.º 33
0
 public BitmapWorkerTask(ContentResolver cr, Android.Net.Uri uri)
 {
     uriReference = uri;
     resolver     = cr;
 }
Ejemplo n.º 34
0
 /// <summary>
 /// Gets the local path.
 /// </summary>
 /// <param name="uri">The URI.</param>
 /// <returns>System.String.</returns>
 private static string GetLocalPath(Uri uri)
 {
     return(new System.Uri(uri.ToString()).LocalPath);
 }
Ejemplo n.º 35
0
 public override int Delete(Android.Net.Uri uri, string selection, string[] selectionArgs)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 36
0
        public void OnLongPress(MotionEvent e)
        {
            if (!HasAnyDragGestures())
            {
                return;
            }

            SendEventArgs <DragGestureRecognizer>(rec =>
            {
                if (!rec.CanDrag)
                {
                    return;
                }

                var element = GetView();
                // TODO MAUI FIX FOR COMPAT
                //var renderer = AppCompat.Platform.GetRenderer(element);
                var v = (AView)element.Handler.PlatformView;

                if (v.Handle == IntPtr.Zero)
                {
                    return;
                }

                var args = rec.SendDragStarting(element);

                if (args.Cancel)
                {
                    return;
                }

                CustomLocalStateData customLocalStateData = new CustomLocalStateData();
                customLocalStateData.DataPackage          = args.Data;


                // TODO MAUI
                string clipDescription  = String.Empty;               //AutomationPropertiesProvider.ConcatenateNameAndHelpText(element) ?? String.Empty;
                ClipData.Item item      = null;
                List <string> mimeTypes = new List <string>();

                if (!args.Handled)
                {
                    if (args.Data.Image != null)
                    {
                        mimeTypes.Add("image/jpeg");
                        item = ConvertToClipDataItem(args.Data.Image, mimeTypes);
                    }
                    else
                    {
                        string text = clipDescription ?? args.Data.Text;
                        if (Uri.TryCreate(text, UriKind.Absolute, out _))
                        {
                            item = new ClipData.Item(AUri.Parse(text));
                            mimeTypes.Add(ClipDescription.MimetypeTextUrilist);
                        }
                        else
                        {
                            item = new ClipData.Item(text);
                            mimeTypes.Add(ClipDescription.MimetypeTextPlain);
                        }
                    }
                }

                var dataPackage        = args.Data;
                ClipData.Item userItem = null;
                if (dataPackage.Image != null)
                {
                    userItem = ConvertToClipDataItem(dataPackage.Image, mimeTypes);
                }

                if (dataPackage.Text != null)
                {
                    userItem = new ClipData.Item(dataPackage.Text);
                }

                if (item == null)
                {
                    item     = userItem;
                    userItem = null;
                }

                ClipData data = new ClipData(clipDescription, mimeTypes.ToArray(), item);

                if (userItem != null)
                {
                    data.AddItem(userItem);
                }

                var dragShadowBuilder = new AView.DragShadowBuilder(v);

                customLocalStateData.SourcePlatformView = v;
                customLocalStateData.SourceElement      = element;

                if (PlatformVersion.IsAtLeast(24))
                {
                    v.StartDragAndDrop(data, dragShadowBuilder, customLocalStateData, (int)ADragFlags.Global | (int)ADragFlags.GlobalUriRead);
                }
                else
#pragma warning disable CS0618 // Type or member is obsolete
                {
                    v.StartDrag(data, dragShadowBuilder, customLocalStateData, (int)ADragFlags.Global | (int)ADragFlags.GlobalUriRead);
                }
#pragma warning restore CS0618 // Type or member is obsolete
            });
        }
 public Task SendFileAsync(IChannel p0, Android.Net.Uri p1)
 {
     return(SendFile(p0, p1).AsAsync());
 }
Ejemplo n.º 38
0
        private void InitBindings()
        {
            Bindings.Add(
                this.SetBinding(() => ViewModel.CurrentStatus,
                                () => MainPageCurrentStatus.Text));


            Bindings.Add(
                this.SetBinding(() => ViewModel.RefreshButtonVisibility,
                                () => MainPageRefreshButton.Visibility).ConvertSourceToTarget(Converters.BoolToVisibility));
            MainPageRefreshButton.Click += (sender, args) => ViewModel.RefreshDataCommand.Execute(null);

            Bindings.Add(
                this.SetBinding(() => ViewModel.SearchToggleVisibility,
                                () => MainPageSearchView.Visibility).ConvertSourceToTarget(Converters.BoolToVisibility));
            Bindings.Add(
                this.SetBinding(() => ViewModel.SearchInputVisibility).WhenSourceChanges(() =>
            {
                MainPageSearchView.Iconified = !ViewModel.SearchInputVisibility;
                if (ViewModel.SearchInputVisibility)
                {
                    MainPageSearchView.SetQuery(ViewModel.CurrentSearchQuery, false);
                }
                MainPageSearchView.ClearFocus();
            }));


            Bindings.Add(this.SetBinding(() => ViewModel.CurrentStatusSub).WhenSourceChanges(() =>
            {
                MainPageCurrentSatusSubtitle.Text = ViewModel.CurrentStatusSub;
                if (string.IsNullOrEmpty(ViewModel.CurrentStatusSub))
                {
                    MainPageCurrentSatusSubtitle.Visibility = ViewStates.Gone;
                    MainPageCurrentStatus.SetMaxLines(2);
                }
                else
                {
                    MainPageCurrentSatusSubtitle.Visibility = ViewStates.Visible;
                    MainPageCurrentStatus.SetMaxLines(1);
                }
            }));

            _searchFrame = MainPageSearchView.FindViewById(Resource.Id.search_edit_frame);

            Bindings.Add(this.SetBinding(() => ViewModel.SearchToggleLock).WhenSourceChanges(
                             () =>
            {
                if (ViewModel.SearchToggleLock)
                {
                    MainPageSearchView.FindViewById(Resource.Id.search_close_btn).Alpha     = 0;
                    MainPageSearchView.FindViewById(Resource.Id.search_close_btn).Clickable = false;
                    if (ViewModel.CurrentMainPage == PageIndex.PageSearch)
                    {
                        InputMethodManager imm = (InputMethodManager)GetSystemService(Context.InputMethodService);
                        imm.ToggleSoftInput(ShowFlags.Forced, HideSoftInputFlags.NotAlways);
                    }
                }
                else
                {
                    MainPageSearchView.FindViewById(Resource.Id.search_close_btn).Alpha     = 1;
                    MainPageSearchView.FindViewById(Resource.Id.search_close_btn).Clickable = true;
                }
            }));

            //MainPageSearchView.LayoutChange += MainPageSearchViewOnLayoutChange;

            //var padding = (int)(11*Resources.DisplayMetrics.Density);
            //searchBtn.SetScaleType(ImageView.ScaleType.FitEnd);
            //searchBtn.SetPadding(padding, padding, padding, padding);
            var observer       = _searchFrame.ViewTreeObserver;
            var prevVisibility = _searchFrame.Visibility;

            observer.GlobalLayout += (sender, args) =>
            {
                if (prevVisibility == _searchFrame.Visibility)
                {
                    return;
                }
                prevVisibility = _searchFrame.Visibility;
                MainPageCurrentStatus.Visibility = Converters.VisibilityInverterConverter(_searchFrame.Visibility);
                var param = MainPageSearchView.LayoutParameters as LinearLayout.LayoutParams;
                Debug.WriteLine(_searchFrame.Visibility);
                if (_searchFrame.Visibility == ViewStates.Visible)
                {
                    var diff = ViewModel.SearchToggleStatus != true;
                    ViewModel.SearchToggleStatus = true;
                    param.Width = ViewGroup.LayoutParams.MatchParent;
                    param.SetMargins(0, 0, DimensionsHelper.DpToPx(20), 0);
                    param.Weight = 1;
                    if (diff)
                    {
                        MainPageSearchView.RequestFocusFromTouch();
                        InputMethodManager imm = (InputMethodManager)GetSystemService(Context.InputMethodService);
                        imm.ToggleSoftInput(ShowFlags.Forced, HideSoftInputFlags.None);
                    }
                }
                else
                {
                    var diff = ViewModel.SearchToggleStatus != false;
                    ViewModel.SearchToggleStatus = false;
                    param.Width = (int)DimensionsHelper.DpToPx(50);
                    param.SetMargins(0, 0, 0, 0);
                    param.Weight = 0;
                    if (diff)
                    {
                        InputMethodManager imm = (InputMethodManager)GetSystemService(Context.InputMethodService);
                        imm.HideSoftInputFromWindow(MainPageSearchView.WindowToken, HideSoftInputFlags.None);
                    }
                }
            };

            _searchSuggestionAdapter = new SimpleCursorAdapter(this, Resource.Layout.SuggestionItem,
                                                               null, new string[] { "hint" }, new int[]
            {
                Resource.Id.SuggestionItemTextView
            });

            //
            MainPageStatusContainer.SetOnClickListener(new OnClickListener(view =>
            {
                if (ViewModel.CurrentMainPage == PageIndex.PageAnimeList)
                {
                    if (ViewModelLocator.AnimeList.WorkMode == AnimeListWorkModes.SeasonalAnime)
                    {
                        _upperFilterMenu = FlyoutMenuBuilder.BuildGenericFlyout(this, MainPageCurrentStatus,
                                                                                ViewModelLocator.AnimeList.SeasonSelection.Select(season => season.Name).ToList(),
                                                                                OnUpperStatusSeasonSelected);
                    }
                    else
                    {
                        _upperFilterMenu = AnimeListPageFlyoutBuilder.BuildForAnimeStatusSelection(this, MainPageCurrentStatus,
                                                                                                   OnUpperFlyoutStatusChanged, (AnimeStatus)ViewModelLocator.AnimeList.CurrentStatus,
                                                                                                   ViewModelLocator.AnimeList.IsMangaWorkMode);
                    }

                    _upperFilterMenu.Show();
                }
            }));


            Bindings.Add(this.SetBinding(() => ViewModel.MediaElementVisibility)
                         .WhenSourceChanges(() =>
            {
                if (ViewModel.MediaElementVisibility)
                {
                    MainPageVideoViewContainer.Visibility = ViewStates.Visible;
                    MainPageVideoView.Visibility          = ViewStates.Visible;
                    MainUpperNavBar.Visibility            = ViewStates.Gone;
                    MainPageVideoView.SetZOrderOnTop(true);
                    _drawer?.DrawerLayout.SetDrawerLockMode(DrawerLayout.LockModeLockedClosed);
                }
                else
                {
                    MainPageVideoViewContainer.Visibility = ViewStates.Gone;
                    MainPageVideoView.Visibility          = ViewStates.Gone;
                    MainUpperNavBar.Visibility            = ViewStates.Visible;
                    MainPageVideoView.SetZOrderOnTop(false);
                    _drawer?.DrawerLayout.SetDrawerLockMode(DrawerLayout.LockModeUnlocked);
                    ViewModelLocator.NavMgr.ResetOneTimeOverride();
                }
            }));



            Bindings.Add(
                this.SetBinding(() => ViewModel.MediaElementSource).WhenSourceChanges(() =>
            {
                if (string.IsNullOrEmpty(ViewModel.MediaElementSource))
                {
                    return;
                }

                var mediaController = new MediaController(this);
                mediaController.SetAnchorView(MainPageVideoView);
                MainPageVideoView.SetMediaController(mediaController);
                MainPageVideoView.SetVideoURI(Uri.Parse(ViewModel.MediaElementSource));
                MainPageVideoView.RequestFocus();
            }));

            MainPageSearchView.SuggestionsAdapter = _searchSuggestionAdapter;
            MainPageSearchView.QueryTextChange   += MainPageSearchViewOnQueryTextChange;
            MainPageSearchView.QueryTextSubmit   += MainPageSearchViewOnQueryTextSubmit;
            MainPageSearchView.SuggestionClick   += MainPageSearchViewOnSuggestionClick;
            MainPageCloseVideoButton.Click       += MainPageCloseVideoButtonOnClick;
            MainPageCopyVideoLinkButton.Click    += MainPageCopyVideoLinkButtonOnClick;
            MainPageVideoView.Prepared           += MainPageVideoViewOnPrepared;
            MainPageSearchView.Visibility         = ViewStates.Visible;
            ((EditText)MainPageSearchView.FindViewById(Resource.Id.search_src_text)).SetTextColor(Color.White);


            MainPageHamburgerButton.Click += MainPageHamburgerButtonOnClick;
            ViewModel.PropertyChanged     += ViewModelOnPropertyChanged;
            BuildDrawer();
            _drawer.OnDrawerItemClickListener = new HamburgerItemClickListener(OnHamburgerItemClick);

            MainPageCloseVideoButton.SetZ(0);
            MainPageCopyVideoLinkButton.SetZ(0);
        }
 public Task AddListenerAsync(IOnMessageReceivedListener p0, Android.Net.Uri p1, int p2)
 {
     return(AddListener(p0, p1, p2).AsAsync());
 }
 public Task ReceiveFileAsync(IChannel p0, Android.Net.Uri p1, bool p2)
 {
     return(ReceiveFile(p0, p1, p2).AsAsync());
 }
Ejemplo n.º 41
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.l_ManagedCompany);


            _mDrawerLayout = FindViewById <DrawerLayout>(Resource.Id.drawer_layout);
            _mToolBar      = FindViewById <SupportToolBar>(Resource.Id.toolbar);
            _mLeftDrawer   = FindViewById <ListView>(Resource.Id.left_drawer);
            _mListViewl    = FindViewById <ListView>(Resource.Id.left_drawer);



            SetSupportActionBar(_mToolBar);
            _mDrawerToggle = new ActionBarDrawerToggle(
                this, _mDrawerLayout, Resource.String.openDrawer,
                Resource.String.closeDrawer
                );

            _mDrawerLayout.AddDrawerListener(_mDrawerToggle);
            SupportActionBar.SetHomeButtonEnabled(true);
            SupportActionBar.SetDisplayHomeAsUpEnabled(true);
            _mDrawerToggle.SyncState();


            _mItems = new List <string>();
            _mItems.Add("Школы");
            _mItems.Add("Почта, Банк");
            _mItems.Add("Транспорт");
            _mItems.Add("радио город Кудрово");
            _mItems.Add("Управляющие компании");
            _mItems.Add("Администрация Кудрово");
            _mItems.Add("Новости");

            var adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleListItem1, _mItems);

            _mListViewl.Adapter    = adapter;
            _mListViewl.ItemClick += mListViewl_ItemClick;

            _btn1 = FindViewById <Button>(Resource.Id.btn1);
            _btn2 = FindViewById <Button>(Resource.Id.btn2);
            _btn3 = FindViewById <Button>(Resource.Id.btn3);
            _btn4 = FindViewById <Button>(Resource.Id.btn4);
            _btn5 = FindViewById <Button>(Resource.Id.btn5);
            _btn6 = FindViewById <Button>(Resource.Id.btn6);
            _btn7 = FindViewById <Button>(Resource.Id.btn7);
            _btn8 = FindViewById <Button>(Resource.Id.btn8);
            _btn9 = FindViewById <Button>(Resource.Id.btn9);


            _btnTest        = FindViewById <Button>(Resource.Id.btnTest);
            _testEmail      = FindViewById <TextView>(Resource.Id.testEmail);
            _testScrollView = FindViewById <ScrollView>(Resource.Id.testScrollView);

            _scroll1 = FindViewById <ScrollView>(Resource.Id.scrol1);
            _scroll2 = FindViewById <ScrollView>(Resource.Id.scrol2);
            _scroll3 = FindViewById <ScrollView>(Resource.Id.scrol3);
            _scroll4 = FindViewById <ScrollView>(Resource.Id.scrol4);
            _scroll5 = FindViewById <ScrollView>(Resource.Id.scrol5);
            _scroll6 = FindViewById <ScrollView>(Resource.Id.scrol6);
            _scroll7 = FindViewById <ScrollView>(Resource.Id.scrol7);
            _scroll8 = FindViewById <ScrollView>(Resource.Id.scrol8);
            _scroll9 = FindViewById <ScrollView>(Resource.Id.scrol9);

            _telFlagman1  = FindViewById <TextView>(Resource.Id.telFlagman1);
            _telFlagman2  = FindViewById <TextView>(Resource.Id.telFlagman2);
            _emailFlagman = FindViewById <TextView>(Resource.Id.emailFlagman);
            _adresFlagman = FindViewById <TextView>(Resource.Id.adresFlagman);

            _tel7Stolic   = FindViewById <TextView>(Resource.Id.tel7Stolic);
            _email7Stolic = FindViewById <TextView>(Resource.Id.email7Stolic);
            _adres7Stolic = FindViewById <TextView>(Resource.Id.adres7Stolic);

            _telNachdom   = FindViewById <TextView>(Resource.Id.telNachdom);
            _emailNachdom = FindViewById <TextView>(Resource.Id.emailNachdom);
            _adresNachdom = FindViewById <TextView>(Resource.Id.adresNachdom);

            _telSodruzestvo   = FindViewById <TextView>(Resource.Id.telSodruzestvo);
            _emailSodruzestvo = FindViewById <TextView>(Resource.Id.emailSodruzestvo);
            _adresSodruzestvo = FindViewById <TextView>(Resource.Id.adresSodruzestvo);
            _paySodruzestvo   = FindViewById <TextView>(Resource.Id.paySodruzestvo);

            _tel14  = FindViewById <TextView>(Resource.Id.tel14);
            _tel24  = FindViewById <TextView>(Resource.Id.tel24);
            _adres4 = FindViewById <TextView>(Resource.Id.adres4);
            _email4 = FindViewById <TextView>(Resource.Id.email4);

            _telUut     = FindViewById <TextView>(Resource.Id.telUut);
            _emalUut    = FindViewById <TextView>(Resource.Id.emalUut);
            _adresUut   = FindViewById <TextView>(Resource.Id.adresUut);
            _privateUut = FindViewById <TextView>(Resource.Id.privateUut);
            _payUut     = FindViewById <TextView>(Resource.Id.payUut);

            _telService1    = FindViewById <TextView>(Resource.Id.telService1);
            _telService2    = FindViewById <TextView>(Resource.Id.telService2);
            _adresService   = FindViewById <TextView>(Resource.Id.adresService);
            _privateService = FindViewById <TextView>(Resource.Id.privateService);

            _telGrad1  = FindViewById <TextView>(Resource.Id.telGrad1);
            _telGrad2  = FindViewById <TextView>(Resource.Id.telGrad2);
            _telGrad3  = FindViewById <TextView>(Resource.Id.telGrad3);
            _adresGrad = FindViewById <TextView>(Resource.Id.adresGrad);
            _emailGrad = FindViewById <TextView>(Resource.Id.emailGrad);

            _telComfort     = FindViewById <TextView>(Resource.Id.telComfort);
            _adresComfort   = FindViewById <TextView>(Resource.Id.adresComfort);
            _emailComfort   = FindViewById <TextView>(Resource.Id.emailComfort);
            _privateComfort = FindViewById <TextView>(Resource.Id.privateComfort);


            _btn1.Click += _btn1_Click1;
            _btn2.Click += _btn2_Click2;
            _btn3.Click += _btn3_Click3;
            _btn4.Click += _btn4_Click4;
            _btn5.Click += _btn5_Click5;
            _btn6.Click += _btn6_Click6;
            _btn7.Click += _btn7_Click7;
            _btn8.Click += _btn8_Click8;
            _btn9.Click += _btn9_Click9;

            _btnTest.Click += _btnTest_Click;

            _telFlagman1.Click += delegate
            {
                var uri    = Uri.Parse("tel:" + GetString(Resource.String.StroylinkTel1));
                var intent = new Intent(Intent.ActionDial, uri);
                StartActivity(intent);
            };
            _telFlagman2.Click += delegate
            {
                var uri    = Uri.Parse("tel:" + GetString(Resource.String.StroylinkTel2));
                var intent = new Intent(Intent.ActionDial, uri);
                StartActivity(intent);
            };


            _testEmail.Click += delegate
            {
                var email = new Intent(Intent.ActionSend);
                email.PutExtra(Intent.ExtraEmail, new string[] { "*****@*****.**" });

                email.SetType("message/rfc822");
                StartActivity(email);
            };


            _emailFlagman.Click += delegate
            {
                var email = new Intent(Intent.ActionSend);
                email.PutExtra(Intent.ExtraEmail, new[] { GetString(Resource.String.StroylinkEmail) });

                email.SetType("message/rfc822");
                StartActivity(email);
            };

            _adresFlagman.Click += delegate
            {
                var geoUri    = Uri.Parse("geo:60.013529, 30.312802");
                var mapIntent = new Intent(Intent.ActionView, geoUri);
                StartActivity(mapIntent);
            };

            _tel7Stolic.Click += delegate
            {
                var uri    = Uri.Parse("tel:" + GetString(Resource.String.tel7Stolic));
                var intent = new Intent(Intent.ActionDial, uri);
                StartActivity(intent);
            };

            _email7Stolic.Click += delegate
            {
                var email = new Intent(Intent.ActionSend);
                email.PutExtra(Intent.ExtraEmail, new[] { GetString(Resource.String.email7Stolic) });

                email.SetType("message/rfc822");
                StartActivity(email);
            };

            _adres7Stolic.Click += delegate
            {
                var geoUri    = Uri.Parse("geo:60.025740, 30.621812");
                var mapIntent = new Intent(Intent.ActionView, geoUri);
                StartActivity(mapIntent);
            };

            _telNachdom.Click += delegate
            {
                var uri    = Uri.Parse("tel:" + GetString(Resource.String.telNachdom));
                var intent = new Intent(Intent.ActionDial, uri);
                StartActivity(intent);
            };

            _emailNachdom.Click += delegate
            {
                var email = new Intent(Intent.ActionSend);
                email.PutExtra(Intent.ExtraEmail, new[] { GetString(Resource.String.emailNachdom) });

                email.SetType("message/rfc822");
                StartActivity(email);
            };


            _adresNachdom.Click += delegate
            {
                var geoUri    = Uri.Parse("geo:59.970140, 30.394220");
                var mapIntent = new Intent(Intent.ActionView, geoUri);
                StartActivity(mapIntent);
            };

            _telSodruzestvo.Click += delegate
            {
                var uri    = Uri.Parse("tel:" + GetString(Resource.String.telSodruzestvo));
                var intent = new Intent(Intent.ActionDial, uri);
                StartActivity(intent);
            };

            _emailSodruzestvo.Click += delegate
            {
                var email = new Intent(Intent.ActionSend);
                email.PutExtra(Intent.ExtraEmail, new[] { GetString(Resource.String.emailSodruzestvo) });

                email.SetType("message/rfc822");
                StartActivity(email);
            };

            _adresSodruzestvo.Click += delegate
            {
                var geoUri    = Uri.Parse("geo:59.831827, 30.194503");
                var mapIntent = new Intent(Intent.ActionView, geoUri);
                StartActivity(mapIntent);
            };

            _paySodruzestvo.Click += delegate
            {
                var uri    = Uri.Parse("https://pay.pscb.ru/list/?lf=uks");
                var intent = new Intent(Intent.ActionView, uri);
                StartActivity(intent);
            };

            _tel14.Click += delegate
            {
                var uri    = Uri.Parse("tel:" + GetString(Resource.String.tel14));
                var intent = new Intent(Intent.ActionDial, uri);
                StartActivity(intent);
            };

            _tel24.Click += delegate
            {
                var uri    = Uri.Parse("tel:" + GetString(Resource.String.tel24));
                var intent = new Intent(Intent.ActionDial, uri);
                StartActivity(intent);
            };

            _adres4.Click += delegate
            {
                var geoUri    = Uri.Parse("geo:60.068014, 30.403911");
                var mapIntent = new Intent(Intent.ActionView, geoUri);
                StartActivity(mapIntent);
            };

            _email4.Click += delegate
            {
                var email = new Intent(Intent.ActionSend);
                email.PutExtra(Intent.ExtraEmail, new[] { GetString(Resource.String.email4) });

                email.SetType("message/rfc822");
                StartActivity(email);
            };

            _telUut.Click += delegate
            {
                var uri    = Uri.Parse("tel:" + GetString(Resource.String.telUut));
                var intent = new Intent(Intent.ActionDial, uri);
                StartActivity(intent);
            };

            _emalUut.Click += delegate
            {
                var email = new Intent(Intent.ActionSend);
                email.PutExtra(Intent.ExtraEmail, new[] { GetString(Resource.String.emalUut) });

                email.SetType("message/rfc822");
                StartActivity(email);
            };

            _adresUut.Click += delegate
            {
                var geoUri    = Uri.Parse("geo:59.903213, 30.398065");
                var mapIntent = new Intent(Intent.ActionView, geoUri);
                StartActivity(mapIntent);
            };

            _privateUut.Click += delegate
            {
                var uri    = Uri.Parse("http://ae-comfort.ru/User/LogOn");
                var intent = new Intent(Intent.ActionView, uri);
                StartActivity(intent);
            };

            _payUut.Click += delegate
            {
                var uri    = Uri.Parse("https://pay.mcplat.ru/article/ukUyut");
                var intent = new Intent(Intent.ActionView, uri);
                StartActivity(intent);
            };

            _telService1.Click += delegate
            {
                var uri    = Uri.Parse("tel:" + GetString(Resource.String.telService1));
                var intent = new Intent(Intent.ActionDial, uri);
                StartActivity(intent);
            };

            _telService2.Click += delegate
            {
                var uri    = Uri.Parse("tel:" + GetString(Resource.String.telService2));
                var intent = new Intent(Intent.ActionDial, uri);
                StartActivity(intent);
            };

            _adresService.Click += delegate
            {
                var geoUri    = Uri.Parse("geo:59.905274, 30.511037");
                var mapIntent = new Intent(Intent.ActionView, geoUri);
                StartActivity(mapIntent);
            };

            _privateService.Click += delegate
            {
                var uri    = Uri.Parse("https://lkabinet.online/login.aspx");
                var intent = new Intent(Intent.ActionView, uri);
                StartActivity(intent);
            };

            _telGrad1.Click += delegate
            {
                var uri    = Uri.Parse("tel:" + GetString(Resource.String.telGrad1));
                var intent = new Intent(Intent.ActionDial, uri);
                StartActivity(intent);
            };
            _telGrad2.Click += delegate
            {
                var uri    = Uri.Parse("tel:" + GetString(Resource.String.telGrad2));
                var intent = new Intent(Intent.ActionDial, uri);
                StartActivity(intent);
            };

            _telGrad3.Click += delegate
            {
                var uri    = Uri.Parse("tel:" + GetString(Resource.String.telGrad3));
                var intent = new Intent(Intent.ActionDial, uri);
                StartActivity(intent);
            };

            _emailGrad.Click += delegate
            {
                var email = new Intent(Intent.ActionSend);
                email.PutExtra(Intent.ExtraEmail, new[] { GetString(Resource.String.emailGrad) });

                email.SetType("message/rfc822");
                StartActivity(email);
            };

            _adresGrad.Click += delegate
            {
                var geoUri    = Uri.Parse("geo:59.915261, 30.519678");
                var mapIntent = new Intent(Intent.ActionView, geoUri);
                StartActivity(mapIntent);
            };

            _adresComfort.Click += delegate
            {
                var geoUri    = Uri.Parse("geo:59.906701, 30.307844");
                var mapIntent = new Intent(Intent.ActionView, geoUri);
                StartActivity(mapIntent);
            };

            _emailComfort.Click += delegate
            {
                var email = new Intent(Intent.ActionSend);
                email.PutExtra(Intent.ExtraEmail, new[] { GetString(Resource.String.emailComfort) });

                email.SetType("message/rfc822");
                StartActivity(email);
            };

            _privateComfort.Click += delegate
            {
                var uri    = Uri.Parse("http://lk.uprkom.ru/");
                var intent = new Intent(Intent.ActionView, uri);
                StartActivity(intent);
            };

            _telComfort.Click += delegate
            {
                var uri    = Uri.Parse("tel:" + GetString(Resource.String.telComfort));
                var intent = new Intent(Intent.ActionDial, uri);
                StartActivity(intent);
            };
        }
Ejemplo n.º 42
0
        private void ProcessPictureUri(MvxIntentResultEventArgs result, Uri uri)
        {
            if (_currentRequestParameters == null)
            {
                MvxTrace.Trace("Internal error - response received but _currentRequestParameters is null");
                return; // we have not handled this - so we return null
            }

            var responseSent = false;
            try
            {
                // Note for furture bug-fixing/maintenance - it might be better to use var outputFileUri = data.GetParcelableArrayExtra("outputFileuri") here?
                if (result.ResultCode != Result.Ok)
                {
                    MvxTrace.Trace("Non-OK result received from MvxIntentResult - {0} - request was {1}",
                                   result.ResultCode, result.RequestCode);
                    return;
                }

                if (uri == null
                    || string.IsNullOrEmpty(uri.Path))
                {
                    MvxTrace.Trace("Empty uri or file path received for MvxIntentResult");
                    return;
                }

                MvxTrace.Trace("Loading InMemoryBitmap started...");
                var memoryStream = LoadInMemoryBitmap(uri);
                MvxTrace.Trace("Loading InMemoryBitmap complete...");
                responseSent = true;
                MvxTrace.Trace("Sending pictureAvailable...");
                _currentRequestParameters.PictureAvailable(memoryStream);
                MvxTrace.Trace("pictureAvailable completed...");
                return;
            }
            finally
            {
                if (!responseSent)
                    _currentRequestParameters.AssumeCancelled();

                _currentRequestParameters = null;
            }
        }
Ejemplo n.º 43
0
 private MemoryStream LoadInMemoryBitmap(Uri uri)
 {
     var memoryStream = new MemoryStream();
     using (Bitmap bitmap = LoadScaledBitmap(uri))
     {
         bitmap.Compress(Bitmap.CompressFormat.Jpeg, _currentRequestParameters.PercentQuality, memoryStream);
     }
     memoryStream.Seek(0L, SeekOrigin.Begin);
     return memoryStream;
 }
Ejemplo n.º 44
0
 public void OnLocationChanged(string newLocation)
 {
     Android.Net.Uri uri = globalUri;
     if (uri != null) {
         long date = WeatherContractOpen.WeatherEntryOpen.getDateFromUri (uri);
         Android.Net.Uri updatedUri = WeatherContractOpen.WeatherEntryOpen.buildWeatherLocationWithDate (newLocation, date);
         globalUri = updatedUri;
         LoaderManager.RestartLoader (URL_LOADER, null, this);
     }
 }
Ejemplo n.º 45
0
        private void setImage(Uri url) {
            uri = url;
            imageView.SetImageURI(uri);
            map = Android.Provider.MediaStore.Images.Media.GetBitmap(ContentResolver, uri);
            layoutHandle.Visibility = ViewStates.Visible;

        }
 public Task <IDataItem> GetDataItemAsync(Android.Net.Uri p0)
 {
     return(GetDataItem(p0).AsAsync <IDataItem> ());
 }
Ejemplo n.º 47
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            Bundle arguments = Arguments;
            if (arguments != null) {
                globalUri = (Android.Net.Uri)arguments.GetParcelable (DetailFragment.DETAIL_URI);
            }

            View rootView = inflater.Inflate (Resource.Layout.fragment_detail, container, false);
            iconView = rootView.FindViewById<ImageView> (Resource.Id.detail_icon);
            dateView = rootView.FindViewById<TextView> (Resource.Id.detail_date_textview);
            friendlyDateView = rootView.FindViewById<TextView> (Resource.Id.detail_day_textview);
            descriptionView = rootView.FindViewById<TextView> (Resource.Id.detail_forecast_textview);
            highTempView = rootView.FindViewById<TextView> (Resource.Id.detail_high_textview);
            lowTempView = rootView.FindViewById<TextView> (Resource.Id.detail_low_textview);
            humidityView = rootView.FindViewById<TextView> (Resource.Id.detail_humidity_textview);
            windView = rootView.FindViewById<TextView> (Resource.Id.detail_wind_textview);
            pressureView = rootView.FindViewById<TextView> (Resource.Id.detail_pressure_textview);

            return rootView;
        }
Ejemplo n.º 48
0
		public void onResultChoosed(Uri uri, bool isInconference, Guid bookingId){
			string path = uri.Path;
			if (path == null) {
				PopupNoticeInfomation popupNotice = new PopupNoticeInfomation (_activity);
				popupNotice.showNoticeDialog (_activity.GetString(Resource.String.title_notice), _activity.GetString(Resource.String.get_img_from_lib));
				return;
			}
			bImages = Utils.GetByteArrayFromFile (path);
			if (bImages != null) {
				sendUploadPhotoRequest (isInconference, bookingId, bImages, utilsAndroid.getNameImageFromPath(path));
			}
		}
Ejemplo n.º 49
0
 private static int GetMaximumDimension(ContentResolver contentResolver, Uri uri)
 {
     using (var inputStream = contentResolver.OpenInputStream(uri))
     {
         var optionsJustBounds = new BitmapFactory.Options
             {
                 InJustDecodeBounds = true
             };
         var metadataResult = BitmapFactory.DecodeStream(inputStream, null, optionsJustBounds);
         var maxDimensionSize = Math.Max(optionsJustBounds.OutWidth, optionsJustBounds.OutHeight);
         return maxDimensionSize;
     }
 }
Ejemplo n.º 50
0
		private string GetPathToImage(Uri uri)
		{
			// The projection contains the columns we want to return in our query.
			var projection = new[] { MediaStore.Images.Media.InterfaceConsts.Data };
			using (var cursor = ContentResolver.Query(uri, projection, null, null, null))
			{
				if (cursor == null) return null;
				var columnIndex = cursor.GetColumnIndexOrThrow(MediaStore.Images.Media.InterfaceConsts.Data);
				cursor.MoveToFirst();
				return cursor.GetString(columnIndex);
			}
		}
        public async Task SaveAndView(string fileName, String contentType, MemoryStream stream)

        {
            string root = null;

            //Get the root path in android device.
            if (Android.OS.Environment.IsExternalStorageEmulated)
            {
                root = Android.OS.Environment.ExternalStorageDirectory.ToString();
            }
            else
            {
                root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
            }

            //Create directory and file
            Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion");
            myDir.Mkdir();

            Java.IO.File file = new Java.IO.File(myDir, fileName);

            //Remove if the file exists
            if (file.Exists())
            {
                file.Delete();
            }

            //Write the stream into the file
            FileOutputStream outs = new FileOutputStream(file);

            outs.Write(stream.ToArray());

            outs.Flush();
            outs.Close();

            //Invoke the created file for viewing
            if (file.Exists())
            {
                Android.Net.Uri path = Android.Net.Uri.FromFile(file);

                var emailMessanger = CrossMessaging.Current.EmailMessenger;
                if (emailMessanger.CanSendEmail)
                {
                    var email = new EmailMessageBuilder()
                                .To("*****@*****.**")
                                .Subject("Punches")
                                .Body("Test Run")
                                .WithAttachment(file)
                                .Build();

                    emailMessanger.SendEmail(email);
                }


                //string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString());
                //string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
                //Intent intent = new Intent(Intent.ActionView);
                //intent.SetDataAndType(path, mimeType);
                //Forms.Context.StartActivity(Intent.CreateChooser(intent, "Choose App"));
            }
        }
 public Task AddListenerAsync(IOnDataChangedListener p0, Android.Net.Uri p1, int p2)
 {
     return(AddListener(p0, p1, p2).AsAsync());
 }
Ejemplo n.º 53
0
 public override int Update(Uri uri, ContentValues values, string selection, string[] selectionArgs)
 {
     throw new NotImplementedException();
 }
 public Task <Java.Lang.Integer> DeleteDataItemsAsync(Android.Net.Uri p0, int p1)
 {
     return(DeleteDataItems(p0, p1).AsAsync <Java.Lang.Integer> ());
 }
Ejemplo n.º 55
0
 private Bitmap LoadScaledBitmap(Uri uri)
 {
     ContentResolver contentResolver = this.GetService<IMvxAndroidGlobals>().ApplicationContext.ContentResolver;
     var maxDimensionSize = GetMaximumDimension(contentResolver, uri);
     var sampleSize = (int) Math.Ceiling((maxDimensionSize)/
                                         ((double) _currentRequestParameters.MaxPixelDimension));
     if (sampleSize < 1)
     {
         // this shouldn't happen, but if it does... then trace the error and set sampleSize to 1
         MvxTrace.Trace(
             "Warning - sampleSize of {0} was requested - how did this happen - based on requested {1} and returned image size {2}",
             sampleSize,
             _currentRequestParameters.MaxPixelDimension,
             maxDimensionSize);
         sampleSize = 1;
     }
     return LoadResampledBitmap(contentResolver, uri, sampleSize);
 }
Ejemplo n.º 56
0
		private string GetPathToImage(Uri uri)
		{
			string path = null;
			try{
				string docId = "";
				using (var cr = _activity.ContentResolver.Query (uri, null, null, null, null)) {
					cr.MoveToFirst ();
					String documentId = cr.GetString (0);
					docId = documentId.Substring (documentId.LastIndexOf (":") + 1);
				}

				// The projection contains the columns we want to return in our query.
				string selection = global::Android.Provider.MediaStore.Images.Media.InterfaceConsts.Id + " =? ";
				using (var cursor = _activity.ManagedQuery(global::Android.Provider.MediaStore.Images.Media.ExternalContentUri, null, selection, new string[] {docId}, null))
				{
					if (cursor == null) return path;
					var columnIndex = cursor.GetColumnIndexOrThrow(global::Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data);
					cursor.MoveToFirst();
					path = cursor.GetString(columnIndex);
				}
			}catch(Exception e){
				System.Console.WriteLine (e.Message);
			}
			return path;
		}
Ejemplo n.º 57
0
        private Bitmap LoadResampledBitmap(ContentResolver contentResolver, Uri uri, int sampleSize)
        {
            using (var inputStream = contentResolver.OpenInputStream(uri))
            {
                var optionsDecode = new BitmapFactory.Options {InSampleSize = sampleSize};

                return BitmapFactory.DecodeStream(inputStream, null, optionsDecode);
            }
        }
Ejemplo n.º 58
0
        public override void OnReceive(Context context, Intent intent)
        {
            try
            {
                Android.Net.Uri alert = RingtoneManager.GetDefaultUri(RingtoneType.Alarm);
                alert = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
                alert = RingtoneManager.GetDefaultUri(RingtoneType.Ringtone);

                // Toast.MakeText(context, "Received intent!", ToastLength.Long).Show();
                var             matakuliah = intent.GetStringExtra("matakuliah");
                var             waktu      = intent.GetStringExtra("waktu");
                var             jadwalId   = Convert.ToInt32(intent.GetStringExtra("jadwalId"));
                Android.Net.Uri soundUri   = Android.Net.Uri.Parse("android.resource://" + "com.ocph23.stimik.simak" + "/raw/alarm");

                if (Build.VERSION.SdkInt < BuildVersionCodes.O)
                {
                    intent.AddFlags(ActivityFlags.ClearTop);
                    var pendingIntent       = PendingIntent.GetActivity(context, 0, intent, PendingIntentFlags.OneShot);
                    var notificationBuilder = new Notification.Builder(context)
                                              .SetContentTitle(waktu)
                                              .SetSmallIcon(Resource.Drawable.Logostimik)
                                              .SetContentText(matakuliah)
                                              .SetAutoCancel(true)
                                              .SetSound(soundUri)
                                              .SetContentIntent(pendingIntent)
                                              .SetPriority((int)Notification.PriorityHigh);
                    var notificationManager = NotificationManager.FromContext(context);
                    notificationManager.Notify(jadwalId, notificationBuilder.Build());
                }
                else
                {
                    intent.AddFlags(ActivityFlags.MultipleTask);
                    var pendingIntent = PendingIntent.GetActivity(context, jadwalId, intent, PendingIntentFlags.OneShot);

                    var notificationBuilder = new Android.App.Notification.Builder(context)
                                              .SetAutoCancel(true)
                                              .SetContentTitle(waktu)
                                              .SetSmallIcon(Resource.Drawable.Logostimik)
                                              .SetContentText(matakuliah)
                                              .SetAutoCancel(true)
                                              .SetSound(soundUri)
                                              .SetVibrate(new long[] { 1000, 1000, 1000 })
                                              .SetContentIntent(pendingIntent)
                                              .SetChannelId(jadwalId.ToString())
                                              .SetPriority((int)Notification.PriorityMax);


                    notificationBuilder.SetSound(Android.Net.Uri.Parse("android.resource://" + context.PackageName + "/" + Resource.Raw.atschool));//Here is FILE_NAME is the name of file that you want to play


                    var channel = new NotificationChannel(jadwalId.ToString(), matakuliah, NotificationImportance.High)
                    {
                        Description = waktu
                    };

                    var notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);
                    notificationManager.CreateNotificationChannel(channel);
                    MediaPlayer mp = MediaPlayer.Create(context, Resource.Raw.schoolringing);
                    if (!mp.IsPlaying)
                    {
                        mp.Start();
                    }
                    notificationManager.Notify(jadwalId, notificationBuilder.Build());
                }
            }
            catch (Exception)
            {
//                throw;
            }
        }
Ejemplo n.º 59
0
 public override int Update(Android.Net.Uri uri, ContentValues values, string selection, string[] selectionArgs)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 60
-1
		protected override void OnCreate(Bundle bundle)
		{
			base.OnCreate(bundle);

			imageViewHelper = new ImageViewHelper(this);

			SetContentView(Resource.Layout.Storage);

			loadPhotoButton = FindViewById<Button>(Resource.Id.loadPhotoButton);
			createDocButton = FindViewById<Button>(Resource.Id.createDocButton);

			if (bundle != null)
			{
				currentImageUri = Android.Net.Uri.Parse(bundle.GetString("current_image_uri", string.Empty));
			}
			else
			{
				currentImageUri = null;
			}

			// This button lets a user pick a photo from the Storage Access Framework UI
			loadPhotoButton.Click += (o, e) =>
			{

				// I want data from all available providers!
				Intent intentOpen = new Intent(Intent.ActionOpenDocument);

				// filter for files that can be opened/used
				intentOpen.AddCategory(Intent.CategoryOpenable);

				//filter results by mime type, if applicable
				intentOpen.SetType("image/*");
				StartActivityForResult(intentOpen, read_request_code);

			};

			// This button takes a photo and saves it to the Storage Access Framework UI
			// The user will be asked what they want to name the file, 
			// and what directory they want to save it in

			createDocButton.Click += (o, e) =>
			{
				Intent intentCreate = new Intent(Intent.ActionCreateDocument);
				intentCreate.AddCategory(Intent.CategoryOpenable);

				// We're going to add a text document
				intentCreate.SetType("text/plain");

				// Pass in a default name for the new document - 
				// the user will be able to change this
				intentCreate.PutExtra(Intent.ExtraTitle, "NewDoc");
				StartActivityForResult(intentCreate, write_request_code);
			};
		}