I am trying to get my xamarin.android foreground service to run after boot completion on my Android 9 (Techno Spark 4 Air) Mobile Phone. It is working very well on the android emulator.
This is what I have done.
My BroadcastReceiver:
[BroadcastReceiver(Name = "com.companyname.IMEI247Tracker.MyBroadcastReceiver", Enabled = true, Exported = true)]
public class MyBroadcastReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
//System.String intent_value = intent.GetStringExtra("key");
Toast.MakeText(context, "Received intent in MyBroadCastReceiver!", ToastLength.Short).Show();
var intent2 = new Intent(Android.App.Application.Context, typeof(StartServiceAndroid));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
{
Android.App.Application.Context.StartForegroundService(intent2);
}
else
{
Android.App.Application.Context.StartService(intent2);
}
}
}
My Receiver defined inside the Application Tag in Android Manifest XML file:
<receiver android:name="com.companyname.IMEI247Tracker.MyBroadcastReceiver" android:enabled="true" android:exported="true" android:directBootAware="true" android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
<action android:name="MY_SPECIFIC_ACTION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
My OnResume in MainActivity (this enables MyBroadcastReceiver to kick-start StartAndroidService when my app is running but when the app is killed, the service stops):
protected override void OnResume()
{
base.OnResume();
if (HelloApplication.GlobalKounter != 1)
{
if (!IsMyServiceRunning(typeof(StartServiceAndroid)))
{
RegisterReceiver(receiver, new IntentFilter("MY_SPECIFIC_ACTION"));
Intent message = new Intent("MY_SPECIFIC_ACTION");
SendBroadcast(message);
}
}
}
Now, the challenge is this: Whenever I re-start the Techno Spark 9 Mobile Phone, MyBroadcastReceiver is not being triggered to start my foreground service. But, on the Android emulator, everything is working smoothly when I am running the app and when I re-boot the emulator.
I am targeting Android 13 and running Visual Studio 2022.
So, what is really going on and how do I get around this?