Xamarin Foreground Services

Buat Interface “IDemoService” di Xamarin.

using System;
using System.Collections.Generic;
using System.Text;

namespace ForegroundXamarin
{
    public interface IDemoServices
    {
        void Start();
        void Stop();
    }
}

Buat Class “DemoService” di bagian Xamarin.Droid:

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
using AndroidApp = Android.App.Application;

[assembly:Xamarin.Forms.Dependency(typeof(ForegroundXamarin.Droid.DemoServices))]
namespace ForegroundXamarin.Droid
{
    [Service(ForegroundServiceType = Android.Content.PM.ForegroundService.TypeDataSync)]
    public class DemoServices : Service, IDemoServices
    {
        public override IBinder OnBind(Intent intent)
        {
            throw new NotImplementedException();
        }

        [return: GeneratedEnum]
        public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
        {
            if(intent.Action == "START_SERVICE")
            {
                RegisterNotification();

                DoSomething();
            }
            else if (intent.Action == "STOP_SERVICE")
            {
                StopForeground(true);
                StopSelfResult(startId);
            }
            return StartCommandResult.NotSticky;
        }

        int i = 1;
        void DoSomething()
        {
            Device.StartTimer(TimeSpan.FromSeconds(10), () =>
            {
               NotificationManager manager = (NotificationManager)MainActivity.ActivityCurrent.
               GetSystemService(Context.NotificationService);

               // if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
               // {
               //     var channelNameJava = new Java.Lang.String("Default");
               //     var channel = new NotificationChannel("default", channelNameJava, NotificationImportance.Default)
               //     {
               //         Description = "Channel Description..."
               //     };
               //     manager.CreateNotificationChannel(channel);
               // }
                Notification notification = new Notification.Builder(this, "ServiceChannel")
                    .SetContentTitle("My Foreground Service : " + i.ToString())
                    .SetSmallIcon(Resource.Drawable.abc_ic_star_black_16dp)
                    .SetOngoing(true)
                    .Build();

                manager.Notify(100, notification);

                i += 1;

                return true;
            });
            
           
        }

        private void RegisterNotification()
        {
            //NotificationChannel channel = new NotificationChannel("ServiceChannel", "Demo Foreground Service",
            //    NotificationImportance.Max);
            //NotificationManager manager = (NotificationManager)MainActivity.ActivityCurrent.
            //    GetSystemService(Context.NotificationService);
            //manager.CreateNotificationChannel(channel);
            //Notification notification = new Notification.Builder(this, "ServiceChannel")
            //    .SetContentTitle("My Foreground Service")
            //    .SetSmallIcon(Resource.Drawable.abc_ic_star_black_16dp)
            //    .SetOngoing(true)
            //    .Build();

            NotificationManager manager = (NotificationManager)MainActivity.ActivityCurrent.
                GetSystemService(Context.NotificationService);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
            {
                var channelNameJava = new Java.Lang.String("Default");
                var channel = new NotificationChannel("default", channelNameJava, NotificationImportance.Default)
                {
                    Description = "Channel Description..."
                };
                manager.CreateNotificationChannel(channel);
            }
            Notification notification = new Notification.Builder(this, "ServiceChannel")
                .SetContentTitle("My Foreground Service")
                .SetSmallIcon(Resource.Drawable.abc_ic_star_black_16dp)
                .SetOngoing(true)
                .Build();
            

            StartForeground(100, notification);
        }




        public void Start()
        {
            Intent startService = new Intent(MainActivity.ActivityCurrent, typeof(DemoServices));
            startService.SetAction("START_SERVICE");
            MainActivity.ActivityCurrent.StartService(startService);
        }

        public void Stop()
        {
            Intent stopIntent = new Intent(MainActivity.ActivityCurrent, this.Class);
            stopIntent.SetAction("STOP_SERVICE");
            MainActivity.ActivityCurrent.StartService(stopIntent);
        }
    }
}

Di bagian Xamarin.Droid MainActivity.cs tambah beberapa kode berikut:

public static Activity ActivityCurrent { get; private set; }
protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            ActivityCurrent = this;

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }

Mengganti warna Text dan Background Toolbar Xamarin forms

Contoh Toolbar:

<ContentPage.ToolbarItems>
    <ToolbarItem Order="Secondary" Icon="morevert.png" Text="Atualizar" Command="{Binding Atualizar}"/>
    <ToolbarItem Order="Secondary" Text="Ajuda" Command="{Binding Ajuda}"/>
    <ToolbarItem Order="Secondary" Text="Sair" Command="{Binding Sair}"/>
</ContentPage.ToolbarItems>

Caranya:

  1. Resources/Values/Style.xml
 <style name="AppToolbarTheme" parent="Theme.AppCompat.NoActionBar">
      <item name="android:colorBackground">#2196F3</item>
      <item name="android:textColor">#000080</item>
    </style>

2.  Resources>Layout folder, update Toolbar.xml

Tambahkan

xmlns:app=”http://schemas.android.com/apk/res-auto&#8221; dan

app:popupTheme=”@style/AppToolbarTheme”

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/AppToolbarTheme" />

Hide Label TabbedPage Xamarin Forms

Buat class NoShiftingEffect.cs di Android

using Android.Support.Design.BottomNavigation;
using Android.Support.Design.Widget;
using Android.Views;
using App16.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly:ResolutionGroupName ("MyCompany")]
[assembly:ExportEffect (typeof(NoShiftEffect), "NoShiftEffect")]
namespace App16.Droid
{
    public class NoShiftEffect : PlatformEffect
    {
        protected override void OnAttached ()
        {
            if (!(Container.GetChildAt(0) is ViewGroup layout))
                return;

            if (!(layout.GetChildAt(1) is BottomNavigationView bottomNavigationView))
                return;

            // This is what we set to adjust if the shifting happens
            bottomNavigationView.LabelVisibilityMode = LabelVisibilityMode.LabelVisibilityLabeled;
        }

        protected override void OnDetached ()
        {
        }
    }
}

Buat Class di namespace Utama NoShiftingEffect.cs

using Xamarin.Forms;

namespace App16
{
    public class NoShiftEffect : RoutingEffect
    {
        public NoShiftEffect() : base("MyCompany.NoShiftEffect")
        {
        }
    }
}

Cara menggunakan Effect:

<TabbedPage.Effects>
    <local:NoShiftEffect />
</TabbedPage.Effects>

Mengganti Effect2 lain:

Here is what the other modes do:

  • LabelVisibilityAuto: Label behaves as “labeled” when there are 3 items or less, or “selected” when there are 4 items or more.
  • LabelVisibilityLabeled: Label is shown on all navigation items.
  • LabelVisibilitySelected: Label is shown on the selected navigation item.
  • LabelVisibilityUnlabled: Label is not shown on any navigation items.