Mouhannad Bar
Mouhannad Bar

Reputation: 101

Starting android activity on boot in Background

I want to start the app after boot completing in Background. I don't want to show the UI.

This is my code, it starts the app as if I clicked its icon, but I need to hide it!

[BroadcastReceiver]
[IntentFilter(new[] { Android.Content.Intent.ActionBootCompleted },
    Categories = new[] { Android.Content.Intent.CategoryDefault }
)]
public class ReceiveBoot: BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {

        if ((intent.Action != null) &&
            (intent.Action ==
                Android.Content.Intent.ActionBootCompleted))
        { 

            Android.Content.Intent start = new Android.Content.Intent(context, typeof(Main_Activity));
            start.AddFlags(ActivityFlags.NewTask);
            start.AddFlags(ActivityFlags.FromBackground);
            context.ApplicationContext.StartActivity(start);

        }
    }
}

Upvotes: 2

Views: 2830

Answers (1)

William Barbosa
William Barbosa

Reputation: 5005

If you need an Activity with no UI, you probably want a service.

Move the logic you need to execute at boot from your Activity to a Service (more info on it here).

Then, in order to start it, just change your intent a to use typeof(MyServiceClass), set whichever flag you may need and call StartService instead of StartActivity

Upvotes: 3

Related Questions