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

Syncfusion.Xamarin.SfNumericUpDown


How to implement Horizontal ListView in Xamarin Forms.

$
0
0

We want to implement horizontal listview in our xamarin forms application, How it is possible?
Any other solution for this, please share.
Thanks in advance...

Help I can't get a user's data when I log in

$
0
0

I am using MVVM and in my login VIewModel I have done the GetUser part and in an ApiService class I have the service
Then I must receive the data when I send the TOKEN that I generate when I log in
and TOKEN I receive it well but it does not generate user data
User comes out null
this is my MVVM
User user = new User();
user = await apiService.GetUser(
"URLBASE",
"/api",
"/datosUsuario",
response.token);

This is mi ApiService

public async Task<User> GetUser(
        string urlBase,
        string servicePrefix,
        string controller,
        string Token)
    {
        try
        {
            var model = new UserRequest
            {
                token = Token
            };
            User user = new User();
            var diccionario = new List<KeyValuePair<string, string>>();
            diccionario.Add(new KeyValuePair<string, string>("token", Token));
            var cliente = new HttpClient();
            cliente.BaseAddress = new Uri(urlBase);
            var url = string.Format("{0}{1}{2}", cliente.BaseAddress, servicePrefix, controller);
            var req = new HttpRequestMessage(HttpMethod.Post, url)
            { Content = new FormUrlEncodedContent(diccionario) };
            var response = await cliente.SendAsync(req);
            if (!response.IsSuccessStatusCode)
    {
                  return null;
            }
            var result = await response.Content.ReadAsStringAsync();
            user = JsonConvert.DeserializeObject<User>(result);
            return new User
            {


            };

        }
        catch 
        {
            return null;
        }
    }

How to embed ZXing scanner in PageRenderer/Fragment/View into Xamarin.Forms ContentPage?

$
0
0

Hi Everyone!

I want to have ZXing.Net.Mobile barcodes scanner with a custom overlay and some UI components implemented in Xamarin.Forms in one View.
Is it possible at all?

I assumed that this is possible and implemented this:
1. Android.Support.V4.App.FragmentActivity with a custom overlay for ZXing scanner.
2. Android Activity with a custom overlay for ZXing scanner.
3. Android PageRenderer with a custom overlay for ZXing scanner.

I was able to run all these variants, but I was not able to mix them with Xamarin.Forms UI.

Example:
Here is my ZXingScannerRendererPage.xaml in the shared project (attached pic). I want to have "TEST BUTTON" button above Zxing Scanner view.

But when I run the application with PageRenderer I can see for a second my layout with "TEST BUTTON" and then view jumps to ZXing scanner.
When I "press back" button, I can see my XAML layout with "TEST BUTTON". I think ZXing opens a new activity or something.

So, what I need is:
1. Embed ZXing.Net.Mobile barcodes scanner with custom overlay into my Xamarin.Forms ContentPage along with other Xamarin.Forms UI.
or
2. Embed Xamarin.Forms UI above view with ZXing.Net.Mobile barcodes scanner with a custom overlay.

How to accomplish this? Is it possible to embed PageRenderer/Fragment/View into Xamarin.Forms XAML?

Thanks!

How can I show a notification? (popup) like facebook, whatsapp, spotify daoes it

$
0
0

At the same way spotify, facebook, whatsapp, instagram show you a notification (popup) when you recive a message, I need to show a message in my app even if this it is off. Any idea?

//xamarin97.rssing.com/chan-50656755/article68946-live.html

$
0
0

After saving the date that was input to a bound field, how do I set it back to displaying the Placeholder text again?
FName.Text="" or FName.Text=null dont work.

Design Cart

Messaging center is not working when object is not there in memory

$
0
0

This is how I am sending data from classA.
RequestClassA req= new RequestClassA
{
Id = Id
};
MessagingCenter.Send<string, RequestClassA >(nameof(classA), "FileClicked", req);
This is how I am receiving data in ClassB.
MessagingCenter.Unsubscribe<string, RequestClassA >(nameof(ClassB), "FileClicked");
MessagingCenter.Subscribe<string, RequestClassA >(nameof(ClassB), "FileClicked", (s, args) => {
Device.InvokeOnMainThreadAsync(async () =>
{
//Some Code Here
});
});


Value cannot be null. Parameter name: type

$
0
0

Not sure what changed, but now when I build I get this error on every XAML file in my project. Has anyone ran into this issue before? Tried all of the usual fixes - del bin/obj, restart, clean rebuild, downgrade Forms...

Background color of a Label within a ViewCell (when the item is selected)

$
0
0

Ok, this is one of those things that seemed very simple, but we have been unable to find a solution:

  • We have a ListView/ViewCell which contains a StackLayout and, within it, a label that shows a small tag and a background color with the status of the item.
  • When the item is selected, the background of the ViewCell changes (fine with that) but... the background of the label also changes (what?).

Is there any way to prevent Xamarin Forms from changing the background color of every element within the ViewCell? (when the item is selected)

As a bonus visual bug, the status of the item can be changed after the user selects the item. This causes the background color to become visible again, but, when the user deselects the item... it goes back to the "old" color that the line had before (Xamarin seems to be caching the previous background color and reapplying it, even though the value has changed).

As a bit of code is probably easier to understand, this is a simplified example of what we are doing:

<ListView ItemsSource="{Binding Lines}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout>
                    <Label Text="{Binding Description}" />
                    <Label Text="{Binding Status}" BackgroundColor="{Binding StatusColor}" />
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Any help/suggestions would be welcome!

Regards,
Salva.

Redirect to Specific Page When Firebase Notification tapped

$
0
0

Hello,

I have implemented android firebase remote notification based on the following walkthrough in my xamarin forms app.

https://docs.microsoft.com/en-us/xamarin/android/data-cloud/google-messaging/remote-notifications-with-fcm?tabs=windows

Now, I would like to redirect to a specific page when the user tapped on the notification badge. Currently, I can able to successfully redirect to a specific page when the app is opened and in an idle state by overriding OnNewIntent method. But when the app is closed it's not redirecting to a specific page when I am tapping on the notification.

FOLLOWING CODE I HAVE USED IN MY APP

MainActivity.cs

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
static readonly string TAG = "MainActivity";

    internal static readonly string CHANNEL_ID = "my_notification_channel";
    internal static readonly int NOTIFICATION_ID = 100;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        //LoadApplication(new App(true));


        string parameterValue = Intent.GetStringExtra("messageBody");
        LoadApplication(parameterValue != null ? new App(true) : new App(false));

        //if (Intent.Extras != null)
        //{
        //    foreach (var key in Intent.Extras.KeySet())
        //    {
        //        var value = Intent.Extras.GetString(key);
        //        //Log.Debug(TAG, "Key: {0} Value: {1}", key, value);
        //        LoadApplication(new App(true));
        //    }
        //}
        //else
        //{
        //    LoadApplication(new App(false));
        //}


        IsPlayServicesAvailable();
        CreateNotificationChannel();
    }

    public bool IsPlayServicesAvailable()
    {
        int resultCode = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.Success)
        {

            if (GoogleApiAvailability.Instance.IsUserResolvableError(resultCode))
            {
                //msgText.Text = GoogleApiAvailability.Instance.GetErrorString(resultCode);
            }
            else
            {
                // msgText.Text = "This device is not supported";
                Finish();
            }
            return false;
        }
        else
        {
            // do whatever if play service is not available
            //msgText.Text = "Google Play Services is available.";
            return true;
        }
    }

    void CreateNotificationChannel()
    {
        if (Build.VERSION.SdkInt < BuildVersionCodes.O)
        {
            return;
        }

        var channel = new NotificationChannel(CHANNEL_ID,
                                              "FCM Notifications",
                                              NotificationImportance.Default)
        {

            Description = "Firebase Cloud Messages appear in this channel"
        };

        var notificationManager = (NotificationManager)GetSystemService(Android.Content.Context.NotificationService);
        notificationManager.CreateNotificationChannel(channel);
    }

    protected override void OnNewIntent(Intent intent)
    {
        //var message = intent.GetStringExtra("message");
        base.OnNewIntent(intent);
        Intent = intent;
        Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync(new Views.AboutPage());

    }
}

MyFirebaseMessagingService.cs

[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
public MyFirebaseMessagingService()
{

    }
    public override void OnMessageReceived(RemoteMessage message)
    {
        //base.OnMessageReceived(message);
        //webContentList = message.Data["webContentList"];
        //new NotificationHelper().CreateNotification(message.GetNotification().Title, message.GetNotification().Body);
        var body = message.GetNotification().Body;
        SendNotification(body, message.Data);
    }

    void SendNotification(string messageBody, IDictionary<string, string> data)
    {
        var intent = new Intent(this, typeof(MainActivity));
        intent.AddFlags(ActivityFlags.ClearTop);
        foreach (var key in data.Keys)
        {
            intent.PutExtra(key, data[key]);
        }
        intent.PutExtra("messageBody", messageBody.ToString());

        var pendingIntent = PendingIntent.GetActivity(this,
                                                      MainActivity.NOTIFICATION_ID,
                                                      intent,
                                                      PendingIntentFlags.OneShot);

        var notificationBuilder = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
                                  .SetSmallIcon(Resource.Drawable.icon)
                                  .SetContentTitle("FCM Message")
                                  .SetContentText(messageBody)
                                  .SetAutoCancel(true)
                                  .SetContentIntent(pendingIntent);

        var notificationManager = NotificationManagerCompat.From(this);
        notificationManager.Notify(MainActivity.NOTIFICATION_ID, notificationBuilder.Build());
    }
}

App.xaml.cs

public App(bool hasNotification)
{
InitializeComponent();

//testing the feature
if (hasNotification)
{
MainPage = new NavigationPage(new HomePage());
}
else
{
MainPage = new MainPage();
}
}

Any help would be highly appreciated.

Thanks
Ranjan

Is there any plugin or guidance when user install the apps to show demo like click here to chat.

$
0
0

I've created an Xamarin app & now customer wants app to be user friendly like in some apps we install from play store or Appstore. At first time it shows some demo like arrows click here to chat click here to call etc. Is there such plugin or guidance Pls?

Firebase and restore Wifi

$
0
0

I fill Entry with data from Firebase , there is only 1 record in the database.

Found out when i start the mainpage the record is in label , but when i start with no wifi nothing is happening of course.

Oke , but when i start Wifi and go back to mainpage there is en error that it is waiting for a response from the database ( from the first time i start mainpage ).

Put it for now in Try and Catch but is there another way to get the record , maybe only 1 time when i start the app

`

try
{
await Task.Delay(2000);

            base.OnAppearing();


            var person = await firebaseHelper.GetPerson(Convert.ToInt32(txtId.Text));
            if (person != null)
            {
                txtId.Text = person.PersonId.ToString();
                txtName.Text = person.Name;



            }
            else
            {

            }
        }
        catch
        {
            // If there is an error
        }

`

CheckBox in ListView with MVVM, notify changes

$
0
0

I am using the MVVM model and have a listview which displays a series of checkboxes. My xaml is

<CheckBox Grid.Row="0" Grid.Column="1" Color="{Binding BreakfastStatusColour}" IsChecked="{Binding BreakfastClaimed, Mode=TwoWay}" HorizontalOptions="Center" CheckedChanged="CheckBox_CheckedChanged"  />

My issue is that when the user checks or unchecks the check box I need the colour to potentially change. My listview has an observablecollection as it's data source and as expected this is being updated as the user checks a box. However I'm not sure how I can inform the UI that the colour also needs to be updated. Obviously if this was a locally bound field I could use 'NotifyPropertyChanged' but the field being updated is in a collection...

I did try capturing the CheckedChanged event but I have the same issue of how to notify to get the colour change to be recognised?

WebView Renderer with WebViewClient

$
0
0

Hello Everyone,
I am using Web View in my Xamarin PCL application which is working fine. However currently some HTTPS pages stop loading only on Android (iOS working fine). So after some google, I have come up to have custom renderer with custom WebViewClient which handle SSL Error. Now url start loading in Android also perfectly but unfortunately WebView in PCL forms stop firing its Navigating & Navigated events. Also GoBack() stop working on WebView.
Here is my control definition in PCL project
public class CustomWebView : WebView { }

And Here is its Custom Renderer
`public class CustomWebViewRenderer : WebViewRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);

            // Setting the background as transparent
            this.Control.SetBackgroundColor(Android.Graphics.Color.Transparent);
            if (e.OldElement == null)
            {
                Control.SetWebViewClient(new FormsWebViewClient()); 
            }
        }
    }
internal class FormsWebViewClient : Android.Webkit.WebViewClient
    {
        public override void OnReceivedSslError(Android.Webkit.WebView view, SslErrorHandler handler, SslError error)
        {           
            handler.Proceed();
        }
}`

Now if user navigate multiple pages in WebView and then press Backbutton it goes out of WebView (instead going to previous URL page). Previously I was handling back button in PCL Form like this
`public bool CanGoBack()
{
if (webView.CanGoBack)
{
webView.GoBack();
return true;
}
return false;
}

                            protected override bool OnBackButtonPressed()
                            {
                                if(!CanGoBack())
                                    return base.OnBackButtonPressed();
                                return true;
                            }`

But now "CanGoBack" is always false. Also WebView stop firing Navigating & Navigated event in PCL form as I have to do some business checks and also show animation so I had captured these events and it was working fine before renderer.

PCL form XAML look like this:
<web:CustomWebView x:Name="webView" Grid.Row="1" />

And its CodeBehind look like:
`webView.Navigated += (s, e) =>
{
busyIndicator.IsVisible = false;
};
webView.Navigating += (s, e) =>
{
//Some business logic here which is very important
busyIndicator.IsVisible = true;
}

webView.Source = startUrl;`

Please need someone expert opinion. Thank you in advance


Linker Issue with Prism.Forms

$
0
0

I have been trying for a while now to achieve linking in mainly my Xamarin.Forms Android project.
I'm using Prism in my project and when i set the Linker to SDK and User assemblies I seem to receive exceptions surround the Prism framework.
After a certain point of debugging my output spits back not info on what caused the app to crash meaning I cannot narrow down what assembly is causing the issue.
Has anyone had any success with linking and Prism

Getting Mono.AndroidTools.RequiresUninstallException on Android

$
0
0

Today I started getting this deployment error on android:

Severity Code Description Project File Line Suppression State
Error ADB0030: Mono.AndroidTools.RequiresUninstallException: The installed package is incompatible. Please manually uninstall and try again.
at Mono.AndroidTools.Internal.AdbOutputParsing.CheckInstallSuccess(String output, String packageName) in E:\A_work\267\s\External\androidtools\Mono.AndroidTools\Internal\AdbOutputParsing.cs:line 339
at Mono.AndroidTools.AndroidDevice.<>c__DisplayClass95_0.b__0(Task1 t) in E:\A\_work\267\s\External\androidtools\Mono.AndroidTools\AndroidDevice.cs:line 753 at System.Threading.Tasks.ContinuationTaskFromResultTask1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at AndroidDeviceExtensions.d__11.MoveNext() in E:\A_work\267\s\External\androidtools\Xamarin.AndroidTools\Devices\AndroidDeviceExtensions.cs:line 187
--- End of stack trace from previous location where exception was thrown ---
at AndroidDeviceExtensions.d__11.MoveNext() in E:\A_work\267\s\External\androidtools\Xamarin.AndroidTools\Devices\AndroidDeviceExtensions.cs:line 194
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at AndroidDeviceExtensions.d__11.MoveNext() in E:\A_work\267\s\External\androidtools\Xamarin.AndroidTools\Devices\AndroidDeviceExtensions.cs:line 203
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Xamarin.AndroidTools.AndroidDeploySession.d__112.MoveNext() in E:\A_work\267\s\External\androidtools\Xamarin.AndroidTools\Sessions\AndroidDeploySession.cs:line 414
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Xamarin.AndroidTools.AndroidDeploySession.d__106.MoveNext() in E:\A_work\267\s\External\androidtools\Xamarin.AndroidTools\Sessions\AndroidDeploySession.cs:line 217
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Xamarin.AndroidTools.AndroidDeploySession.d__104.MoveNext() in E:\A_work\267\s\External\androidtools\Xamarin.AndroidTools\Sessions\AndroidDeploySession.cs:line 119 0

It only happens in Debug, but in Release i can deploy and run the app just fine.
Why is this happening?

This morning i installed the Android SDK 10.0 and I suspect it started after that, so now I uninstalled it, but I still can't deploy because of the same error.
Other apps from the same PC can be deployed just fine, so I don't get it...

I did check this out
https://docs.microsoft.com/en-us/xamarin/android/errors-and-warnings/adb0030

but I don't even have my app installed on the device...

Thanks

add properties Button

$
0
0

Can this be done?

Key1 Key2 Key3

CarouselPage not appearing when swiped...

$
0
0

I have a CarouselPage (I know its deprecated, next step is to replace.) in which the first two pages appear but remaining pages are blank. In the emulator, if I click on "Overview" and return back to the app then the pages appear. I'm using the latest version of Forms, 4.3. I've attached the XAML. We are adding on page at run time. I've uploaded pictures of what the experience looks like. Any help would be appreciated. I'm happy to provide additional code as required.

Push Notification not working after Xamarin.Forms upgrade

$
0
0

My app was upgraded from Xamarin.Forms 3.1 to 4.1. Before upgrade, my push notification was working perfectlty, receiving notifications when in foreground, background or closed.

After the upgrade, my app is only receiving notifications when it is in foreground or background. If my remove my app from "apps recent list" or simply do not open it after cellphone reboot, i do not receive any notification.

I am sending my notifications using firebase portal and postman. Below, is my json format:

{
   "data": {
      "title": "Título da Mensagem - data 1",
      "body": "Essa é uma mensagem longa, com muito conteúdo que precisa ser visualizado por inteiro na notificação do aplicativo !!!",
      "sound": "true"
   },
   "notification": {
      "title": "Título da Mensagem - notification 1",
      "body": "Essa é uma mensagem longa, com muito conteúdo que precisa ser visualizado por inteiro na notificação do aplicativo !!!",
      "content_available": "true"
   },
   "priority": "high",
   "to": "cezjmhzWaKM:APA91bGkEUQ......."
}

Every notification sent by postman, receives the confirmation, like the example below:

{
    "multicast_id": 2772544695401950510,
    "success": 1,
    "failure": 0,
    "canonical_ids": 0,
    "results": [
        {
            "message_id": "0:1574816910300590%6671412c6671412c"
        }
    ]
}

I do not receive any error, when my app is closed. So, I think the notification is received by my app, but it is not processed.

I am using FCM (Firebase Cloud Messaging).

Below, is my AndroidManifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="215" android:versionName="2.0.9" package="com.algorix.myapp" android:installLocation="auto">
  <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
  <uses-feature android:glEsVersion="0x00020000" android:required="true" />
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  <uses-permission android:name="myapp.permission.MAPS_RECEIVE" android:protectionLevel="signature" />
  <uses-permission android:name="myapp.permission.C2D_MESSAGE" android:protectionLevel="signature" />
  <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
  <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
  <uses-permission android:name="android.permission.WAKE_LOCK" />
  <uses-permission android:name="android.permission.VIBRATE" />
  <application android:label="@string/app_name" android:icon="@mipmap/icon">
    <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/ic_stat_logo_notification" />
    <meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/accent_color" />
    <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
    <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
      <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
        <category android:name="${applicationId}" />
      </intent-filter>
    </receiver>
    <uses-library android:name="org.apache.http.legacy" android:required="false" />
    <meta-data android:name="com.google.android.geo.API_KEY" android:value="AIza......." />
  </application>
</manifest>

I have also tried add the flag "FLAG_INCLUDE_STOPPED_PACKAGES", but without any change. Below, is my class which intercepts the notifications:

    [Service]
    [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
    [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
    public class MyFirebaseMessagingService : FirebaseMessagingService
    {
    ///
        public override void OnMessageReceived(RemoteMessage message)
        {
            if (message.Data.Count > 0)
            {
                Log.Debug("Data - ", "Message data: " + message.Data.ToString());
                SendNotification(message.Data);
            }
            else
            {
                if (message.GetNotification() != null)
                {
                    Log.Debug("Notification - ", "Message notification: " + message.Data.ToString());
                    SendNotification(message.GetNotification());
                }
            }
        }

    ///
        public void SendNotification(IDictionary<string, string> data)
        {
            try
            {
                var intent = new Intent(this, typeof(MainActivity));
                intent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.IncludeStoppedPackages);

                foreach (string key in data.Keys)
                {
                    intent.PutExtra(key, data[key]);
                }

                var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

                messageTitle = intent.GetStringExtra("title");
                messageBody = intent.GetStringExtra("body");
                messageSoundEnabled = intent.GetStringExtra("sound");

                SetNewAlert(messageTitle, messageBody);
                MountAlert(messageTitle, messageBody, pendingIntent);
            }
            catch (Exception ex)
            {
                _services.SendError(ex.GetType().Name, ex.Message, "Android Project", "SendNotification", _version.GetVersion());
            }
        }

    ///
        public void SendNotification(RemoteMessage.Notification notification)
        {
            try
            {
                var intent = new Intent(this, typeof(MainActivity));
                intent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.IncludeStoppedPackages);
                var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);

                messageTitle = notification.Title;
                messageBody = notification.Body;

                SetNewAlert(messageTitle, messageBody);
                MountAlert(messageTitle, messageBody, pendingIntent);
            }
            catch (Exception ex)
            {
                _services.SendError(ex.GetType().Name, ex.Message, "Android Project", "SendNotification", _version.GetVersion());
            }
        }

    ///
        private void MountAlert(string title, string message, PendingIntent intent)
        {
            try
            {
                string channelIdAndroid = Android.App.Application.Context.Resources.GetString(Resource.String.appnotificationchannel);
                string channelNameAndroid = "Android Channel";

                Notification.Builder notification = null;

                if (Android.OS.Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.Lollipop)
                {
                    notification = new Notification.Builder(this, channelIdAndroid)
                                    .SetSmallIcon(Resource.Drawable.ic_stat_logo_notification)
                                    .SetContentTitle(title)
                                    .SetContentText(message)
                                    .SetAutoCancel(true)
                                    .SetStyle(new Notification.BigTextStyle().BigText(message))
                                    .SetContentIntent(intent);

                    notificationManager = NotificationManager.FromContext(this);
                }
                else
                {
                    if ((Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop) &&
                        (Android.OS.Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.O))
                    {
                        notification = new Notification.Builder(this, channelIdAndroid)
                                        .SetSmallIcon(Resource.Drawable.ic_stat_logo_notification)
                                        .SetLargeIcon(BitmapFactory.DecodeResource(Android.App.Application.Context.Resources, Resource.Mipmap.icon))
                                        .SetColor(Resource.Color.accent_color)
                                        .SetContentTitle(title)
                                        .SetContentText(message)
                                        .SetAutoCancel(true)
                                        .SetStyle(new Notification.BigTextStyle().BigText(message))
                                        .SetContentIntent(intent);

                        notificationManager = NotificationManager.FromContext(this);
                    }
                    else
                    {
                        if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
                        {
                            NotificationChannel androidChannel = new NotificationChannel(channelIdAndroid, channelNameAndroid, NotificationImportance.Default);
                            androidChannel.EnableVibration(true);
                            androidChannel.SetSound(null, null);
                            androidChannel.ShouldShowLights();
                            androidChannel.EnableLights(true);
                            androidChannel.SetShowBadge(true);
                            androidChannel.LightColor = Resource.Color.accent_color;
                            androidChannel.LockscreenVisibility = NotificationVisibility.Public;

                            notificationManager = (NotificationManager)GetSystemService(Android.Content.Context.NotificationService);

                            notificationManager.CreateNotificationChannel(androidChannel);

                            notification = new Notification.Builder(this, channelIdAndroid)
                                            .SetSmallIcon(Resource.Drawable.ic_stat_logo_notification)
                                            .SetLargeIcon(BitmapFactory.DecodeResource(Android.App.Application.Context.Resources, Resource.Mipmap.icon))
                                            .SetColor(Resource.Color.accent_color)
                                            .SetContentTitle(title)
                                            .SetContentText(message)
                                            .SetAutoCancel(true)
                                            .SetStyle(new Notification.BigTextStyle().BigText(message))
                                            .SetContentIntent(intent);

                        }
                    }
                }

                if (notificationManager != null && notification != null)
                {
                    notificationManager.Notify(RandomGenerator(), notification.Build());

                    if (messageSoundEnabled != null && messageSoundEnabled.Length > 0)
                    {
                        bool soundEnabled;
                        bool.TryParse(messageSoundEnabled, out soundEnabled);

                        if (soundEnabled)
                        {
                            var player = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;
                            player.Load("notification.mp3");
                            player.Play();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _services.SendError(ex.GetType().Name, ex.Message, "Android Project", "MountAlert", _version.GetVersion());
            }
        }

And my last try, was to upgrade Xamarin.Forms to 4.3, but also nothing happenned.

Please, any clue to solve this problem ???

Viewing all 77050 articles
Browse latest View live


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