takachaa / .net-Framework

0 stars 0 forks source link

【Xamarin】バックグランド処理 #17

Open takachaa opened 7 years ago

takachaa commented 7 years ago

Main.axml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="25px"
    android:minHeight="25px">
    <Button
        android:text="Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/MyButton" />
</LinearLayout>

MainActtivity.cs

using Android.App;
using Android.Widget;
using Android.OS;
using Android.Content;

namespace App2
{
    [Activity(Label = "App2", MainLauncher = true)]
    public class MainActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.MyButton);

            button.Click += (_, __) =>
            {
                var ServiceIntent = new Intent(this, typeof(MyService));
                StartService(ServiceIntent);
            };
        }
    }
}

MyService.cs

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

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Util;

namespace App2
{
    [Service]
    class MyService : Service
    {
        public override IBinder OnBind(Intent intent)
        {
            throw new NotImplementedException();
        }

        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            for (int i = 0; i < 100; i++)
            {
                Log.Debug("MyService", "OnDestroy");//ログ
                System.Threading.Thread.Sleep(1000);
                var n = new Notification.Builder(this)
                        .SetContentTitle("Hello notification")
                        .SetSmallIcon(Resource.Drawable.Icon)
                        .Build();

                var nm = (NotificationManager)this.GetSystemService(Context.NotificationService);
                nm.Notify(i, n);
            }

            return StartCommandResult.Sticky;
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
            Log.Debug("MyService", "OnDestroy");//ログ

        }
    }
}

参考 https://techbooster.org/android/application/3270/