Is there any possibility to open Contacts App in Xamarin IOS - c#

Is there any possibility to open Contacts App in Xamarin IOS,
For android the below code worked for me.
var activity = Forms.Context as Activity;
var intent = new Intent(Intent.ActionInsert);
intent.SetType(ContactsContract.Contacts.ContentType);
activity.StartActivity(intent);
Where as for IOS I have't find any code can any one have solution for this.

Apple has released two new frameworks, Contacts and ContactsUI, that replace the existing Address Book and Address Book UI frameworks used by iOS 8 and earlier.
You could use these two frameworks to deal with all situation which involve contacts.
To make it clear, I create a simple app to show how to display contact app in ios.
you can open the contacts app with code like:
public override void ViewDidLoad()
{
base.ViewDidLoad();
picker1.TouchDown += Picker1_TouchDown;
}
private void Picker1_TouchDown(object sender, EventArgs e)
{ //create a picker
var picker = new CNContactPickerViewController();
//set the delegate
picker.Delegate = new ContactPickerDelegate();
//display picker
PresentViewController(picker, true, null);
}
The ContactPickerDelegate is what you need to create and used to respond to the user's interaction with the picker.
The code is like:
public class ContactPickerDelegate: CNContactPickerDelegate
{
#region Constructors
public ContactPickerDelegate ()
{
}
public ContactPickerDelegate (IntPtr handle) : base (handle)
{
}
#endregion
#region Override Methods
public override void ContactPickerDidCancel (CNContactPickerViewController picker)
{
Console.WriteLine ("User canceled picker");
}
public override void DidSelectContact (CNContactPickerViewController picker, CNContact contact)
{
Console.WriteLine ("Selected: {0}", contact);
}
public override void DidSelectContactProperty (CNContactPickerViewController picker, CNContactProperty contactProperty)
{
Console.WriteLine ("Selected Property: {0}", contactProperty);
}
#endregion
}
Screenshots:
For more information, you can refer to https://learn.microsoft.com/en-us/xamarin/ios/platform/contacts

Related

What is the base function name for Menu and Home buttonPressed? Xamarin Form C#

I am trying to find other ButtonPressed base functions (Home & Menu), but i could not find it.
Is anyone know how to control or execute events when the Menu and Home button is pressed in Xamarin Form C#?
According to my query, there is no directly used function.
I realized this function by broadcasting.
Here is my solution(All the code is added in Android.MainActivity):
Register the broadcast in OnCreate of Android.MainActivity.
RegisterReceiver(new broadcastReceiver(), new IntentFilter(
Intent.ActionCloseSystemDialogs));
Realize the internal operation of broadcasting.
[BroadcastReceiver]
public class broadcastReceiver : BroadcastReceiver
{
string SYSTEM_REASON = "reason";
string SYSTEM_HOME_KEY = "homekey";
string SYSTEM_HOME_KEY_LONG = "recentapps";
public override void OnReceive(Context context, Intent intent)
{
string action = intent.Action;
if (action.Equals(Intent.ActionCloseSystemDialogs))
{
string reason = intent.GetStringExtra(SYSTEM_REASON);
if (reason.Equals(SYSTEM_HOME_KEY))
{
Console.WriteLine("Home click");
}
else if (reason.Equals(SYSTEM_HOME_KEY_LONG))
{
Console.WriteLine("Menu click");
}
}
}
}
Here is the screenshot:

Passing a string from an event to MainActivity in Android Xamarin Visual Studio

The project is done in Visual Studio with Xamarin and targeted for Android.
In my simple project I have 1 activity (MainActivity). Here I create an instance of a Scanner object that will sit in background and listen for iBeacons. Once the scanner has been created I call a Start method on the scanner object.
In the constructor of the Scanner object, there will be setup an instance of a Listener object. This instance is called when ever a beacon is detected.
Cut short – my main activity makes an instance of a scanner object. On creation of the scanner object a listener object is created. This listener object will be activated when a beacon is detected.
In my MainActivity I have a multiline TextView. I want it to show the beacons found in the listener object.
What is the best way to pass this beacon ID (string) to the TextView in the main activity?
I’m new to programming in Android, so all the different concepts with blocks, intents and what have you, are a bit confusing. I would have thought it was straight forward passing data from a listener event to the TextView but this has proven more difficult then expected.
I don’t mind going slow – so please feel free to elaborate and consider me the novice I am :-D
UPDATE:
I have edited the code to make it as short as possible, and pasted it below. Hope this gives an idea.
[Activity(Label = "DeviceScanSample", MainLauncher = true, Icon = "#mipmap/icon")]
public class MainActivity : Activity
{
KontaktScanner scanner;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
// Initialize Scanner
scanner = new KontaktScanner(this);
// Button actions
startScanButton.Click += delegate
{
if (CheckPermission(Manifest.Permission.AccessCoarseLocation))
{
// Start devices scan
scanner.Start();
}
else
{
// Ask for permissions if needed
...
}
};
}
}
public class KontaktScanner : Java.Lang.Object, IOnServiceReadyListener
{
IProximityManager proximityManager;
public KontaktScanner(Context context)
{
// Set Space listener
proximityManager.SetSpaceListener(new KontaktSimpleSpaceListener());
}
public void Start()
{
proximityManager.Connect(this);
}
}
class KontaktSimpleSpaceListener : SimpleSpaceListener
{
public void OnRegionEntered(IBeaconRegion beaconRegion)
{
Log.Info(TAG, string.Format("Entered {0} region", beaconRegion.Identifier));
}
public void OnRegionAbandoned(IBeaconRegion beaconRegion)
{
Log.Info(TAG, string.Format("Abandoned {0} region", beaconRegion.Identifier));
}
}
Try something like this:
Pass the context here:
public KontaktScanner(Activity activity)
{
// Set Space listener
proximityManager.SetSpaceListener(new KontaktSimpleSpaceListener(activity));
}
Then:
class KontaktSimpleSpaceListener : SimpleSpaceListener
{
Activity context
public KontaktSimpleSpaceListener(Activity activity)
{
this.context = activity;
}
public void OnRegionEntered(IBeaconRegion beaconRegion)
{
Log.Info(TAG, string.Format("Entered {0} region", beaconRegion.Identifier));
MainActivity myActivity = (MainActivity) context;
myActivity.updateTextView("My Data");// pass the string here.
}
public void OnRegionAbandoned(IBeaconRegion beaconRegion)
{
Log.Info(TAG, string.Format("Abandoned {0} region", beaconRegion.Identifier));
MainActivity myActivity = (MainActivity) context;
myActivity.updateTextView("My another data");// pass the string here.
}
}
Then create method in MainActivity:
public void updateTextView(string s)
{
RunOnUiThread(() =>
{
yourTextView.Text = s;//set your TextView here
});
}
I have not checked the syntax but something like this should work.

Get current Activity - Xamarin Android

I am developing an portable App for Android and iOS. My current function is taking a Screenshot and use that image in the code. Therefor I have an Interface in the portable library.
public interface IFileSystemService
{
string GetAppDataFolder();
}
I am taking the Screenshot also in the portable Library with the following code:
static public bool TakeScreenshot()
{
try
{
byte[] ScreenshotBytes = DependencyService.Get<Interface.IScreenshotManager>().TakeScreenshot();
return true;
}
catch (Exception ex)
{
}
return false;
}
This either calls the Android or the iOS version.
Android:
class ScreenshotManagerAndroid : IScreenshotManager
{
public static Activity Activity { get; set; }
public byte[] TakeScreenshot()
{
if (Activity == null)
{
throw new Exception("You have to set ScreenshotManager.Activity in your Android project");
}
var view = Activity.Window.DecorView;
view.DrawingCacheEnabled = true;
Bitmap bitmap = view.GetDrawingCache(true);
byte[] bitmapData;
using (var stream = new MemoryStream())
{
bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
bitmapData = stream.ToArray();
}
return bitmapData;
}
The question now is to get the current Activity from my app.
A better way would be to use the Standalone Current Activity Plugin or the Current Activity Property in the Xamarin Essentials Plugin. Then you could just do:
Standalone: CrossCurrentActivity.Current.Activity
Xamarin Essentials: Platform.CurrentActivity
If you do not want to use a plugin and you only have 1 Activity in your app, you could get away with assigning a static variable in MainActivity and referencing that where ever you needed it like this:
public class MainActivity : FormsApplicationActivity {
public static Context Context;
public MainActivity () {
Context = this;
}
}
If you needed Context within a custom renderer, you would want to use the Context passed into the constructor, like this:
public class MyEntryRenderer : EntryRenderer {
private readonly Context _context;
public MyEntryRenderer(Context context) : base(context) {
_context = context;
}
// Now use _context or ((Activity)_context) any where you need to (just make sure you pass it into the base constructor)
}
The old deprecated way would be Context view = (Activity)Xamarin.Forms.Forms.Context
Xamarin automatically assigns the Activity to Forms.Context.
Since the release of Xamarin 2.5, Xamarin.Forms.Forms.Context is obsolete. The Context can now be obtained as follows:
var currentContext = Android.App.Application.Context;
var activity = (Activity)Forms.Context;
or if you are using MainActivity
var activity = (MainActivity)Forms.Context;
If you are using Xamarin Essentials 1.5 or higher, then you can use Platform.CurrentActivity. This is basically the equivalent of using the CurrentActivity plugin.
Ensure you initialise this correctly as per the instructions ie. in MainActivity OnCreate add the following line
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
I was trying to do something similar in Xamarin 5 and am having some luck in both my Android and iOS versions using
Shell.Current.CurrentPage
So something happens like a screenshot or a login and that method (whatever it is) can fire a static event so that any interested activity can look for itself whether it's the active view or not, and if so consume the data (byte array etc.) transported by the event.
class FileChooserPage : ContentPage
{
public FileChooserPage()
{
InitializeComponent();
GoogleDriveService.Authenticated += GoogleDriveService_Authenticated;
}
private void GoogleDriveService_Authenticated(object sender, EventArgs e)
{
if (ReferenceEquals(this, Shell.Current.CurrentPage))
{
Populate(e);
}
}
}

MessageBox Display Once

I was wondering if there was a way to display a messagebox in WP8 just once i.e. on app opening.
I have the following code already, very basic.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
MessageBox.Show("Hi");
}
However, this shows every time the app is opened. I only want it to show the first time.
Is that possible?
I have used this successfully in WP 8.0 Silverlight apps. Create a reusable class, OneTimeDialog:
using System.Windows;
using System.IO.IsolatedStorage;
namespace MyApp
{
public static class OneTimeDialog
{
private static readonly IsolatedStorageSettings _settings = IsolatedStorageSettings.ApplicationSettings;
public static void Show(string uniqueKey, string title, string message)
{
if (_settings.Contains(uniqueKey)) return;
MessageBox.Show(message, title, MessageBoxButton.OK);
_settings.Add(uniqueKey, true);
_settings.Save();
}
}
}
Then use it anywhere in your app, like this:
OneTimeDialog.Show("WelcomeDialog", "Welcome", "Welcome to my app! You'll only see this once.")
Showing a "Hint" or "Welcome" dialog just once is helpful in lots of different types of apps, so I actually have the code above in a Portable Class Library so I can reference it from multiple projects.
Since you need to persist a state across sessions, an isolated storage key-value pair is a good choice. Just check before, and then update:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
var settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.ContainsKey("messageShown") && (bool)settings["messageShown"] == true)
{
MessageBox.Show("Hi");
settings["messageShown"] = true;
}
}

Mono for Android Location using C# & VS 2010

I am trying to create a simple app to get user coordinates on an Android phone using VS 2010 and Mono for Android. All samples seem to be in java which, as I'm not a java developer, is confusing. If anyone has some sample code using only C# it would be much appreciated.
You can create a listener by implementing the ILocationListener interface. This is a sample for an activity that also acts as a location listener (though it can be a separate class if you want too):
[Activity(Label = "Location Demo")]
public class LocationActivity : Activity, ILocationListener
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
var locationManager = (LocationManager)GetSystemService(LocationService);
var criteria = new Criteria { Accuracy = Accuracy.NoRequirement };
string bestProvider = locationManager.GetBestProvider(criteria, true);
locationManager.RequestLocationUpdates(bestProvider, 5000, 2, this);
}
public void OnLocationChanged(Location location)
{
}
public void OnProviderDisabled(string provider)
{
}
public void OnProviderEnabled(string provider)
{
}
public void OnStatusChanged(string provider, Availability status, Bundle extras)
{
}
}
I have a similar sample up here that reads in the coordinates and prints them to the screen.

Categories

Resources