Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 204402

Best practice for calling an Android Activity with a Dependency Service

$
0
0

I have a PCL that defines an Interface (IPictureTaker). From a viewmodel within the PCL, I use the DependencyService to call my SnapPic method :
public interface IPictureTaker { void SnapPic(); }
In the view model:

public void ExecuteMethod() { IPictureTaker pictureTaker = DependencyService.Get<IPictureTaker>(); pictureTaker.SnapPic(); }

I implement the interface in the MainActivity of the Android Project and call activity.StartActivityForResult:

`public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity, IPictureTaker
{
//OnCreate omitted

    public void SnapPic()
    {
        var activity = Forms.Context as Activity;

        var picker = new MediaPicker(activity);
        var intent = picker.GetTakePhotoUI(new StoreCameraMediaOptions
        {
            Name = "profile.jpg",
            Directory = "Krizzma"
        });
        activity.StartActivityForResult(intent, 1);
    }

protected override async void OnActivityResult(int requestCode, Result resultCode,
        Android.Content.Intent data)
    {
        if (resultCode == Result.Canceled)
            return;

        var mediaFile = await data.GetMediaFileExtraAsync(Forms.Context);

        WriteImageToDB(mediaFile);

        MessagingCenter.Send<IPictureTaker, Stream>(this, "pictureTaken", mediaFile.GetStream());

    }   

}`

My Question: I would prefer to not use the MainActivity for this purpose as I plan to have multiple interfaces similar to this one and it feels wrong to have to handle which method was called inside of the OnActivityResult. I have tried creating a "TakePictureActivity" with the exact same code and the SnapPic method is called correctly, but OnActivityResult is called in the MainAcitivty. I believe this is because Forms.Context is the MainActivity. I have tried starting the TakePictureActivity from within the SnapPic method, but was unsuccessful and it also does not seem to be the correct way to go about it.

Any suggestions on how to properly implement this would be appreciated.


Viewing all articles
Browse latest Browse all 204402

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>