Home > Back-end >  Run my app when a file with custom extension is selected (and do something)
Run my app when a file with custom extension is selected (and do something)

Time:11-24

I'm trying to write my first cross platform app in Xamarin using mvvm. The app records items (payments) inserted by the user and does some stuff (previsions and other math).

I wrote the code to add/update/delete/show items and when a item is added the app save the item writing a file with a custom extension (*.dinero) that contains all information about the item, so asynchronously the app load all files at the start.

I embedded a function that send by email these files in order to allow to another user to add the same item to its items list.

My question is how can I associate the the custom file extension to my app and how implement a procedure that open the "newItempage" to allow the user to save the item to its files?

I found the question Associate file extension with Xamarin Android application but I can't understand how to use it (where i have to write the code reported in the answer).

CodePudding user response:

I Answer my question in order to make others life a little simple. To associate files with the app that allow to start the app when the event "tap on a file with custom extension" occurs we have to add in the MainActivity.cs above the class declariation:

 [IntentFilter(new[] { Android.Content.Intent.ActionView }, 
Categories = new[] { Android.Content.Intent.CategoryDefault }, 
DataMimeType = "application/*", DataPathPattern = "*.Dinero")]

So in the method OnCreate we have to add the if statement to handle the intent data:

if ( Intent.Action== Android.Content.Intent.ActionView)
{
      string filecontent = GetFileContent(Intent);
}

in my situation, I would to read the Dinero file. The intent data does not contains the file path but the URI, so to read the file content we need to call the ContentResolver in order to create a stream and finally read the file content:

string GetFileContent(Android.Content.Intent Intent)
        {
            Android.Net.Uri uridata = Intent.Data;
            StreamReader streamread = new StreamReader(ContentResolver.OpenInputStream(uridata));
            string content = streamread.ReadToEnd();
            return content;
        }
  • Related