public async void CreatePlaylist(string name, string path) { await MainActivity.instance.GetWritePermission(); ContentResolver resolver = MainActivity.instance.ContentResolver; Uri uri = MediaStore.Audio.Playlists.ExternalContentUri; ContentValues value = new ContentValues(); value.Put(MediaStore.Audio.Playlists.InterfaceConsts.Name, name); resolver.Insert(uri, value); long playlistID = 0; CursorLoader loader = new CursorLoader(Android.App.Application.Context, uri, null, null, null, null); ICursor cursor = (ICursor)loader.LoadInBackground(); if (cursor != null && cursor.MoveToFirst()) { int nameID = cursor.GetColumnIndex(MediaStore.Audio.Playlists.InterfaceConsts.Name); int getplaylistID = cursor.GetColumnIndex(MediaStore.Audio.Playlists.InterfaceConsts.Id); do { string playlistName = cursor.GetString(nameID); long id = cursor.GetLong(getplaylistID); if (playlistName == name) { playlistID = id; } }while (cursor.MoveToNext()); cursor.Close(); } AddToPlaylist(path, "foo", playlistID); }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { if (requestCode == 0 && resultCode == Result.Ok) { //Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile); //Uri contentUri = Uri.FromFile(_file); //mediaScanIntent.SetData(contentUri); //SendBroadcast(mediaScanIntent); ContentValues values = new ContentValues(); values.Put(MediaStore.MediaColumns.Data, _file.Path); ContentResolver.Insert(MediaStore.Images.Media.ExternalContentUri, values); var img = compressImage(_file.Path); var filename = _file.Name.Split('.'); imageView.SetImageBitmap(img); var imgBytes = ImageToByte(img); inputAlertDialog(filename[0], imgBytes); } else if (requestCode == 1 && resultCode == Result.Ok) { var img = compressImage(GetPathToImage(data.Data)); var path = GetPathToImage(data.Data).Split('/'); var filename = path[path.Length - 1].Split('.'); imageView.SetImageBitmap(img); var imgBytes = ImageToByte(img); inputAlertDialog(filename[0], imgBytes); } }
public void AddCalenderEvent(string title, string location, DateTime startDate, DateTime endDate) { int sdy = startDate.Day; int smn = startDate.Month; int syy = startDate.Year; int shh = startDate.Hour; int smm = startDate.Minute; int edy = endDate.Day; int emn = endDate.Month; int eyy = endDate.Year; int ehh = endDate.Hour; int emm = endDate.Minute; string[] calendarsProjection = { CalendarContract.Calendars.InterfaceConsts.Id, CalendarContract.Calendars.InterfaceConsts.CalendarDisplayName, CalendarContract.Calendars.InterfaceConsts.AccountName, }; ContentValues eventValues = new ContentValues(); eventValues.Put(CalendarContract.Events.InterfaceConsts.CalendarId, 1); eventValues.Put(CalendarContract.Events.InterfaceConsts.Title, title); eventValues.Put(CalendarContract.Events.InterfaceConsts.Description, ""); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS(syy, smm, sdy, shh, smm)); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS(eyy, emm, edy, ehh, emm)); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, "GMT"); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "GMT"); var uri = ContentResolver.Insert(CalendarContract.Events.ContentUri, eventValues); }
protected void MakePictureAndAdd() { /*if (!PackageManager.HasSystemFeature(PackageManager.FeatureCamera)) * { * Toast.MakeText(this, "No camera detected on device", ToastLength.Long).Show(); * return; * }*/ /*var photoIntent = new Intent(MediaStore.ActionImageCapture); * _currentPictureFile = storage.GetTempImageFileName(); * photoIntent.PutExtra(MediaStore.ExtraOutput, _currentPictureFile); * StartActivityForResult(photoIntent, Constants.TAKE_PICTURE);*/ /*var dir = new Java.IO.File( * Android.OS.Environment.GetExternalStoragePublicDirectory * (Android.OS.Environment.DirectoryDcim), "crime");*/ var uri = ContentResolver.Insert(MediaStore.Images.Media.ExternalContentUri, new ContentValues()); //var _file = new Java.IO.File(@"/mnt/.bonuscards", "mypic.jpg"); var intent = new Intent(MediaStore.ActionImageCapture); //intent.PutExtra(MediaStore.ExtraOutput, uri); //_currentPictureFile = @"/mnt/.bonuscards/mypic.jpg"; StartActivityForResult(intent, Constants.TAKE_PICTURE); }
public void CapturePhoto() { ImageUri = ContentResolver.Insert(MediaStore.Images.Media.ExternalContentUri, new ContentValues()); var i = new Intent(MediaStore.ActionImageCapture); i.PutExtra(MediaStore.ExtraOutput, ImageUri); StartActivityForResult(i, CAPTURE_PHOTO); }
public override bool Set(Context context, ComponentName component, int badgeCount) { if (Build.VERSION.SdkInt >= BuildVersionCodes.LollipopMr1 && base.IsSupported(context)) //new samsung >= 5.1 use default badger system { //use default badger return(base.Set(context, component, badgeCount)); } Uri contentUri = Uri.Parse(CONTENT_URI); ContentResolver resolver = context.ContentResolver; ICursor cursor = null; try { cursor = resolver.Query(contentUri, ContentProjection, "package=?", new[] { component.PackageName }, null); if (cursor == null) { return(false); } string entryActivityName = component.ClassName; bool entryActivityExist = false; while (cursor.MoveToNext()) { int id = cursor.GetInt(0); ContentValues contentValues = GetContentValues(component, badgeCount, false); resolver.Update(contentUri, contentValues, "_id=?", new [] { id.ToString() }); if (entryActivityName.Equals(cursor.GetString(cursor.GetColumnIndex("class")))) { entryActivityExist = true; } } if (!entryActivityExist) { ContentValues contentValues = GetContentValues(component, badgeCount, true); resolver.Insert(contentUri, contentValues); } return(true); } catch (Exception) { //ignored return(false); } finally { if (cursor != null && !cursor.IsClosed) { cursor.Close(); } } }
private void BtnAddPht_Click(object sender, EventArgs e) { var uri = ContentResolver.Insert(isMounted ? MediaStore.Images.Media.ExternalContentUri : MediaStore.Images.Media.InternalContentUri, new ContentValues()); //_imageUri = uri.ToString(); intent = new Intent(MediaStore.ActionImageCapture); intent.PutExtra(MediaStore.ExtraOutput, uri); StartActivityForResult(intent, 1001); }
public async Task AddToPlaylist(Playlist playlist, Song song) { await Task.Run(() => { ContentValues cv = new ContentValues(); cv.Put(MediaStore.Audio.Playlists.Members.PlayOrder, 0); cv.Put(MediaStore.Audio.Playlists.Members.AudioId, song.Id); Android.Net.Uri uri = MediaStore.Audio.Playlists.Members.GetContentUri("external", (long)playlist.Id); ContentResolver resolver = Android.App.Application.Context.ContentResolver; var rUri = resolver.Insert(uri, cv); resolver.NotifyChange(Android.Net.Uri.Parse("content://media"), null); }); }
private void AddPlaylistToIndex(bool utf8) { string name = utf8 ? "haplaylist8" : "haplaylist"; ContentResolver.Delete(MediaStore.Audio.Playlists.ExternalContentUri, "name == ?", new string[] { name }); ContentValues cv = new ContentValues(); cv.Put("name", name); cv.Put("_data", getPlaylistPath(utf8)); cv.Put("date_added", DateTime.Now.ToFileTime()); cv.Put("date_modified", DateTime.Now.ToFileTime()); ContentResolver.Insert(MediaStore.Audio.Playlists.ExternalContentUri, cv); }
private void DoTakePhoto(Activity activity) { SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMdd_HHmmss"); string filename = timeStampFormat.Format(new Date()); ContentValues values = new ContentValues(); values.Put(MediaStore.Images.ImageColumns.Title, filename); mCameraUri = ContentResolver.Insert(MediaStore.Images.Media.ExternalContentUri, values); Intent cameraIntent = new Intent(MediaStore.ActionImageCapture); cameraIntent.PutExtra(MediaStore.ExtraOutput, mCameraUri); activity.StartActivityForResult(cameraIntent, FileChooserCodeCamera); }
/** * A copy of the Android internals StoreThumbnail method, it used with the insertImage to * populate the android.provider.MediaStore.Images.Media#insertImage with all the correct * meta data. The StoreThumbnail method is private so it must be duplicated here. * @see android.provider.MediaStore.Images.Media (StoreThumbnail private method) */ private static Bitmap storeThumbnail( ContentResolver cr, Bitmap source, long id, float width, float height, int kind) { // create the matrix to scale it Matrix matrix = new Matrix(); float scaleX = width / source.Width; float scaleY = height / source.Height; matrix.SetScale(scaleX, scaleY); Bitmap thumb = Bitmap.CreateBitmap(source, 0, 0, source.Width, source.Height, matrix, true ); ContentValues values = new ContentValues(4); values.Put(MediaStore.Images.Thumbnails.Kind, kind); values.Put(MediaStore.Images.Thumbnails.ImageId, (int)id); values.Put(MediaStore.Images.Thumbnails.Height, thumb.Height); values.Put(MediaStore.Images.Thumbnails.Width, thumb.Width); Android.Net.Uri url = cr.Insert(MediaStore.Images.Thumbnails.InternalContentUri, values); try { System.IO.Stream thumbOut = cr.OpenOutputStream(url); thumb.Compress(Bitmap.CompressFormat.Jpeg, 100, thumbOut); thumbOut.Close(); return(thumb); } catch (FileNotFoundException ex) { return(null); } catch (IOException ex) { return(null); } }
void InitAddEvent() { var addSampleEvent = FindViewById <Button> (Resource.Id.addSampleEvent); addSampleEvent.Click += (sender, e) => { // Create Event code ContentValues eventValues = new ContentValues(); eventValues.Put(CalendarContract.Events.InterfaceConsts.CalendarId, _calId); eventValues.Put(CalendarContract.Events.InterfaceConsts.Title, "Test Event from M4A"); eventValues.Put(CalendarContract.Events.InterfaceConsts.Description, "This is an event created from Mono for Android"); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS(2011, 12, 15, 10, 0)); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS(2011, 12, 15, 11, 0)); var uri = ContentResolver.Insert(CalendarContract.Events.ContentUri, eventValues); Console.WriteLine("Uri for new event: {0}", uri); }; }
void InitAddEvent() { ContentValues eventValues = new ContentValues(); eventValues.Put(CalendarContract.Events.InterfaceConsts.CalendarId, _calId); eventValues.Put(CalendarContract.Events.InterfaceConsts.Title, "Appointment for picking up my bicycle"); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventLocation, BikeData.Straat + " " + BikeData.Huisnummer); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS()); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS()); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, "UTC"); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "UTC"); var uri = ContentResolver.Insert(CalendarContract.Events.ContentUri, eventValues); Toast.MakeText(this, "You have made an appoinment ", ToastLength.Short).Show(); }
private async Task AddEvent(DateTime startTime, DateTime endTime, string subject, string location, string details, bool isAllDay) { ContentResolver cr = Activity.ContentResolver; ContentValues eventValues = new ContentValues(); eventValues.Put(CalendarContract.Events.InterfaceConsts.CalendarId, 1); eventValues.Put(CalendarContract.Events.InterfaceConsts.Title, subject); eventValues.Put(CalendarContract.Events.InterfaceConsts.Description, details); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS(startTime)); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS(endTime)); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, "UTC"); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "UTC"); eventValues.Put(CalendarContract.Events.InterfaceConsts.AllDay, (isAllDay) ? "1" : "0"); var eventUri = cr.Insert(CalendarContract.Events.ContentUri, eventValues); long eventID = long.Parse(eventUri.LastPathSegment); await App.Current.MainPage.DisplayAlert("App", subject + "\r\n Start date: " + startTime + "\r\n Return date: " + endTime, "ok"); }
public async void SetCurrentEventReminder(object sender, EventArgs e) { if (CheckSelfPermission(Manifest.Permission.WriteCalendar.ToString()) == Android.Content.PM.Permission.Granted) { try { if (!isEventInCal(this, App.reminderEvent.eventName)) { ContentValues eventValues = new ContentValues(); eventValues.Put(CalendarContract.Events.InterfaceConsts.CalendarId, 1); eventValues.Put(CalendarContract.Events.InterfaceConsts.Title, App.reminderEvent.eventName); eventValues.Put(CalendarContract.Events.InterfaceConsts.Description, App.reminderEvent.eventDescription); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS(BaseFunctions.GetDateTimeFull(App.reminderEvent.eventStartDate + " " + App.reminderEvent.eventStartTime))); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS(BaseFunctions.GetDateTimeFull(App.reminderEvent.eventEndDate + " " + App.reminderEvent.eventEndTime))); eventValues.Put(CalendarContract.Events.InterfaceConsts.AllDay, "0"); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventLocation, App.reminderEvent.eventAddress); eventValues.Put(CalendarContract.Events.InterfaceConsts.HasAlarm, "1"); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, "UTC"); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "UTC"); var eventUri = ContentResolver.Insert(CalendarContract.Events.ContentUri, eventValues); long eventID = long.Parse(eventUri.LastPathSegment); ContentValues reminderValues = new ContentValues(); reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.Minutes, 30); reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.EventId, eventID); reminderValues.Put(CalendarContract.Reminders.InterfaceConsts.Method, (int)RemindersMethod.Alert); var reminderUri = ContentResolver.Insert(CalendarContract.Reminders.ContentUri, reminderValues); await App.Current.MainPage.DisplayAlert("Alert", "This event is added to your calender", "Ok"); } else { await App.Current.MainPage.DisplayAlert("Alert", "This event is already added to your calender", "Ok"); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } } else { RequestPermissions(new string[] { Manifest.Permission.WriteCalendar.ToString() }, calenderRequestCode); } }
void InsertValues() { ContentValues values = new ContentValues(); values.Put(LocationContentProvider._ID, 1); values.Put(LocationContentProvider.NAME, "Brüel & Kjær"); values.Put(LocationContentProvider.LATITUTDE, 55.816932); values.Put(LocationContentProvider.LONGITUDE, 12.532697); Android.Net.Uri uri = ContentResolver.Insert(LocationContentProvider.CONTENT_URI, values); System.Diagnostics.Debug.WriteLine("Insert: " + uri.ToString()); values.Clear(); values.Put(LocationContentProvider._ID, 2); values.Put(LocationContentProvider.NAME, "Technical University of Denmark"); values.Put(LocationContentProvider.LATITUTDE, 55.786323); values.Put(LocationContentProvider.LONGITUDE, 12.524135); uri = ContentResolver.Insert(LocationContentProvider.CONTENT_URI, values); System.Diagnostics.Debug.WriteLine("Insert: " + uri.ToString()); }
/* * Add sms to history requires 2 permissions: * <uses-permission android:name="android.permission.WRITE_SMS" /> * <uses-permission android:name="android.permission.READ_SMS" /> * */ private void AddSentSmsToHistory(String address, String message) { try { ContentValues values = new ContentValues(); values.Put("address", address); values.Put("body", message); //values.Put("body", String.Format("{0} (sent by sms2, {1})", message, SHORT_URL_TO_GOOGLE_PLAY_SMS2)); //values.Put("date", DateTime.Now.Ticks); //long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; var totalPeriod = DateTime.UtcNow - new DateTime(1970, 1, 1); long milliseconds = (long)totalPeriod.TotalMilliseconds; values.Put("date", milliseconds); //getContentResolver.Insert(Android.Net.Uri.Parse("content://sms/sent"), values); ContentResolver.Insert(Android.Net.Uri.Parse("content://sms/sent"), values); } catch (Exception e) { //e.printStackTrace(); Toast.MakeText(Application.Context, String.Format("SMS cannot be stored, because '{0}'", e.Message), ToastLength.Long).Show(); } }
public async Task SaveImageAsync(string fileName, string url) { ContentResolver resolver = this.Context?.ContentResolver; if (resolver != null) { Android.Net.Uri imagesCollection; if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Q) { imagesCollection = MediaStore.Images.Media.GetContentUri(MediaStore.VolumeExternalPrimary); } else { imagesCollection = MediaStore.Images.Media.ExternalContentUri; } try { var imageData = await GetImageFromUriAsync(url); ContentValues image = new ContentValues(); var imageName = fileName.Split('.').First(); image.Put(MediaStore.Images.ImageColumns.DisplayName, string.Join(string.Empty, imageName.Split('_'))); image.Put(MediaStore.Images.ImageColumns.MimeType, "image/jpeg"); Android.Net.Uri savedImageUri = resolver.Insert(imagesCollection, image); using (Android.Graphics.Bitmap bitmap = Android.Graphics.BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length)) { using (Stream stream = resolver.OpenOutputStream(savedImageUri)) { bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Jpeg, 100, stream); } } } catch (Exception ex) { Console.WriteLine($"ImageService.SaveImageAsync Exception: {ex}"); } } }
public override void SetBadge(int count) { try { /*ContentResolver contentResolver = mContext.ContentResolver; * var cursor = contentResolver.Query(CONTENT_URI, new string[]{ COLUMN_ID }, COLUMN_PACKAGE + "=?", new string[]{ GetPackageName() }, null); * * if (cursor == null || !cursor.MoveToFirst()) { * var contentValues = new ContentValues(); * contentValues.Put(COLUMN_PACKAGE, GetPackageName()); * contentValues.Put(COLUMN_CLASS, GetMainActivityClassName()); * contentValues.Put(COLUMN_BADGE_COUNT, count); * contentResolver.Insert(CONTENT_URI, contentValues); * } else { * int idColumnIndex = cursor.GetColumnIndex(COLUMN_ID); * * var contentValues = new ContentValues(); * contentValues.Put(COLUMN_BADGE_COUNT, count); * contentResolver.Update(CONTENT_URI, contentValues, COLUMN_ID + "=?", new string[]{ cursor.GetInt(idColumnIndex).ToString() }); * }*/ var cv = new ContentValues(); cv.Put("package", GetPackageName()); cv.Put("class", GetMainActivityClassName()); cv.Put("badgecount", count); // integer count you want to display ContentResolver contentResolver = mContext.ContentResolver; int updated = contentResolver.Update(CONTENT_URI, cv, "package=?", new string[] { GetPackageName() }); if (updated == 0) { contentResolver.Insert(CONTENT_URI, cv); } } catch (Exception e) { // Some Samsung devices are throwing SecurityException or RuntimeException when // trying to set the badge saying the app needs permission which are already added, // this try/catch protect us from these "crappy phones" :) throw new Java.Lang.UnsupportedOperationException(); } }
void InitAddEvent() { var addSampleEvent = FindViewById <Button> (Resource.Id.addSampleEvent); addSampleEvent.Click += (sender, e) => { // Create Event code ContentValues eventValues = new ContentValues(); eventValues.Put(CalendarContract.Events.InterfaceConsts.CalendarId, _calId); eventValues.Put(CalendarContract.Events.InterfaceConsts.Title, "Test Event from M4A"); eventValues.Put(CalendarContract.Events.InterfaceConsts.Description, "This is an event created from Mono for Android"); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS(2011, 12, 15, 10, 0)); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS(2011, 12, 15, 11, 0)); // GitHub issue #9 : Event start and end times need timezone support. // https://github.com/xamarin/monodroid-samples/issues/9 eventValues.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, "UTC"); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "UTC"); var uri = ContentResolver.Insert(CalendarContract.Events.ContentUri, eventValues); Console.WriteLine("Uri for new event: {0}", uri); }; }
public void AddAppointment(string desc, int day, int year, int month) { Java.Util.TimeZone timeZone = Java.Util.TimeZone.Default; ContentValues eventValues = new ContentValues(); eventValues.Put(CalendarContract.Events.InterfaceConsts.CalendarId, "1"); eventValues.Put(CalendarContract.Events.InterfaceConsts.Title, "Your AutoCal event"); eventValues.Put(CalendarContract.Events.InterfaceConsts.Description, desc); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS(year, month, day, 00, 0)); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS(year, month, day, 23, 59)); //eventValues.Put(CalendarContract.ExtraEventBeginTime, "00:00"); //eventValues.Put(CalendarContract.ExtraEventEndTime, "23:59"); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, timeZone.ID); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventEndTimezone, timeZone.ID); //ContentResolver contResv = getApplicationContext().getContentResolver(); //Context context = (Context) this.getActivity().getApplicationContext().getContentResolver(); //ContentResolver result = (ContentResolver)context.getContentResolver(); Android.Net.Uri uri = ContentResolver.Insert(CalendarContract.Events.ContentUri, eventValues); //long startTime = ; //Intent intent = new Intent(Intent.ActionInsert); // //intent.PutExtra(CalendarContract.Events.InterfaceConsts.Title, "New calendarEvent by Team B"); //intent.PutExtra(CalendarContract.Events.InterfaceConsts.Description, desc); //intent.PutExtra(CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS(year, month, day, 00, 0)); //intent.PutExtra(CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS(year, month, day, 23, 59)); //intent.PutExtra(CalendarContract.ExtraEventBeginTime, "00:00"); //intent.PutExtra(CalendarContract.ExtraEventEndTime, "23:59"); //intent.PutExtra(CalendarContract.Events.InterfaceConsts.EventTimezone, timeZone.ID); //intent.PutExtra(CalendarContract.Events.InterfaceConsts.EventEndTimezone, timeZone.ID); //intent.SetData(CalendarContract.Events.ContentUri); //((Activity)Forms.Context).StartActivity(intent); }
private void AddGoHejaCalendarToDevice() { try { var calendarsUri = CalendarContract.Calendars.ContentUri; string[] calendarsProjection = { CalendarContract.Calendars.InterfaceConsts.Id, CalendarContract.Calendars.InterfaceConsts.CalendarDisplayName, CalendarContract.Calendars.InterfaceConsts.AccountName }; var cursor = ApplicationContext.ContentResolver.Query(calendarsUri, calendarsProjection, null, null, null); #region remove existing GoHeja calendar if (cursor.MoveToFirst()) { do { long id = cursor.GetLong(0); String displayName = cursor.GetString(1); if (displayName == Constants.DEVICE_CALENDAR_TITLE) { //RemoveCalendar(id); calendarID = id; } } while (cursor.MoveToNext()); } #endregion #region create GoHeja Calendar if (calendarID == -1) { var uri = CalendarContract.Calendars.ContentUri; ContentValues val = new ContentValues(); val.Put(CalendarContract.Calendars.InterfaceConsts.AccountName, Constants.DEVICE_CALENDAR_TITLE); val.Put(CalendarContract.Calendars.InterfaceConsts.AccountType, CalendarContract.AccountTypeLocal); val.Put(CalendarContract.Calendars.Name, Constants.DEVICE_CALENDAR_TITLE); val.Put(CalendarContract.Calendars.InterfaceConsts.CalendarDisplayName, Constants.DEVICE_CALENDAR_TITLE); val.Put(CalendarContract.Calendars.InterfaceConsts.CalendarColor, Android.Graphics.Color.Yellow); val.Put(CalendarContract.Calendars.InterfaceConsts.OwnerAccount, Constants.DEVICE_CALENDAR_TITLE); val.Put(CalendarContract.Calendars.InterfaceConsts.Visible, true); val.Put(CalendarContract.Calendars.InterfaceConsts.SyncEvents, true); uri = uri.BuildUpon() .AppendQueryParameter(CalendarContract.CallerIsSyncadapter, "true") .AppendQueryParameter(CalendarContract.Calendars.InterfaceConsts.AccountName, Constants.DEVICE_CALENDAR_TITLE) .AppendQueryParameter(CalendarContract.Calendars.InterfaceConsts.AccountType, CalendarContract.AccountTypeLocal) .Build(); var calresult = ContentResolver.Insert(uri, val); calendarID = long.Parse(calresult.LastPathSegment); } #endregion RemoveGoHejaTodayAndFutureEvents(); UpdateGoHejaEvents(); } catch (Exception err) { Toast.MakeText(this, err.ToString(), ToastLength.Long).Show(); } }
private void AddEventsToGoHejaCalendar(List <GoHejaEvent> events) { if (calendarID == -1 || events == null || events.Count == 0) { return; } try { foreach (var goHejaEvent in events) { var startDate = goHejaEvent.StartDateTime(); //Convert.ToDateTime(goHejaEvent.start); var endDate = goHejaEvent.EndDateTime(); //Convert.ToDateTime(goHejaEvent.end); DateTime now = DateTime.Now; DateTime startNow = new DateTime(now.Year, now.Month, now.Day); DateTime startDay = new DateTime(startDate.Year, startDate.Month, startDate.Day); var deltaSec = (startDay - startNow).TotalSeconds; if (deltaSec < 0) { continue; } var title = goHejaEvent.title; string eventDescription = goHejaEvent.eventData; var filteredDescription = baseVC.FormatEventDescription(eventDescription); string[] arryEventDes = filteredDescription.Split(new char[] { '~' }); string note = ""; for (var i = 0; i < arryEventDes.Length; i++) { note += arryEventDes[i] + Environment.NewLine; } var strDistance = goHejaEvent.distance; float floatDistance = strDistance == "" ? 0 : float.Parse(strDistance); var b = Math.Truncate(floatDistance * 100); var c = b / 100; var formattedDistance = c.ToString("F2"); var durMin = goHejaEvent.durMin == "" ? 0 : int.Parse(goHejaEvent.durMin); var durHrs = goHejaEvent.durHrs == "" ? 0 : int.Parse(goHejaEvent.durHrs); var pHrs = durMin / 60; durHrs = durHrs + pHrs; durMin = durMin % 60; var strDuration = durHrs.ToString() + ":" + durMin.ToString("D2"); note += System.Environment.NewLine + "Planned HB : " + goHejaEvent.hb + Environment.NewLine + "Planned TSS : " + goHejaEvent.tss + Environment.NewLine + "Planned distance : " + formattedDistance + "KM" + Environment.NewLine + "Duration : " + strDuration + Environment.NewLine; //var encodedTitle = System.Web.HttpUtility.UrlEncode(goHejaEvent.title); //var strDate = startDate.ToString();//String.Format("{ 0:MM/dd/yyyy hh:mm:ss a}", startDate.ToString()); //var encodedDate = System.Web.HttpUtility.UrlEncode(strDate); //var encodedEventURL = String.Format(Constants.URL_EVENT_MAP, encodedTitle, encodedDate, AppSettings.Username); //note += Environment.NewLine + encodedEventURL; #region create event ContentValues eventValues = new ContentValues(); eventValues.Put(CalendarContract.Events.InterfaceConsts.CalendarId, calendarID); eventValues.Put(CalendarContract.Events.InterfaceConsts.Title, title); eventValues.Put(CalendarContract.Events.InterfaceConsts.Description, note); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS(startDate)); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS(endDate)); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, "UTC"); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "UTC"); eventValues.Put(CalendarContract.Events.InterfaceConsts.HasAlarm, 1); var eventURI = ContentResolver.Insert(CalendarContract.Events.ContentUri, eventValues); var eventID = long.Parse(eventURI.LastPathSegment); var deltaMin = (startDate - DateTime.Now).TotalMinutes; if (deltaMin > 45) { ContentValues reminderValues1 = new ContentValues(); reminderValues1.Put(CalendarContract.Reminders.InterfaceConsts.EventId, eventID); reminderValues1.Put(CalendarContract.Reminders.InterfaceConsts.Minutes, 45.0f); reminderValues1.Put(CalendarContract.Reminders.InterfaceConsts.Method, 1); ContentResolver.Insert(CalendarContract.Reminders.ContentUri, reminderValues1); if (deltaMin > (10 * 60)) { ContentValues reminderValues2 = new ContentValues(); reminderValues2.Put(CalendarContract.Reminders.InterfaceConsts.EventId, eventID); reminderValues2.Put(CalendarContract.Reminders.InterfaceConsts.Minutes, 60 * 10); reminderValues2.Put(CalendarContract.Reminders.InterfaceConsts.Method, 1); ContentResolver.Insert(CalendarContract.Reminders.ContentUri, reminderValues2); } } #endregion } } catch (Exception err) { Toast.MakeText(this, err.ToString(), ToastLength.Long).Show(); } }
public static String insertImage(ContentResolver cr, Bitmap source, String title, String description) { ContentValues values = new ContentValues(); values.Put(MediaStore.Images.ImageColumns.Title, title); values.Put(MediaStore.Images.ImageColumns.DisplayName, title); values.Put(MediaStore.Images.ImageColumns.Description, description); values.Put(MediaStore.Images.ImageColumns.MimeType, "image/jpeg"); // Add the date meta data to ensure the image is added at the front of the gallery values.Put(MediaStore.Images.ImageColumns.DateAdded, CurrentTimeMillis());// System.currentTimeMillis()); values.Put(MediaStore.Images.ImageColumns.DateTaken, CurrentTimeMillis()); Android.Net.Uri url = null; String stringUrl = null; /* value to be returned */ try { url = cr.Insert(MediaStore.Images.Media.InternalContentUri, values); if (source != null) { System.IO.Stream imageOut = cr.OpenOutputStream(url); try { source.Compress(Bitmap.CompressFormat.Jpeg, 50, imageOut); } finally { imageOut.Close(); } long id = ContentUris.ParseId(url); // Wait until MINI_KIND thumbnail is generated. Bitmap miniThumb = MediaStore.Images.Thumbnails.GetThumbnail(cr, id, ThumbnailKind.MiniKind, null); // This is for backward compatibility. storeThumbnail(cr, miniThumb, id, 50F, 50F, 3); //ThumbnailKind id } else { cr.Delete(url, null, null); url = null; } } catch (Exception e) { if (url != null) { cr.Delete(url, null, null); url = null; } } if (url != null) { stringUrl = url.ToString(); } return(stringUrl); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.BikeAgenda); this.registerReturnButton(); // If GPS is installed for the geolocater.. if (GooglePlayService.IsGooglePlayServicesInstalled(this)) { // API client that will be used for the location apiClient = new GoogleApiClient.Builder(this, this, this).AddApi(LocationServices.API).Build(); // generate a location request that we will pass into a call for location updates locRequest = new LocationRequest(); // We get our location GetLocation(); } else { // GPS is not installed, error message & return to home. Log.Error("OnCreate", "Google Play Services is not installed"); Toast.MakeText(this, "Google Play Services is niet geinstalleerd!", ToastLength.Long).Show(); Finish(); } // The used UI elements DatePicker datePicker = (DatePicker)FindViewById(Resource.Id.datePicker); TimePicker timePicker = (TimePicker)FindViewById(Resource.Id.timePicker); timePicker.ClearFocus(); Button confirmButton = FindViewById <Button>(Resource.Id.datePickerSelect); // Confirm button & it's event handler. confirmButton.Click += delegate { // The date int cDay = datePicker.DayOfMonth; int cMonth = datePicker.Month; int cYear = datePicker.Year; // The time int cHour = (int)timePicker.CurrentHour; int cMin = (int)timePicker.CurrentMinute; // The starting times standard variables int cFirstHour = 0; int cFirstMin = 0; // If the minutes is less than 0 if you reduce it by 30 (for the first time) if (cMin - 30 < 0) { // Remove an hour cFirstHour = cHour - 1; // Remove the minutes so we can round the hours int removedMin = 30 - cMin; // Remove the leftover minutes from the rounded hour cFirstMin = 60 - removedMin; } else { // Same hours cFirstHour = cHour; // Reduced minutes cFirstMin = cMin - 30; } // Class that can save content for applications. ContentValues eventValues = new ContentValues(); // We think the standard id for a calendar is 1 on a device. eventValues.Put(CalendarContract.Events.InterfaceConsts.CalendarId, 1); // Title for the agenda item. eventValues.Put(CalendarContract.Events.InterfaceConsts.Title, "Fiets ophalen."); // Description for the agenda item. eventValues.Put(CalendarContract.Events.InterfaceConsts.Description, "Haal uw fiets op, de locatie is opgeslagen."); // Location for the agenda item. eventValues.Put(CalendarContract.Events.InterfaceConsts.EventLocation, streetName); // Convert to milliseconds so we can define a start date eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtstart, Helpers.convertToMilliseconds(cYear, cMonth, cDay, cFirstHour, cFirstMin)); // Convert to milliseconds so we can define a end date. eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtend, Helpers.convertToMilliseconds(cYear, cMonth, cDay, cHour, cMin)); // Define the timezones. eventValues.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, "Europe/Berlin"); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "Europe/Berlin"); // Insert the data into the agenda content. var uri = ContentResolver.Insert(CalendarContract.Events.ContentUri, eventValues); // Popup message Toast.MakeText(this, "Uw reminder is toevoegd!", ToastLength.Long).Show(); }; }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.LaunchDetail); //get the controls we want to put information into TextView nameText = (TextView)FindViewById(Resource.Id.name); TextView statusText = (TextView)FindViewById(Resource.Id.status); TextView startText = (TextView)FindViewById(Resource.Id.windowStart); TextView endText = (TextView)FindViewById(Resource.Id.windowEnd); TextView location = (TextView)FindViewById(Resource.Id.location); TextView url = (TextView)FindViewById(Resource.Id.watchLive); ImageView rocketImg = (ImageView)FindViewById(Resource.Id.rocketImg); //get the information that was passed over nameText.Text += Intent.GetStringExtra("name") ?? "Data not available"; int status = Intent.GetIntExtra("status", 0); switch (status) { case 0: statusText.Text = "Data not available"; break; case 1: statusText.Text += "Green"; statusText.SetTextColor(Android.Graphics.Color.Green); break; case 2: statusText.Text += "Red"; statusText.SetTextColor(Android.Graphics.Color.Red); break; case 3: statusText.Text += "Success"; statusText.SetTextColor(Android.Graphics.Color.Green); break; case 4: statusText.Text += "Failure"; statusText.SetTextColor(Android.Graphics.Color.Red); break; } startText.Text += Intent.GetStringExtra("start") ?? "Data not available"; endText.Text += Intent.GetStringExtra("end") ?? "Data not available"; location.Text += Intent.GetStringExtra("location") ?? "Data not available"; url.Text += Intent.GetStringExtra("url") ?? "No URL Available"; var image = GetImageBitmapFromUrl(Intent.GetStringExtra("rocketImg")); rocketImg.SetImageBitmap(image); //get the button for creating the calendar event Button calendarEvent = (Button)FindViewById(Resource.Id.calendarEvent); //click action to perform when the button is clicked //currently a work in progress calendarEvent.Click += (object sender, EventArgs e) => { ContentValues eventValues = new ContentValues(); eventValues.Put(CalendarContract.Events.InterfaceConsts.CalendarId, calID); eventValues.Put(CalendarContract.Events.InterfaceConsts.Title, nameText.Text); eventValues.Put(CalendarContract.Events.InterfaceConsts.Description, "Launch Event"); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS(2017, 12, 15, 10, 0)); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS(2017, 12, 15, 11, 0)); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, "UTC"); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "UTC"); var uri = ContentResolver.Insert(CalendarContract.Events.ContentUri, eventValues); Console.WriteLine("Uri for new event: {0}", uri); }; }
/* JAVA: * if(ringtone != null && ringtone.isPlaying()) * ringtone.stop(); * * Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); * //Uri uri = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE); * //Uri uri = RingtoneManager.getActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_RINGTONE); * ringtone = RingtoneManager.getRingtone(getApplicationContext(), uri); * * if(ringtone != null) * ringtone.play(); */ private void setAsRingtone(string audioName) { string folderName = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/" + Android.OS.Environment.DirectoryRingtones + "/"; string audioFile = audioName + ".mp3"; Log.Info(TAG, "Ringtones folder: " + folderName); Log.Info(TAG, "audio file: " + audioFile); var soundFilePath = Path.Combine(folderName, audioFile); Log.Info(TAG, "full path: " + soundFilePath); using (FileStream writeStream = File.OpenWrite(soundFilePath)) { //var readStream = context.Resources.OpenRawResource(soundId[pos]); //var readStream = Resources.OpenRawResource(audioName); var readStream = Assets.Open(audioFile); BinaryWriter writer = new BinaryWriter(writeStream); // create a buffer to hold the bytes byte[] buffer = new Byte[1024]; int bytesRead; // while the read method returns bytes keep writing them to the output stream while ((bytesRead = readStream.Read(buffer, 0, 1024)) > 0) { writeStream.Write(buffer, 0, bytesRead); } } //We now create a new content values object to store all the information about the ringtone. ContentValues values = new ContentValues(); //values.Put(MediaStore.MediaColumns.Data, fi2.DirectoryName); values.Put(MediaStore.MediaColumns.Data, soundFilePath); if (audioName == "bepohello") { values.Put(MediaStore.MediaColumns.Title, "Bepo Hello"); } else if (audioName == "beporooster") { values.Put(MediaStore.MediaColumns.Title, "Bepo rooster"); } //values.Put(MediaStore.MediaColumns.Title, "Lelux"); //values.Put(MediaStore.MediaColumns.Size, fi2.Length); values.Put(MediaStore.MediaColumns.MimeType, "audio/mp3"); values.Put(AudioColumns.Artist, "MARCELO"); values.Put(AudioColumns.IsRingtone, true); values.Put(AudioColumns.IsNotification, false); values.Put(AudioColumns.IsAlarm, false); values.Put(AudioColumns.IsMusic, false); // We put in the DDBB of MediaStore //Uri uri = MediaStore.Audio.Media.getContentUriForPath(f.getAbsolutePath()); //Uri newUri = getBaseContext().getContentResolver().insert(uri, values); // Set as default //RingtoneManager.setActualDefaultRingtoneUri(getBaseContext(), RingtoneManager.TYPE_RINGTONE, newUri); //Android.Net.Uri uri = Media.GetContentUriForPath(soundFilePath); //Android.Net.Uri newUri = ContentResolver.Insert(uri, values); var uri = Media.GetContentUriForPath(soundFilePath); //var uri = MediaStore.Audio.Media.GetContentUriForPath(soundFilePath); //var cr = this.ContentResolver; var newUri = cr.Insert(uri, values); //this.ContentResolver.Insert(Android.Provider.MediaStore.Audio.Media.ExternalContentUri, values); //Android.Net.Uri newUri = this.ContentResolver.Insert(uri, values); //Android.Net.Uri newUri = BaseContext.ContentResolver.Insert(uri, values); RingtoneManager.SetActualDefaultRingtoneUri(this, RingtoneType.Ringtone, newUri); Log.Info(TAG, "uri: " + uri); Log.Info(TAG, "newUri: " + newUri); }