Я делаю небольшое приложение для своей племянницы, используя Xamarin Android в VS 2017. Я хочу, чтобы оно открывало страницу в приложении, где каждый раз, когда она открывает телефон, она задает простой вопрос умножения.Я хочу, чтобы он работал в качестве службы переднего плана, поэтому он все еще делает это, когда приложение свернуто.У меня есть широковещательный приемник, который обнаружил событие кнопки, когда приложение было в фокусе, и я переместил его в службу для запуска.
В настоящее время я нажимаю кнопку переключения, а затем через 5-10 секунд выдает ошибку.Не могу увидеть ошибку в VS, потому что она внешняя.Я предполагаю, что это эмулятор Genymotion, который поймал это тогда?
Есть идеи?
ОБНОВЛЕНИЕ: Я думал, что приду и обновлю это, если это будет кому-то еще пригодиться в будущем.После обновления Oreo NotificationCompat.Builder теперь требуется указание идентификатора канала.Я отразил это в коде, и теперь он правильно запускает службу.
Мне все еще нужно, чтобы приемник вещания работал из службы, но я получаю это!
ОБНОВЛЕНИЕ 2:Работа выполнена!
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
Intent startServiceIntent;
Intent stopServiceIntent;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
// Difficulty Radio Buttons
RadioButton radioEasy = FindViewById<RadioButton>(Resource.Id.radioEasy);
radioEasy.Click += RadioButton_Click;
RadioButton radioMedium = FindViewById<RadioButton>(Resource.Id.radioMedium);
radioMedium.Click += RadioButton_Click;
RadioButton radioHard = FindViewById<RadioButton>(Resource.Id.radioHard);
radioHard.Click += RadioButton_Click;
// Set/Remove Lock
Button ToggleLock = FindViewById<Button>(Resource.Id.ToggleLock);
ToggleLock.Click += ToggleLock_Click;
startServiceIntent = new Intent(this, typeof(LockService));
stopServiceIntent = new Intent(this, typeof(LockService));
}
private void RadioButton_Click(object sender, EventArgs e)
{
var radiobtn = sender as RadioButton;
Toast.MakeText(this, radiobtn.Text, ToastLength.Long).Show();
}
private void ToggleLock_Click(object sender, EventArgs e)
{
var togglebtn = sender as ToggleButton;
if (togglebtn.Checked)
{
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
StartForegroundService(startServiceIntent);
else
StartService(startServiceIntent);
Toast.MakeText(this, "On", ToastLength.Long).Show();
}
else
{
Toast.MakeText(this, "Off", ToastLength.Long).Show();
}
}
}
/// <summary>
/// ////////////////////////////////////////////////////////////////////////////
/// </summary>
[Service]
public class LockService : Service
{
private PowerBroadcastReceiver receiver;
public override void OnCreate()
{
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
NotificationManager mngr = (NotificationManager)GetSystemService(NotificationService);
NotificationChannel chnl = new NotificationChannel("Channel", "Name", NotificationImportance.Default);
mngr.CreateNotificationChannel(chnl);
NotificationCompat.Builder foregroundNotification = new NotificationCompat.Builder(this);
foregroundNotification.SetOngoing(true);
foregroundNotification.SetContentTitle("My Foreground Notification")
.SetChannelId("Channel")
.SetContentText("This is the first foreground notification Peace");
StartForeground(101, foregroundNotification.Notification);
// Broadcast Receiver
receiver = new PowerBroadcastReceiver();
RegisterReceiver(receiver, new IntentFilter(Intent.ActionScreenOn));
return StartCommandResult.Sticky;
}
public override IBinder OnBind(Intent intent)
{
// Return null because this is a pure started service. A hybrid service would return a binder that would
// allow access to the GetFormattedStamp() method.
return null;
}
}
/// <summary>
/// ////////////////////////////////////////////////////////////////////////////////
/// </summary>
[BroadcastReceiver]
[IntentFilter(new[] { Intent.ActionScreenOn, Intent.ActionScreenOff })]
public class PowerBroadcastReceiver : BroadcastReceiver
{
public PowerBroadcastReceiver()
{
}
public override void OnReceive(Context context, Intent intent)
{
if (intent.Action.Equals(Intent.ActionScreenOn))
{
// TODO: Launch Question Page
Toast.MakeText(context, "On", ToastLength.Long).Show();
}
else if (intent.Action.Equals(Intent.ActionScreenOff))
Toast.MakeText(context, "Off", ToastLength.Long).Show();
}
}
Спасибо.