Когда вы храните целое число в памяти, компьютер сохраняет его в виде серии байтов. Они могут быть представлены как серия единиц и нулей.
Например, нуль будет представлен как 00000000
(8-битные целые числа), и часто 127 будут представлены как 01111111
. Если вы добавите один из 127, это «перевернит» биты и заменит его на 10000000
, но в представлении комплимента в стандарте , это фактически используется для представления -128. Это «переполняет» значение.
С неподписанными номерами происходит то же самое: 255 (11111111
) плюс 1 станет 100000000
, но так как есть только 8 "бит", это заканчивается как 00000000
, который равен 0.
Вы можете избежать этого, выполнив правильную проверку диапазона для вашего правильного целочисленного размера или используя язык, который делает правильную обработку исключений для вас.
Пожалуйста, обратитесь к приведенному ниже образцу. Вы можете использовать диспетчер тревог для перезапуска службы.
Пожалуйста, следуйте инструкциям.
Шаг 1: Создание BroadcastReceiver
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;
namespace AlarmManagerApp
{
[BroadcastReceiver(Enabled = true)]
[IntentFilter(new[] { Android.Content.Intent.ActionBootCompleted })]
class AlarmReceiver : BroadcastReceiver
{
Context context;
public override void OnReceive(Context context, Intent intent)
{
this.context = context;
Toast.MakeText(context,"Recieved",ToastLength.Long).Show();
Intent background = new Intent(context, typeof(BackgroundService));
context.StartService(background);
}
}
}
Шаг 2: Добавьте AlarmManager в MainActivity, где вы хотите вызвать службу
namespace AlarmManagerApp
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
String alarm = Context.AlarmService;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
var alarmIntent = new Intent(this, typeof(AlarmReceiver));
alarmIntent.PutExtra("title", "Hello");
alarmIntent.PutExtra("message", "World!");
var pending = PendingIntent.GetBroadcast(this, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
var alarmManager = GetSystemService(AlarmService).JavaCast<AlarmManager>();
alarmManager.SetRepeating(AlarmType.ElapsedRealtime,DateTime.Now.Millisecond, 5 * 100, pending);
}
}
Шаг 3: Добавить службу
namespace AlarmManagerApp
{
[Service]
public class BackgroundService : Service
{
public override void OnCreate()
{
base.OnCreate();
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
Log.Debug("service","Service Started");
//init the handler in oncreate
System.Timers.Timer Timer1 = new System.Timers.Timer();
Timer1.Start();
Timer1.Interval = 3000;
int a = 0;
Timer1.Enabled = true;
//Timer1.Elapsed += OnTimedEvent;
Timer1.Elapsed += (object sender, System.Timers.ElapsedEventArgs e) =>
{
Timer1.Stop();
Timer1.Start();
a++;
//Delete time since it will no longer be used.
Timer1.Dispose();
};
Timer1.Start();
return StartCommandResult.Sticky;
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public override void OnTaskRemoved(Intent rootIntent)
{
Intent restartServiceIntent = new Intent(this, this.Class);
restartServiceIntent.SetPackage(this.PackageName);
Log.Debug("service", "Service Restarted");
PendingIntent restartServicePendingIntent = PendingIntent.GetService(this, 1, restartServiceIntent, PendingIntentFlags.OneShot);
AlarmManager alarmService = (AlarmManager)this.GetSystemService(Context.AlarmService);
alarmService.SetRepeating(AlarmType.RtcWakeup, SystemClock.CurrentThreadTimeMillis(), 30 * 1000, restartServicePendingIntent);
NotificationManager notificationManager =
(NotificationManager)GetSystemService(NotificationService);
Notification.Builder builder = new Notification.Builder(this);
Intent notificationIntent = new Intent(this, typeof(MainActivity));
PendingIntent contentIntent = PendingIntent.GetActivity(this, 0, notificationIntent, 0);
//set
builder.SetContentIntent(contentIntent);
builder.SetSmallIcon(Resource.Mipmap.ic_launcher);
builder.SetContentText("Contents");
builder.SetContentTitle("title");
builder.SetAutoCancel(true);
builder.SetDefaults(NotificationDefaults.All);
notificationManager.Notify(1, builder.Build());
base.OnTaskRemoved(rootIntent);
}
}
}
Это также работает, если приложение закрыто и устройство перезапущено.