You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET MAUI Android端系统重启后如何自动重启应用?

.NET MAUI Android系统重启后自动启动应用问题

我正在.NET MAUI 7.0应用中实现Android系统重启后自动启动应用的功能,已编写以下代码,但尝试了StackOverflow上所有相关解决方案后仍无效。开发环境为Visual Studio 2022。

现有实现代码

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application android:allowBackup="true" android:icon="@mipmap/appicon" android:roundIcon="@mipmap/appicon_round" android:supportsRtl="true">
<receiver android:enabled="true" android:name="com.companyname.mauiapp3.BootBroadcastReceiver" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest>

BootBroadcastReceiver.cs

using global::Android.App;
using global::Android.Content; 

[BroadcastReceiver(Enabled = true, DirectBootAware = true,Exported = true)]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class BootBroadcastReceiver : BroadcastReceiver
{
   public override void OnReceive(Context context, Intent intent)
   {
      Intent i = new Intent(context, typeof(MainActivity));
      i.AddFlags(ActivityFlags.NewTask);
      context.StartActivity(i);
    }
}

MainActivity.cs

[Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
public class MainActivity : MauiAppCompatActivity
{
    BootBroadcastReceiver receiver;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        receiver = new BootBroadcastReceiver();
    }
}

排查与修复要点

  • 移除重复配置:同时在AndroidManifest.xml和代码特性中配置广播接收器可能导致冲突,建议保留代码中的特性配置,删除AndroidManifest.xml内的<receiver>节点。
  • 确认权限授予:除了清单文件声明,部分Android版本(尤其是国内定制ROM)需要手动在应用设置中开启自启动权限,确保RECEIVE_BOOT_COMPLETED权限生效。
  • 调整DirectBoot配置:若无需直接启动感知,移除DirectBootAware = true以避免权限问题;若需要该功能,需补充对应权限与逻辑。
  • 优化启动标志:在OnReceive中启动Activity时,可添加更多兼容标志:
    i.AddFlags(ActivityFlags.NewTask | ActivityFlags.ClearTop | ActivityFlags.ClearTask);
    
  • 模拟广播测试:无需频繁重启系统,用ADB命令模拟开机广播验证逻辑:
    adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -n com.companyname.mauiapp3/.BootBroadcastReceiver
    
  • 检查应用状态:确保应用未被系统冻结、休眠或标记为异常,这类状态会限制自启动行为。

内容的提问来源于stack exchange,提问作者SAN SHEVA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 22:22:44