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");//ログ
}
}
}
Main.axml
MainActtivity.cs
MyService.cs
参考 https://techbooster.org/android/application/3270/