How do I call a method located in an Android project from a Portable Class Library Project in Xamarin.Forms?

This may seem like a silly question, but since I am completely new to Xamarin, I will go for it.

So I have a Xamarin.Forms solution and have an Android project plus a portable class library. I am calling the start page from MainActivity.cs in an Android project, which itself calls the first page from the forms defined in the Portable Class Library project (by calling App.GetMainPage ()). Now I want to add a click event to one of my forms to get the current location of the device. Apparently in order to get the location I have to implement it in an android project. So how can I call the GetLocation method from my click event inside the Portable Class Library project? Any help would be greatly appreciated. Sorry for the possible duplicate.

+3


source to share


1 answer


The solution is indeed in the link provided if you are using Xamarin.Forms.Labs. If you are using Xamarin.Forms, this is pretty much the same as what you should do using DependencyService. This is easier than it sounds. http://developer.xamarin.com/guides/cross-platform/xamarin-forms/dependency-service/

I suggest reading this post where I nearly broke my brain trying to understand. http://forums.xamarin.com/discussion/comment/95717

For convenience, here's a working example that you could adapt if you haven't finished your work yet:

Create an interface in your Xamarin.Forms project.

using Klaim.Interfaces;
using Xamarin.Forms;

namespace Klaim.Interfaces
{
    public interface IImageResizer
    {
        byte[] ResizeImage (byte[] imageData, float width, float height);
    }
}

      



Create service / custom renderer in your android project.

using Android.App;
using Android.Graphics;
using Klaim.Interfaces;
using Klaim.Droid.Renderers;
using System;
using System.IO;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: Xamarin.Forms.Dependency (typeof (ImageResizer_Android))]
namespace Klaim.Droid.Renderers
{
    public class ImageResizer_Android : IImageResizer
    {
        public ImageResizer_Android () {}
        public byte[] ResizeImage (byte[] imageData, float width, float height)
        {

            // Load the bitmap
            Bitmap originalImage = BitmapFactory.DecodeByteArray (imageData, 0, imageData.Length);
            Bitmap resizedImage = Bitmap.CreateScaledBitmap(originalImage, (int)width, (int)height, false);

            using (MemoryStream ms = new MemoryStream())
            {
                resizedImage.Compress (Bitmap.CompressFormat.Jpeg, 100, ms);
                return ms.ToArray ();
            }
        }
    }
}

      

So when you call this:

byte[] test = DependencyService.Get<IImageResizer>().ResizeImage(AByteArrayHereCauseFun, 400, 400);

      

It executes Android code and returns the value to your Forms project.

+9


source







All Articles