string GetFileName(Android.Net.Uri uri) { Context ctx = this.context; string[] projection = { MediaStore.MediaColumns.DisplayName }; ContentResolver cr = ctx.ContentResolver; string name = string.Empty; ICursor metaCursor = cr.Query(uri, projection, null, null, null); if (metaCursor != null) { try { if (metaCursor.MoveToFirst()) { name = metaCursor.GetString(0); } } finally { metaCursor.Close(); } } return(name); }
internal static AndroidUri GetShareableFileUri(FileBase file) { Java.IO.File sharedFile; if (FileProvider.IsFileInPublicLocation(file.FullPath)) { // we are sharing a file in a "shared/public" location sharedFile = new Java.IO.File(file.FullPath); } else { var root = FileProvider.GetTemporaryRootDirectory(); var tmpFile = FileSystem.GetEssentialsTemporaryFile(root, file.FileName); System.IO.File.Copy(file.FullPath, tmpFile.CanonicalPath); sharedFile = tmpFile; } // create the uri, if N use file provider if (HasApiLevelN) { return(FileProvider.GetUriForFile(sharedFile)); } // use the shared file path created return(AndroidUri.FromFile(sharedFile)); }
protected override void OnActivityResult(int requestCode, Result result, Intent data) { base.OnActivityResult(requestCode, result, data); if (requestCode == LOAD_IMAGE && result == Result.Ok && imageReciever != null) { Android.Net.Uri imageUri = data.Data; Bitmap bitmap; try { bitmap = Android.Provider.MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUri); } catch (IOException e) { System.Console.WriteLine("Activity Result Error " + e.Message + "\n"); return; } string encodedPath = imageUri.EncodedPath; imageReciever.receiveImage(bitmap, "" + System.Text.RegularExpressions.Regex.Replace(imageUri.EncodedPath, "[/\\:.$%-+*?]", "") + imageUri.GetHashCode()); imageReciever = null; } }
public String getFileName(Android.Net.Uri uri) { String result = null; if (uri.Scheme.Equals("content")) { ICursor cursor = ContentResolver.Query(uri, null, null, null, null); try { if (cursor != null && cursor.MoveToFirst()) { result = cursor.GetString(cursor.GetColumnIndex(OpenableColumns.DisplayName)); } } finally { cursor.Close(); } } if (result == null) { result = uri.Path; int cut = result.LastIndexOf('/'); if (cut != -1) { result = result.Substring(cut + 1); } } return(result); }
void ShareCurrentPhoto() { File externalCacheDir = Activity.ExternalCacheDir; if (externalCacheDir == null) { Toast.MakeText(Activity, "Error writing to USB/external storage.", ToastLength.Short).Show(); return; } // Prevent media scanning of the cache directory. File noMediaFile = new File(externalCacheDir, ".nomedia"); try { noMediaFile.CreateNewFile(); } catch (IOException e) { } // Write the bitmap to temporary storage in the external storage directory (e.g. SD card). // We perform the actual disk write operations on a separate thread using the // {@link AsyncTask} class, thus avoiding the possibility of stalling the main (UI) thread. File tempFile = new File(externalCacheDir, "tempfile.jpg"); new AsyncTaskImpl(delegate(Java.Lang.Object [] parms) { /** * Compress and write the bitmap to disk on a separate thread. * @return TRUE if the write was successful, FALSE otherwise. */ try { var fo = System.IO.File.OpenWrite(tempFile.AbsolutePath); if (!mBitmap.Compress(Bitmap.CompressFormat.Jpeg, 60, fo)) { Toast.MakeText(Activity, "Error writing bitmap data.", ToastLength.Short).Show(); return(false); } return(true); } catch (FileNotFoundException e) { Toast.MakeText(Activity, "Error writing to USB/external storage.", ToastLength.Short).Show(); return(false); } }, delegate { throw new System.NotImplementedException(); }, delegate(bool result) { /** * After doInBackground completes (either successfully or in failure), we invoke an * intent to share the photo. This code is run on the main (UI) thread. */ if (result != true) { return; } Intent shareIntent = new Intent(Intent.ActionSend); shareIntent.PutExtra(Intent.ExtraStream, Uri.FromFile(tempFile)); shareIntent.SetType("image/jpeg"); StartActivity(Intent.CreateChooser(shareIntent, "Share photo")); }).Execute(); }
public Bitmap LoadBitmapFromContactUri(Uri contactUri) { if (contactUri == null) { return(null); } Bitmap result = null; ICursor cursor = Activity.ContentResolver.Query(contactUri, null, null, null, null); if (cursor != null && cursor.MoveToFirst()) { int idx = cursor.GetColumnIndex(ContactsContract.ContactsColumns.PhotoId); string hasPhoto = cursor.GetString(idx); Uri photoUri = Uri.WithAppendedPath(contactUri, ContactsContract.Contacts.Photo.ContentDirectory); if (hasPhoto != null) { try { result = MediaStore.Images.Media.GetBitmap(Activity.ContentResolver, photoUri); } catch (IOException e) { Log.Error(TAG, string.Format("Failed to load resource. Uri {0}", photoUri), e); } } else { Drawable defaultContactDrawable = Activity.Resources.GetDrawable(Resource.Drawable.ic_contact_picture); result = ((BitmapDrawable)defaultContactDrawable).Bitmap; } } return(result); }
protected override async void OnHandleIntent(Intent intent) { //UDP Receiver var listenPort = 15000; var receiver = new UdpSocketReceiver(); receiver.MessageReceived += (sender, args) => { //Daten und Senderadresse auswerten var from = String.Format("{0}:{1}", args.RemoteAddress, args.RemotePort); var data = Encoding.UTF8.GetString(args.ByteData, 0, args.ByteData.Length); //Falls Link übermittelt if (string.IsNullOrEmpty(data) == false) { //Starte MainActivity (mit erhaltener URI) Intent i = new Intent(this, typeof(MainActivity)); i.SetData(Uri.Parse(data)); //i.AddFlags(ActivityFlags.NewTask); this.StartActivity(i); } }; //Abhören am UDP Port starten await receiver.StartListeningAsync(listenPort); }
protected override async void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (requestCode == CropImage.CropImageActivityRequestCode && resultCode == Result.Ok) { if (resultCode == Result.Ok) { Android.Net.Uri imageUri = CropImage.GetPickImageResultUri(this, data); var activityResult = CropImage.GetActivityResult(data); Bitmap bitmap = MediaStore.Images.Media.GetBitmap(ContentResolver, activityResult.Uri); byte[] bitmapData; var stream = new MemoryStream(); bitmap.Compress(Bitmap.CompressFormat.Jpeg, 0, stream); bitmapData = stream.ToArray(); await ViewModel.SendImage.ExecuteAsync(bitmapData); } } else { await ViewModel.Close.ExecuteAsync(); } }
/** * Get the value of the data column for this Uri. This is useful for * MediaStore Uris, and other file-based ContentProviders. * * @param context The context. * @param uri The Uri to query. * @param selection (Optional) Filter used in the query. * @param selectionArgs (Optional) Selection arguments used in the query. * @return The value of the _data column, which is typically a file path. */ public static string getDataColumn(Context context, Uri uri, string selection, string[] selectionArgs) { ICursor cursor = null; string column = "_data"; string[] projection = { column }; try { cursor = context.ContentResolver.Query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.MoveToFirst()) { int index = cursor.GetColumnIndexOrThrow(column); return(cursor.GetString(index)); } } finally { if (cursor != null) { cursor.Close(); } } return(null); }
/* * Result function for clicking on the gallery button. Sets the private variable detailing the current image * to the image selected from the gallery. */ private void Gallery_Activity_Result(Intent data) { Android.Net.Uri image_uri = data.Data; Console.WriteLine(image_uri); _imageView.SetImageURI(image_uri); string path_name = null; try { path_name = Get_Path_To_Image(image_uri); } catch (Exception e) { Console.WriteLine("Exception in getting path to image " + e.Message); } //sets private variable image_bytes to the byte array of the current selected image image_bytes = File.ReadAllBytes(path_name); //sets private variable image_path to the path of the current selected image image_path = path_name; //sets private variable image_stream to the stream of the current selected image image_stream = new MemoryStream(image_bytes); }
public void NotifyInfo(string szTitle, string szMsg, bool bVoice, bool bVibrate) { //设置通知的图标以及显示的简介Title Notification notify = new Notification(Resource.Mipmap.ic_launcher, szTitle); //初始化点击通知后打开的活动 PendingIntent pintent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(MainActivity)), PendingIntentFlags.UpdateCurrent); //设置通知的主体 notify.SetLatestEventInfo(this, szTitle, szMsg, pintent); if (bVoice) { Android.Net.Uri ringUri = RingtoneManager.GetDefaultUri(RingtoneType.Notification); notify.Sound = ringUri; notify.Defaults = NotificationDefaults.Sound | notify.Defaults; } if (bVibrate) { notify.Vibrate = new long[] { 1000 }; notify.Defaults = NotificationDefaults.Vibrate | notify.Defaults; } notify.LedARGB = Color.Green; //设置LED显示时间为1s notify.LedOnMS = 1000; //设置LED熄灭时间为1s notify.LedOffMS = 1000; notify.Flags = NotificationFlags.ShowLights | notify.Flags; notify.Defaults = NotificationDefaults.Lights | notify.Defaults; //发送通知 nMgr.Notify(0, notify); }
private void askPermission() { AndroidNet.Uri uri = AndroidNet.Uri.Parse("package:" + this.PackageName); Intent intent = new Intent(Settings.ActionManageOverlayPermission, uri); //this.Activity.StartActivityForResult(intent,Manifest.Permission.SystemAlertWindow); }
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId) { // start your service logic here Log.Debug(TAG, "StartCommandResult"); Uri requestUri = intent.Data; if (requestUri == null) { StopSelf(); Log.Debug(TAG, "Request URI was NULL"); } else { Log.Debug(TAG, $"OnStartCommand requestUri {requestUri}, flags={flags}, startid={startId}"); DisplayNotification(); DisplayToastToUser(); // <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> ConnectivityManager connectivityManager = (ConnectivityManager)GetSystemService(ConnectivityService); NetworkInfo networkInfo = connectivityManager.ActiveNetworkInfo; if (networkInfo.IsConnected) { var jsonResponse = GetRemoteJSONStringData(requestUri); } StopSelf(); //Stop (and destroy) the service } // Return the correct StartCommandResult for the type of service you are building return(StartCommandResult.NotSticky); }
public override AssetFileDescriptor OpenTypedAssetFile(Android.Net.Uri uri, string mimeTypeFilter, Bundle opts, CancellationSignal signal) { System.Diagnostics.Debug.WriteLine(nameof(OpenTypedAssetFile) + " B"); var result = base.OpenTypedAssetFile(uri, mimeTypeFilter, opts, signal); return(result); }
public override AssetFileDescriptor OpenAssetFile(Android.Net.Uri uri, string mode, CancellationSignal signal) { System.Diagnostics.Debug.WriteLine(nameof(OpenAssetFile) + " B"); var result = base.OpenAssetFile(uri, mode, signal); return(result); }
//open local file, API 24 and above public void OpenLocalPdf(WebView view, string filePath, Context context) { //Android.Net.Uri uri = Android.Net.Uri.Parse("file:///" + filePath); //Android.Net.Uri uri = Android.Net.Uri.FromFile() // Android.Net.Uri pdfPath = Android.Net.Uri.FromFile(new Java.IO.File(filePath)); Android.Net.Uri pdfPath = Android.Support.V4.Content.FileProvider.GetUriForFile(context, "com.fresh.fixityio.fileprovider", new Java.IO.File(filePath)); Intent intent = new Intent(Intent.ActionView); intent.SetDataAndType(pdfPath, "application/pdf"); intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask); intent.AddFlags(ActivityFlags.GrantReadUriPermission); try { view.Context.StartActivity(intent); } catch (System.Exception ex) { //Toast.MakeText(Xamarin.Forms.Forms.Context, "No Application Available to View PDF", ToastLength.Short).Show(); Console.WriteLine("error: " + ex.Message); } }
private IMediaSource CreateAdsMediaSource(IMediaSource mediaSource, android.Net.Uri adTagUri) { // Load the extension source using reflection so the demo app doesn't have to depend on it. // The ads loader is reused for multiple playbacks, so that ad playback can resume. try { Class loaderClass = Class.ForName("com.google.android.exoplayer2.ext.ima.ImaAdsLoader"); if (adsLoader == null) { Constructor loaderConstructor = loaderClass.AsSubclass(Class.FromType(typeof(IAdsLoader))).GetConstructor(Class.FromType(typeof(Context)), Class.FromType(typeof(android.Net.Uri))); adsLoader = (IAdsLoader)loaderConstructor.NewInstance(this, adTagUri); adUiViewGroup = new FrameLayout(this); // The demo app has a non-null overlay frame layout. playerView.OverlayFrameLayout.AddView(adUiViewGroup); } AdMediaSourceFactory adMediaSourceFactory = new AdMediaSourceFactory(this); return(new AdsMediaSource(mediaSource, adMediaSourceFactory, adsLoader, adUiViewGroup)); } catch (ClassNotFoundException e) { // IMA extension not loaded. return(null); } catch (Java.Lang.Exception e) { throw new RuntimeException(e); } }
public static void ShareSong(Context context, long id) { var projection = new[] { BaseColumns.Id, MediaStore.MediaColumns.Data, MediaStore.Audio.AudioColumns.AlbumId }; var selection = $"{projection[0]} IN ({id})"; var c = context.ContentResolver.Query(MediaStore.Audio.Media.ExternalContentUri, projection, selection, null, null); if (c is null) { return; } c.MoveToFirst(); try { var share = new Intent(Intent.ActionSend); share.SetType("audio/*"); share.PutExtra(Intent.ExtraStream, Uri.FromFile(new Java.IO.File(c.GetString(1)))); context.StartActivity(Intent.CreateChooser(share, "Share the song")); c.Close(); } catch { } }
public override ICursor Query(Android.Net.Uri uri, string[] projection, string selection, string[] selectionArgs, string sortOrder) { var item = ItemForUri(uri); if (item == null || item.Value == null) { return(null); } if (item.Value is FileInfo) { return(new PrimativeCursor(item.Value)); } var type = item.Value.GetType(); if (type.ToAndroidFieldType() != FieldType.Null) { return(new PrimativeCursor(item.Value)); } if (item.Value is IList list && type.IsGenericType) { var elementType = type.GenericTypeArguments[0]; //var fieldType = elementType.ToAndroidFieldType(); //if (fieldType != FieldType.Null) return(new IListCursor(item.MimeType, list, elementType)); } return(item.Value is IDictionary && type.IsGenericType ? new PrimativeCursor(item.Value) : null); }
public async void PlaySong(QueueSong queue) { _appSettingsHelper.Write(PlayerConstants.CurrentTrack, queue.Id); if (_alreadyStarted) { _player.Reset(); } else { StartForeground(NotificationId, BuildNotification()); } _alreadyStarted = true; try { await _player.SetDataSourceAsync(ApplicationContext, Uri.Parse(queue.Song.AudioUrl)); MediaPlayerState = MediaPlayerState.Buffering; _player.PrepareAsync(); } catch (Exception e) { MediaPlayerState = MediaPlayerState.None; Log.Error("MUSIC SERVICE", "Player error", e); } }
private string GetPathToImage(Android.Net.Uri uri) { string doc_id = ""; using (var c1 = ContentResolver.Query(uri, null, null, null, null)) { c1.MoveToFirst(); String document_id = c1.GetString(0); doc_id = document_id.Substring(document_id.LastIndexOf(":") + 1); } string path = null; // The projection contains the columns we want to return in our query. string selection = Android.Provider.MediaStore.Images.Media.InterfaceConsts.Id + " =? "; using (var cursor = ManagedQuery(Android.Provider.MediaStore.Images.Media.ExternalContentUri, null, selection, new string[] { doc_id }, null)) { if (cursor == null) { return(path); } var columnIndex = cursor.GetColumnIndexOrThrow(Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data); cursor.MoveToFirst(); path = cursor.GetString(columnIndex); } return(path); }
public override ParcelFileDescriptor OpenPipeHelper(Android.Net.Uri uri, string mimeType, Bundle opts, Java.Lang.Object args, IPipeDataWriter func) { System.Diagnostics.Debug.WriteLine(nameof(OpenPipeHelper)); var result = base.OpenPipeHelper(uri, mimeType, opts, args, func); return(result); }
public override AssetFileDescriptor OpenAssetFile(Android.Net.Uri uri, string mode) { System.Diagnostics.Debug.WriteLine("OpenAssetFile A"); var result = base.OpenAssetFile(uri, mode); return(result); }
public override ParcelFileDescriptor OpenFile(Android.Net.Uri uri, string mode) { string fileName = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), uri.LastPathSegment); return(ParcelFileDescriptor.Open(new Java.IO.File(fileName), ParcelFileMode.ReadOnly)); }
// Updates the contact information on the screen when a contact is picked. public void UpdateContactEntryFromUri(Uri uri) { ICursor cursor = Activity.ContentResolver.Query(contactUri, null, null, null, null); if (cursor != null && cursor.MoveToFirst()) { int idx = cursor.GetColumnIndex(ContactsContract.ContactsColumns.DisplayName); string name = cursor.GetString(idx); idx = cursor.GetColumnIndex(ContactsContract.ContactsColumns.PhotoId); string hasPhoto = cursor.GetString(idx); Uri photoUri = Uri.WithAppendedPath(contactUri, ContactsContract.Contacts.Photo.ContentDirectory); ImageView contactPhoto = (ImageView)Activity.FindViewById(Resource.Id.contact_photo); if (hasPhoto != null) { contactPhoto.SetImageURI(photoUri); } else { Drawable defaultContactDrawable = Activity.Resources.GetDrawable(Resource.Drawable.ic_contact_picture); contactPhoto.SetImageDrawable(defaultContactDrawable); } TextView contactName = (TextView)Activity.FindViewById(Resource.Id.contact_name); contactName.SetText(name, TextView.BufferType.Normal); Activity.FindViewById(Resource.Id.contact_entry).Visibility = ViewStates.Visible; Activity.FindViewById(Resource.Id.attach_person).Visibility = ViewStates.Gone; Activity.FindViewById(Resource.Id.click_to_change).Click += delegate { FindContact(); }; Log.Info(Tag, string.Format("Contact updated. Name {0}, PhotoUri {1}", name, photoUri)); } }
public static void GoToFrPlayStore(Context context) { var intent = new Intent(Intent.ActionView); intent.SetData(Uri.Parse("market://details?id=com.fanreact.app")); context.StartActivity(intent); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Android.Net.Uri uri_android = Intent.Data; Intent.Dispose(); // Convert iOS NSUrl to C#/netxf/BCL System.Uri - common API System.Uri uri_netfx = new System.Uri(uri_android.ToString()); // Send the URI to the Authenticator for continuation MainPage.authenticator.OnPageLoading(uri_netfx); // Xamarin.Forms.DependencyService.Register<INativePages>(); //DependencyService.Get<INativePages>().StartDashboardInAndroid(); var intent = new Intent(MainActivity.mainactivity, typeof(MainActivity)); intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop); StartActivity(intent); Finish(); }
private void TakeAPicture(object sender, EventArgs eventArgs) { Intent intent = new Intent(MediaStore.ActionImageCapture); _file = new File(_dir, string.Format("myPhoto_{0}.jpg", Guid.NewGuid())); if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) == Android.Content.PM.Permission.Granted && ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) == Android.Content.PM.Permission.Granted && ContextCompat.CheckSelfPermission(this, Manifest.Permission.Camera) == Android.Content.PM.Permission.Granted) { _uri = FileProvider.GetUriForFile(ApplicationContext, "com.company.app.fileprovider", _file); intent.PutExtra(MediaStore.ExtraOutput, _uri); StartActivityForResult(intent, 0); } else { ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.ReadExternalStorage, Manifest.Permission.WriteExternalStorage, Manifest.Permission.Camera }, 1); Toast.MakeText(this, "Please try again", ToastLength.Short).Show(); return; } }
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); //Make it available in the gallery Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile); Android.Net.Uri contentUri = Android.Net.Uri.FromFile(App._file); mediaScanIntent.SetData(contentUri); SendBroadcast(mediaScanIntent); //Display in ImageView. resize bitmap to fit display //loading full size image will consume too much memory //and cause crashes int height = Resources.DisplayMetrics.HeightPixels; int width = _imageView.Height; App.bitmap = App._file.Path.LoadAndResizeBitmap(width, height); if (App.bitmap != null) { _imageView.SetImageBitmap(App.bitmap); App.bitmap = null; } //dispose of the java side bitmap GC.Collect(); }
/// <summary> /// Make the call /// </summary> /// <param name="phoneNumber">Phone number.</param> void MakeCall(string phoneNumber) { var uri = Uri.Parse($"tel:{phoneNumber}"); var callIntent = new Intent(Intent.ActionCall, uri); StartActivity(callIntent); }
private static int GetSmallestDimensionOfImage(ContentResolver cr, Uri uri) { using (var inputStream = cr.OpenInputStream(uri)) { var justSizeOptions = new BitmapFactory.Options(); justSizeOptions.InJustDecodeBounds = true; BitmapFactory.DecodeStream(inputStream, new Rect(), justSizeOptions); return Math.Min(justSizeOptions.OutHeight, justSizeOptions.OutWidth); } }
public override void OnCreate () { base.OnCreate (); audio_manager = (AudioManager)GetSystemService (AudioService); //set the original volume and max volume variables to the phone's current and max volume levels orig_volume = audio_manager.GetStreamVolume (Android.Media.Stream.Ring); max_volume = audio_manager.GetStreamMaxVolume (Android.Media.Stream.Ring); //set the sound for the alarm to the phone's alarm tone alarm_sound = RingtoneManager.GetDefaultUri (RingtoneType.Alarm); media_player = new MediaPlayer (); }
/* * Invoked when showNotificationButton is clicked. * Creates a new notification and sets metadata passed as arguments. */ public Notification CreateNotification(Priority priority, Category category, Uri contactUri) { var builder = new Notification.Builder (Activity) .SetContentTitle ("Notification with other metadata") .SetSmallIcon (Resource.Drawable.ic_launcher_notification) .SetPriority ((int)priority.priority) .SetCategory (category.ToString ()) .SetContentText(string.Format("Category {0}, Priority {1}",category.ToString(),priority.ToString())); if (contactUri != null) { builder.AddPerson (contactUri.ToString ()); Bitmap photoBitmap = LoadBitmapFromContactUri (contactUri); if (photoBitmap != null) builder.SetLargeIcon (photoBitmap); } return builder.Build (); }
public Bitmap LoadBitmapFromContactUri(Uri contactUri) { if(contactUri==null) return null; Bitmap result = null; ICursor cursor = Activity.ContentResolver.Query (contactUri, null, null, null, null); if (cursor != null && cursor.MoveToFirst ()) { int idx = cursor.GetColumnIndex (ContactsContract.ContactsColumns.PhotoId); string hasPhoto = cursor.GetString (idx); Uri photoUri = Uri.WithAppendedPath (contactUri, ContactsContract.Contacts.Photo.ContentDirectory); if (hasPhoto != null) { try { result = MediaStore.Images.Media.GetBitmap (Activity.ContentResolver, photoUri); } catch (IOException e) { Log.Error (TAG, string.Format ("Failed to load resource. Uri {0}", photoUri), e); } } else { Drawable defaultContactDrawable = Activity.Resources.GetDrawable (Resource.Drawable.ic_contact_picture); result = ((BitmapDrawable)defaultContactDrawable).Bitmap; } } return result; }
// Updates the contact information on the screen when a contact is picked. public void UpdateContactEntryFromUri(Uri uri) { ICursor cursor = Activity.ContentResolver.Query (contactUri, null, null, null, null); if (cursor != null && cursor.MoveToFirst ()) { int idx = cursor.GetColumnIndex (ContactsContract.ContactsColumns.DisplayName); string name = cursor.GetString (idx); idx = cursor.GetColumnIndex (ContactsContract.ContactsColumns.PhotoId); string hasPhoto = cursor.GetString (idx); Uri photoUri = Uri.WithAppendedPath (contactUri, ContactsContract.Contacts.Photo.ContentDirectory); ImageView contactPhoto = (ImageView)Activity.FindViewById (Resource.Id.contact_photo); if (hasPhoto != null) contactPhoto.SetImageURI (photoUri); else { Drawable defaultContactDrawable = Activity.Resources.GetDrawable (Resource.Drawable.ic_contact_picture); contactPhoto.SetImageDrawable (defaultContactDrawable); } TextView contactName = (TextView)Activity.FindViewById (Resource.Id.contact_name); contactName.SetText (name, TextView.BufferType.Normal); Activity.FindViewById (Resource.Id.contact_entry).Visibility = ViewStates.Visible; Activity.FindViewById (Resource.Id.attach_person).Visibility = ViewStates.Gone; Activity.FindViewById (Resource.Id.click_to_change).Click += delegate { FindContact (); }; Log.Info(Tag,string.Format("Contact updated. Name {0}, PhotoUri {1}",name,photoUri)); } }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); this._noteView = FindViewById<TextView>(Resource.Id.noteview); AndroidUri localUri = Intent.Data; if ((localUri == null) && (bundle != null)) { localUri = AndroidUri.Parse(bundle.GetString(KEY_URL)); } if ((localUri == null) || (localUri.PathSegments.Count < 2)) { localUri = AndroidUri.WithAppendedPath(WikiNote.Notes.ALL_NOTES_URI, Resources.GetString(Resource.String.start_page)); } ICursor localCursor = ManagedQuery(localUri, WikiNote.WIKI_NOTES_PROJECTION, null, null, null); bool newNote = false; if ((localCursor == null) || (localCursor.Count == 0)) { try { // no matching wikinote, so create it localUri = ContentResolver.Insert(localUri, null); if (localUri == null) { Log.Error("WikiNotes", "Failed to insert new wikinote into " + Intent.Data); Finish(); return; } // make sure that the new note was created successfully, and // select it localCursor = ManagedQuery(localUri, WikiNote.WIKI_NOTES_PROJECTION, null, null, null); if ((localCursor == null) || (localCursor.Count == 0)) { Log.Error("WikiNotes", "Failed to open new wikinote: " + Intent.Data); Finish(); return; } newNote = true; } catch (Exception ex) { Log.Error(WikiNote.LOG_TAG, ex.Message); } } _uri = localUri; _cursor = localCursor; localCursor.MoveToFirst(); _helper = new WikiActivityHelper(this); // get the note name String noteName = _cursor.GetString(_cursor .GetColumnIndexOrThrow(WikiNote.Notes.TITLE)); _noteName = noteName; // set the title to the name of the page Title = Resources.GetString(Resource.String.wiki_title, noteName); // If a new note was created, jump straight into editing it if (newNote) { _helper.EditNote(noteName, null); } // Set the menu shortcut keys to be default keys for the activity as well SetDefaultKeyMode(DefaultKey.Shortcut); }
public void DeleteDataItems (List<Android.Net.Uri> dataItemUriList) { if (google_api_client.IsConnected) { foreach (Android.Net.Uri dataItemUri in dataItemUriList) { this.dataItemUri = dataItemUri; WearableClass.DataApi.DeleteDataItems (google_api_client, dataItemUri) .SetResultCallback (new DeleteResultCallback (this)); } } else { Log.Error (TAG, "Failed to delete data items because client is disconnected from" + "Google Play Services"); } }
public override void OnActivityResult (int requestCode, Result resultCode, Intent data) { base.OnActivityResult (requestCode, resultCode, data); switch (requestCode) { case REQUEST_CODE_PICK_CONTACT: if (resultCode == Result.Ok) { Uri contactUri = data.Data; this.contactUri = contactUri; UpdateContactEntryFromUri (contactUri); } break; } }
public void ShowNotificationClicked(Priority p, Category c, Uri u) { incrementalNotificationId++; notificationManager.Notify (incrementalNotificationId, CreateNotification (p, c, u)); Toast.MakeText (Activity, "Show Notification clicked", ToastLength.Short).Show (); }