Reputation: 803
I want to open a specific Page from completely closed Xamarin Forms application on android service OnReceive
I set an alarm to launch the application at specific time
[BroadcastReceiver(Enabled = true, Exported = false)]
public class Alarm : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager)context.GetSystemService(Context.PowerService);
PowerManager.WakeLock wl = pm.NewWakeLock(WakeLockFlags.Partial, "");
wl.Acquire();
Vibrator v = (Vibrator)context.GetSystemService(Context.VibratorService);
v.Vibrate(1000);
Intent i = new Intent(context, typeof(myForm));
i.AddFlags(ActivityFlags.NewTask);
context.StartActivity(i);
}
public void SetAlarm(Context context, DateTime time, string uniqName)
{
AlarmManager am = (AlarmManager)context.GetSystemService(Context.AlarmService);
Intent i = new Intent(context, typeof(Alarm));
i.SetAction(uniqName);
PendingIntent pi = PendingIntent.GetBroadcast(context, 0, i, 0);
//var totalMilliseconds = (long)(time - DateTime.Now).TotalMilliseconds;
DateTime st = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
TimeSpan t = (time.ToUniversalTime() - st);
var totalMilliseconds = (Int64)(t.TotalMilliseconds + 0.5);
am.Set(AlarmType.RtcWakeup, totalMilliseconds, pi);
}
}
When I try this code i got this error
Unhandled Exception:
System.ArgumentException: type
Parameter name: Type is not derived from a java type.
Upvotes: 1
Views: 771
Reputation: 2718
Xamarin.Forms run on a single activity, so if you handle the OnReceive on a different class, make sure to switch to the MainActivity from where you can use the normal navigation.
Should be something like this:
public override void OnReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager)context.GetSystemService(Context.PowerService);
PowerManager.WakeLock wl = pm.NewWakeLock(WakeLockFlags.Partial, "");
wl.Acquire();
Vibrator v = (Vibrator)context.GetSystemService(Context.VibratorService);
v.Vibrate(1000);
Intent i = new Intent(context, typeof(MainActivity));
i.AddFlags(ActivityFlags.NewTask);
i.PutExtra("alarmIntent",Intent.Data);
context.StartActivity(i);
this.FinishActivity(0);
}
and then in your MainActivity:
protected override void OnNewIntent(Intent intent)
{
base.OnNewIntent(intent);
Intent = intent;
}
protected override void OnPostResume()
{
base.OnPostResume();
if (Intent.Extras != null)
{
string fileName = Intent.Extras.GetString("alarmIntent");
if (!string.IsNullOrEmpty(fileName))
{
Xamarin.Forms.Application.Current.MainPage.Navigation.PushAsync (new myForm());
}
Intent.RemoveExtra("alarmIntent");
}
}
Check out this post
Upvotes: 1