Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all 79144 articles
Browse latest View live

Get number from Incoming call and then launch my app

$
0
0

Hi Geeks,

I have a requirement where I need to work in the following scenario.

When any user gets a call, identify the number, and launch my app in the background and insert a record in some table.

I searched through different forums and found BroadcastReceiver is the one by which I can get the incoming number.

However, I tried to implement this, but no success.

[BroadcastReceiver(Enabled =true)]
[IntentFilter(new[] { "com.App.CALLER_RECEIVER" })]
public class IncomingCallReader : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        switch (intent.Action)
        {
            case Intent.ActionNewOutgoingCall:
                Globals.ContactNumber = intent.GetStringExtra(Intent.ExtraPhoneNumber);
                var outboundPhoneNumber = intent.GetStringExtra(Intent.ExtraPhoneNumber);
                Toast.MakeText(context, $"Started: Outgoing Call to {outboundPhoneNumber}", ToastLength.Long).Show();
                break;
             case TelephonyManager.ActionPhoneStateChanged:
                var state = intent.GetStringExtra(TelephonyManager.ExtraState);
                if (state == TelephonyManager.ExtraStateIdle)
                    Toast.MakeText(context, "Phone Idle (call ended)", ToastLength.Long).Show();
                else if (state == TelephonyManager.ExtraStateOffhook)
                    Toast.MakeText(context, "Phone Off Hook", ToastLength.Long).Show();
                else if (state == TelephonyManager.ExtraStateRinging)
                    Toast.MakeText(context, "Phone Ringing", ToastLength.Long).Show();
                else if (state == TelephonyManager.ExtraIncomingNumber)
                {
                    var incomingPhoneNumber = intent.GetStringExtra(TelephonyManager.ExtraIncomingNumber);
                    Toast.MakeText(context, $"Incoming Number: {incomingPhoneNumber}", ToastLength.Long).Show();
                }
                break;
            default:
                break;
        }
    }


   protected override void OnCreate(Bundle savedInstanceState)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;
        base.OnCreate(savedInstanceState);
        Xam.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        RegisterReceiver(new IncomingCallReader(), new IntentFilter("com.uniconta.mobile_new.app"));
        LoadApplication(new App());
    }

Second Approach:

 public interface ICallReceiver
   {
    void OnReceive();
   }

public class IncomingCallReceiver: ICallReceiver
{
    public void OnReceive()
    {
        Intent intent = new Intent("com.uniconta.CALLER_RECEIVER");
        var incomingPhoneNumber = intent.GetStringExtra(TelephonyManager.ExtraIncomingNumber);
        Globals.ContactNumber = incomingPhoneNumber;
        Forms.Context.SendBroadcast(intent);
    }
} 

DependencyService.Get().OnReceive();

I want this method to be called whenever the user gets a call.

1st question - Is it possible to get the incoming call number in Xamarin forms?
2nd Question - is it possible to launch an app in the background when someone gets a call and app can do things in the background?

Thanks
Anand


Xam.Plugin.Media Saving photo in both internal storage and SD card on Android

$
0
0

I use Xam.Plugin.Media Camera option. My app takes photo and uploads this photo to remote server. I want the user to choose whether can save the picture or not save on phone while they use Xam.Plugin.Media Camera option. So I did a basic ui for this. After the user's choice, I set SaveToAlbum (true or false) It works on iOS good. But on android it doesn't work on SD card.

After taking photo using " await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions { } ) ", the following cases are belowing:

  • If "SaveToAlbum = true" and phone camera setting is SD card, Xam.Plugin.Media is save photo twice, one to internal storage and one to SD card. (it should save one photo just internal storage)
  • If "SaveToAlbum = true" and phone camera setting is internal storage, Xam.Plugin.Media is save photo twice, just internal storage. (it should save one photo just internal storage)
  • If "SaveToAlbum = false" and phone camera setting is SD card, Xam.Plugin.Media is save photo once, just SD card. (it should never save)
  • If "SaveToAlbum = false" and phone camera setting is internal storage, Xam.Plugin.Media is save photo once, just internal. (it should never save)

How can i fix this? Thank you.

Xamarin Forms, cannot generate IPA file for IOS project

$
0
0

Hello,

I have a Xamarin.Forms app that we run on Android, IOS and Windows. Android and Windows work fine and we have them deployed. IOS works fine in the Simulator, and I can install to an iPad via a USB cable. But, I have been unable to generate an IPA file for wider distribution.

When running the Release build (Build IPA is checked), all seems to go well but no IPA file is generated.

The only thing that looks awry is this warning message: "There is no available connection to the Mac, hence the task Xamarin.Messaging.Tasks.CopyFileFromMac will not be executed".

Our MacInCloud server is paired for the build session, so should be "available". But I assume this is why we are not getting the IPA file? Does that message imply that I could/should be able to find the file out on the MacInCloud server somewhere? I looked around, but could not see one.

VS.2019 is latest build, and NuGet Xamarin packages are also latest.

Can anyone give me some guidance on how to get our IPA generated?

Thanks for any help.

Bryan Hunt

How to consume Jar file in Xamarin forms UWP project?

$
0
0

Hi..
I am having a JAR file containing html images to view in WebView.
How to use that JAR file to view in my Xamarin forms UWP Project.

From Listview to Slider showing details

$
0
0

Have a Listview and with SelectedItemChangedEvent the details are showing on other page

Works fine.

But i found a Slider and is it possible to show the details in the Slider on the same page as the Listview and not on the other page ?

Fill the Listview from a Firebase database.

The Slider i made

https://xamaringuyshow.com/2020/06/21/xamarin-forms-bottom-slider/?utm_campaign=Weekly%2BXamarin&utm_medium=email&utm_source=Weekly_Xamarin_265 

Go to other page and show the details

async  void lstBal_ItemSelected(System.Object sender, Xamarin.Forms.SelectedItemChangedEventArgs e)
        {

                if (e.SelectedItem != null)
                {
                    await Navigation.PushAsync(new Waar
                    {
                        BindingContext = e.SelectedItem as Person
                    });
                lstBal.SelectedItem = null;
            }

        }

CarouselView does not show images

$
0
0

Hi
I have two Models and a ViewModels for articles and posts from DB . One of them like this

and i use BackgroundImage in CarouselView like this

And there is no problem with CarouselView and it shows images . But with another Model that likes this

and use like this

CarouselView does not show anythings . What's the problem ?

Export a scroll page to PDF

$
0
0

I need to convert my scroll page into the pdf in Xamarin forms. My Scroll page has contained so many elements and i need to export everything to the Pdf.

can anyone please help ?

Building app from scratch - help

$
0
0

Hi,

I am looking to build a cross platform native feel wellness app and take it through every stage of the development process and maintain it long term. As I wish to do so at as little as possible a cost I am considering doing it all by myself via Xamarin coding learned from scratch.

My question from a beginners perpective, with no experience in coding or app creation, is: is this possible/realistic, and what would be the time resource required to do so on my own? I wish to ask experienced personel in the field of app creation their opinion to give me an idea if this is possible before I spend so many hours doing so only to find out the hard way its not. Any help greatly appreciated, thanks in advance!

Best regards,
Brian.


How to make second bottom toolbar with buttons

$
0
0

I need to create bottom toolbar with buttons. It must be capable of such things as:

  • contain imaged buttons with occasional badges.
  • some buttons must act like commands (e.g. display alert message), others open random pages.
  • buttons added dynamically at runtime.
  • target platforms: IOS, Droid, UWP
  • toolbar can be hidden/shown at runtime

I tried few approaches, all with subjective restrictions:

TabbedPage

  • requires existent content pages.
  • cannot receive content of another page, not in tabbedpage list
  • buttons cannot act as commands, couldn't find a way to intercept "before change" event and stop it if neccessary.
  • no way to unselect button. One is always selected. This one is the most frustrating, because I thought about create a tabbed page in the bottom of main page with empty pages and zero content height.

Native bottom bar
Have examples for Droid
(docs.microsoft.com/en-us/xamarin/android/user-interface/controls/tool-bar/adding-a-second-toolbar)
and IOS
(docs.microsoft.com/en-us/xamarin/ios/user-interface/controls/creating-tabbed-applications)

  • cannot dynamically add/remove buttons
  • cannot dynamically add/remove toolbar
  • not universal (need to create xml android forms and weld it into page)

Hardcore manual mimic toolbar with Grids/Boxes

  • have to support all styles/effects to match othet Material-design/ios style

After couple days I stopped at variant three with drawing toolbar with grids, imagebuttons and circles.

The question is more of asking for advice. Is there a way to achive dynamic bottom toolbar with standard controls?

Thank you in advance.

On Platform values for font ionicons.woff

$
0
0

Hi

I am using custom font ionicons.woff and have used below;

    <ResourceDictionary>
        <OnPlatform x:TypeArguments="x:String" x:Key="ionicons">
            <On Platform="Android"
              Value="ionicons.woff#Regular" />
            <On Platform="iOS"
              Value="ioniconsr" />
        </OnPlatform>
    </ResourceDictionary>

However this is not working. What are the correct 'On Platform' values for font ionicons.woff and in general what is the method to get these values for a given font.

Thanks

Regards

Binding Library Error: How to make a method return an array of IDictionary ?

$
0
0

I am getting an error when I import a .aar file to integrate with a machine service.

My question is as per the title.

This the code I am trying to get:

[Register ("getSlots", "()[Ljava/util/HashMap;", "")]
        public unsafe global::System.Collections.Generic.IDictionary <string, byte[]> [] GetSlots ()
        {
            const string __id = "getSlots.()[Ljava/util/HashMap;";
            try {
                var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
                return (global::System.Collections.Generic.IDictionary<string, byte[]>[]) JNIEnv.GetArray (__rm.Handle, JniHandleOwnership.TransferLocalRef, typeof (global::System.Collections.Generic.IDictionary<string, byte[]>));
            } finally {
            }
        }

This is the code I am getting:

[Register ("getSlots", "()[Ljava/util/HashMap;", "")]
        public unsafe global::System.Collections.Generic.IDictionary <string, byte[]>GetSlots ()
        {
            const string __id = "getSlots.()[Ljava/util/HashMap;";
            try {
                var __rm = _members.InstanceMethods.InvokeNonvirtualObjectMethod (__id, this, null);
                return (global::System.Collections.Generic.IDictionary<string, byte[]>[]) JNIEnv.GetArray (__rm.Handle, JniHandleOwnership.TransferLocalRef, typeof (global::System.Collections.Generic.IDictionary<string, byte[]>));
            } finally {
            }
        }

I need a method that returns an array IDictionary <string, byte[]>[], but I am getting IDictionary <string, byte[]>

This is the code that is in metadata.xml

<attr path="/api/package[@name='br.com.uol.pagseguro.plugpagservice.wrapper']/class[@name='PlugPagNFCResult']/method[@name='getSlots' and count(parameter)=0]" name="managedReturn">System.Collections.Generic.IDictionary &lt;string, byte[]&gt;</attr>

But every time I write "[]", after ">", it doesn't appear to form an array!

Could you help me with this?

Create Multiple Table with SQLite Database

$
0
0

hello, xamarians,
I am creating a project and I want to need to more than 3 tables but I don't understand how to create
please help me out.

AppThemeBinding not working

$
0
0

Hi,
Using latest Xamarin Forms 4.7.0.968.
SfButton.BackgroundColor="{AppThemeBinding Light={StaticResource PrimaryColorLight}, Dark={StaticResource PrimaryColorDark }}"
is not working.
Thank you

Unable to get password autofill effect to work

$
0
0

I am developing a Xamarin.Forms app for iOS and Android. So far i only tested on iOS since that is the client priority.

i have followed the guide here to setup the password autofill but it does not seems to work. I follow the guide till the Domain association section since from what i read it does not seems to be needed for my case as my app do not have a registration function in the website or app.

I am assuming the linking of AutofillEffect.cs and the AppleAutofillEffect.cs is not link properly.

Code for AutofillEfect.cs
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;

namespace MyProject
{
    public class AutofillEffect : RoutingEffect
    {
        public AutofillContentType Type { get; set; }

        public AutofillEffect() : base("PasswordAutofill." + nameof(AutofillEffect))
        {
        }
    }
}

Code for AppleAutofillEffect.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using Foundation;
using UIKit;

[assembly: Xamarin.Forms.ResolutionGroupName("PasswordAutofill")]
[assembly: Xamarin.Forms.ExportEffect(typeof(MyProject.iOS.AppleAutofillEffect), "AutofillEffect")]
namespace MyProject.iOS
{
    public class AppleAutofillEffect : PlatformEffect
    {
        protected override void OnAttached()
        {
            var effect = (AutofillEffect)Element.Effects
                .FirstOrDefault(e => e is AutofillEffect);
            if (effect != null
                && UIDevice.CurrentDevice.CheckSystemVersion(11, 0)
                && Control is UITextField textField)
            {
                switch (effect.Type)
                {
                    case AutofillContentType.None:
                        textField.TextContentType = NSString.Empty;
                        break;
                    case AutofillContentType.Username:
                        textField.TextContentType = UITextContentType.Username;
                        break;
                    case AutofillContentType.Password:
                        textField.TextContentType = UITextContentType.Password;
                        break;
                }
            }
        }

        protected override void OnDetached()
        {
            if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)
                && Control is UITextField textField)
            {
                textField.TextContentType = NSString.Empty;
            }
        }
    }
}

Login.xaml

<StackLayout x:Name="loginForm">
         <Label Text="Username" TextColor="#0071BB" FontSize="16" FontFamily="Roboto" HorizontalTextAlignment="Center"></Label>                            
          <inputLayout:SfTextInputLayout OutlineCornerRadius="20" ContainerBackgroundColor="#000" >
                  <Entry x:Name="txtUsername" BackgroundColor="#FFF" TextColor="#FFF" FontSize="20" FontFamily="Roboto">
                           <Entry.Effects>
                                  <local1:AutofillEffect Type="Username" />
                           </Entry.Effects>
                     </Entry>
            </inputLayout:SfTextInputLayout>
           <Label Text="Password" TextColor="#0071BB" FontSize="16" FontFamily="Roboto" HorizontalTextAlignment="Center"></Label>
           <inputLayout:SfTextInputLayout OutlineCornerRadius="20"  ContainerBackgroundColor="#000">
                    <Entry x:Name="txtPassword" BackgroundColor="#FFF" TextColor="#FFF" FontSize="20" FontFamily="Roboto" IsPassword="True">
                            <Entry.Effects>
                                    <local1:AutofillEffect Type="Password" />
                            </Entry.Effects>
                     </Entry>
             </inputLayout:SfTextInputLayout>
            <buttons:SfButton Text="Login" CornerRadius="20" x:Name="btnLogin" Clicked="btnLogin_Clicked" FontFamily="Roboto-Light" FontSize="20" 
                                                          BackgroundColor="#0071BB" TextColor="#FFF" WidthRequest="150"/>
</StackLayout>

Directory Structure

  • MyProject.sln
    ---------- MyProject
    ----------------AutofillEffect .cs
    ----------------Views
    ---------------------Login.xaml
    -----------MyProject.iOS
    -----------------AppleAutofillEffect .cs

Printerest like CollectionView renderer for iOS in Xamarin.Forms?

$
0
0

After some research I could find the custom renderer for CollectionView in Android and it works great, but I couldn't find the equalant for iOS. Please help me create it for iOS. Thanks

Custom CollectionView for android:

[assembly: ExportRenderer(typeof(CollectionView), typeof(CustomCollectionViewRenderer))]
namespace App.Droid
{
    public class CustomCollectionViewRenderer : CollectionViewRenderer
    {
        public CustomCollectionViewRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<ItemsView> elementChangedEvent)
        {
            base.OnElementChanged(elementChangedEvent);

            if (elementChangedEvent.NewElement != null)
            {
                StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.Vertical);
                SetLayoutManager(manager);
            }
        }
    }
}

Custom CollectionView for iOS: ??


Xamarin.Forms Fiddle (Code, Scan and Run)

$
0
0

With Web Atoms Playground, you can create Xamarin.Forms apps in JavaScript. You can write JSX instead of Xaml and that gives you powerful multibinding and allows you to push code on production.

  1. Side by side versioning
  2. Divide large app in multiple javascript npm packages
  3. No need to create multiple apps and integrate all of them
  4. Debug JavaScript in Chrome using V8 Inspector protocol for Android
  5. Debug JavaScript in Safari debugger for iOS

Download the App

App Store

Play Store

Open Demo

Shapes

https://www.webatoms.in/play/demo/shapes/1
https://www.webatoms.in/play/demo/rating/4

Explore new feature "Shapes" of Xamarin.Forms 4.7.

Master Detail

https://www.webatoms.in/play/demo/master-detail

Application with drawer and multiple pages, using navigation service to open pages, retrieve result and load unpacked pages.

List View

https://www.webatoms.in/play/demo/list

Explore list view with Cell bindings. Using two way binding to update the selection.

Form

https://www.webatoms.in/play/demo/form/3

Explore validation sample with simple form.

Tabbed Page

https://www.webatoms.in/play/demo/tabbed-page/3

Explore tabbed pages.

Scan QR Code

Scan and Play

Console Logging

You can see console of your device and you can log errors/warnings in the console in your code.

Setting Initial Value to Picker MVVM Xamarin Sets ObservableCollection to NULL

$
0
0

I'm trying to set the initalvalue of a picker in a a list view. However, when I have tried to do this through many methods, nothing is set and the underlying source (the property IngredientName for each element of downloadedRecipeIngredients) (the array is initially correct prior to being stored in teh ObserverableCollection) is set to null. This can be seen when utilizing breakpoints in the for loop which get data and stores it to DownloadedRecipeIngredients.

The picker is populated with a list of strings and the choices are displayed correctly when you click on the picker. This list is stored in _listIngredients. These are the possible ingredients one can utilize with a given recipe.

I'm trying to set the initial value to IngredientName which is also a string.

Please help. Thanks.

The picker in question is named 'pickerIngredientancestor'

XAML

<ContentPage.Content>
    <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

        <ListView HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" ItemsSource="{Binding downloadedRecipeIngredients}">  <!--SelectedItem="{Binding SelectedItem}"-->
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal">
                            <Picker x:Name="pickerIngredientancestor" HorizontalOptions = "StartAndExpand" ItemsSource="{Binding listIngredients, Source={RelativeSource AncestorType={x:Type viewModel:testPageViewModel}}}" SelectedItem="{Binding IngredientName}" WidthRequest="100"/>
                            <Entry Text="{Binding Comments}" VerticalOptions="CenterAndExpand" HorizontalOptions="StartAndExpand" />
                            <Label Text="Clickable Label" VerticalOptions="CenterAndExpand" HorizontalOptions="EndAndExpand">
                                <Label.GestureRecognizers>
                                    <TapGestureRecognizer Command="{Binding Path=BindingContext.btnPress, Source={x:Reference Page}}" CommandParameter="{Binding .}" />
                                </Label.GestureRecognizers>
                            </Label>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage.Content>

VIEW MODEL

public class testPageViewModel : BaseViewModel
{
    ObservableCollection<clRecipeIngredient> _downloadedRecipeIngredients = new ObservableCollection<clRecipeIngredient>();
    public ObservableCollection<clRecipeIngredient> downloadedRecipeIngredients
    { 
        get { return _downloadedRecipeIngredients; } 
        set 
        {
            _downloadedRecipeIngredients = value;
            OnPropertyChanged();
        } 
    }

    ObservableCollection<string> _listIngredients = new ObservableCollection<string>();
    public ObservableCollection<string> listIngredients { get { return _listIngredients; } }

    private clRecipeDataBase recipeDataBase;

    public testPageViewModel()
    {
        recipeDataBase = new clRecipeDataBase();

        getData();
    }

    async void getData()
    {
        //PICKER INGREDIENT DATA
        clIngredient[] tmp = await recipeDataBase.getIngredientData();
        //picker.ItemsSource = null;

        for (int i = 0; i < tmp.Length; i++)
        {
            _listIngredients.Add(tmp[i].IngredientName);
        }

        clRecipeIngredient[] arr = await recipeDataBase.getRecipeIngredientsDataByRecipeID(310); //HARDCODED TO CRISPY PIZZA RECIPE
        clRecipeIngredient tmp1;
        for (int i = 0; i < arr.Length; i++)
        {
            _downloadedRecipeIngredients.Add(arr[i]);
        }


    }

Trying to get the value of a picker's selectedItem within a listview (MVVM)

$
0
0

Need some direction/help here guys. Similar to a basic contacts app - I'm building a customer entry screen and need a drop down for contact types (phone, email, etc). I figured out how to populate the picker(s) by explicitly defining the path and source but I can't seem to get SelectedItem to do anything. My expectation is set the default value of the picker with whats in the record and also be able to change that value.

<ListView x:Name="ContactListView" ItemsSource="{Binding Customer.ContactList}" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout>
<Picker
ItemsSource="{Binding Path=BindingContext.ContactTypes, Source={x:Reference ContactListView} }"
ItemDisplayBinding="{Binding TypeName}"
SelectedItem="{Binding TypeName, Mode=TwoWay}"
/>
<Entry Text="{Binding Value}" />
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

The ViewModel attached to this page has an Customer object which has a nested contact list in it (defined at the list view). Each contact has a picker with multiple types and a value field so they can type in the corresponding data.

Navigation Confusion

$
0
0

I am obviously missing something or not understanding the Navigation correctly. I have a UserLogin page that when the user logs in they are sent to another page for two factor authentication.

await Navigation.PushModalAsync(new TwoFactorPage(UserKey, TicketValue));

this works fine and it the user get the two factor correct I send them onto the main page

await Navigation.PushModalAsync(new MainPage(UserKey));

But if the user gets the two factor incorrect I want to send them back to the userlogin page but everything I do results in a error.
I thought I was supposed to use

await Navigation.PopAsync();

but that doesn't work, give the me lovely "is not supported globally on Android, please use a NavigationPage"

So am I doing my page navigation wrong? How do I go back a page?

Shell: Register routes when app starts (before you start AppShell

$
0
0

Hi there
in my main AppShell I register routes like this
[code]
public partial class MainPage : Xamarin.Forms.Shell
{
public MainPage()
{
InitializeComponent();
RegisterRoutes(); //Register page route so we can navigate to the page
}

    //Register page route so we can navigate to the page
    public void RegisterRoutes()
    {
        Routing.RegisterRoute("showImage", typeof(ShowImagePage));
    }
}

[/code]
if I first start the app so it goes to a home page I can navigate to here fine
my App.xaml.cs looks like this
[code]
public partial class App : Application
{
public App()
{
InitializeComponent();

        MainPage = new MainPage();
    }

    protected override void OnStart()
    {
        // Handle when your app starts
    }

    protected override void OnSleep()
    {
        // Handle when your app sleeps
    }

    protected override void OnResume()
    {
        // Handle when your app resumes
    }

    //Show image that user wants to share with our app
    public void ShowImage() //this method couses problems if I call this method direcly from native part b4 my app shows home page my app will crash
    {
        Task.Run(async () => await Shell.Current.GoToAsync("showImage")); //Go to the route we registered
    }

[/code]

but in my Native part I hook insto share dialog and want to show this showImage page when user shares a file
[code]
[Activity(Label = "clip2url", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
[IntentFilter(new[] { Intent.ActionSend }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = @image/jpeg)] //Declaration to handle incoming files via share dialog
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(savedInstanceState);

        global::Xamarin.Forms.Forms.SetFlags("Shell_Experimental", "Visual_Experimental", "CollectionView_Experimental", "FastRenderers_Experimental");
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

        //Init Xmarin Plugins
        ImageCircle.Forms.Plugin.Droid.ImageCircleRenderer.Init(); //Init native Image library

        //To get acsess to Xamarin Forms part
        var mainForms = new App();
        LoadApplication(mainForms);

        //Here we tell out app what do we want to do with this share dialog data
        if (Intent.Action == Intent.ActionSend)
        {
            mainForms.ShowImage(); //here I call my ShowImage method and I want the page to be displayed but now my home page a seperate page and I want to then navigate back to home page
        }
    }
    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

[/code]

now if I start the app from home screen then try to share file it works fine, but if I start my app from share dialog, then my app crashes as routes for some reason don't get registered and I cannot navigate to my ShowImage page if I didn't first open my MainPage

Hope someone can shed some light to this and help me figure out whats is wrong :smile:

Thanks

Viewing all 79144 articles
Browse latest View live


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