我使用 Dot Net Maui 和 .Net Core 8 开发了小型 Andriod TV 应用程序 我希望这个应用程序在设备启动完成后运行,我尝试了以下代码作为 BroadcastReceiver 类,但这不起作用
using Android;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Net;
using Android.OS;
using Android.Runtime;
using Android.Views;
using static Android.Provider.ContactsContract.CommonDataKinds;
using static Java.Util.Jar.Attributes;
[assembly: UsesPermission(Manifest.Permission.ReceiveBootCompleted)]
namespace MMusicPlayer.Platforms.Android
{
[BroadcastReceiver(Enabled = true)]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class StartReceiver : BroadcastReceiver
{
public override void OnReceive(Context? context, Intent? intent)
{
}
}
}
确保权限正确: 您的许可声明看起来是正确的。在清单中拥有 RECEIVE_BOOT_COMPLETED 权限允许您的应用程序侦听启动完成事件。
实现应用程序启动逻辑:在 BroadcastReceiver 的 OnReceive 方法中,您需要启动应用程序的主要 Activity。假设您的主要活动是 MainActivity,则启动它的方法如下:
using Android;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Net;
using Android.OS;
using Android.Runtime;
using Android.Views;
using static Android.Provider.ContactsContract.CommonDataKinds;
using static Java.Util.Jar.Attributes;
[assembly: UsesPermission(Manifest.Permission.ReceiveBootCompleted)]
namespace MMusicPlayer.Platforms.Android
{
[BroadcastReceiver(Enabled = true, DirectBootAware = true)]
[IntentFilter(new[] { Intent.ActionBootCompleted }]
public class StartReceiver : BroadcastReceiver
{
public override void OnReceive(Context? context, Intent? intent)
{
if (intent?.Action == Intent.ActionBootCompleted)
{
Intent startIntent = new Intent(context, typeof(MainActivity));
startIntent.AddFlags(ActivityFlags.NewTask);
context?.StartActivity(startIntent);
}
}
}
}
<receiver android:name=".StartReceiver" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>