Activity Android 应用 运行 在后台不需要

Activity not required for Android app running in the background

当 运行 不需要 Activity 并在后台运行的 Xamarin Android 应用程序时,Visual studio 内发生错误。

No Launchable Activity: This project does not contain any activities marked MainLauncher. It has been deployed to the device, but no activity will be launched.

To mark an activity as launchable, add the [Activity] attribute to it with MainLauncher = true:

[Activity (MainLauncher = true)] public class MyActivity : Activity

下面是我的代码

[Application(Label = "@string/app_name")]
    public class Application : Android.App.Application
    {
        public Application(IntPtr javaReference, JniHandleOwnership transfer)
           : base(javaReference, transfer)
        {
        }

        public override void OnCreate()
        {
            base.OnCreate();

            Xamarin.Essentials.Platform.Init(this);      
            Intent oaServiceIntent = new Intent(this, typeof(MainApplicationService));
            StartService(oaServiceIntent);
        }
}

我是否必须创建一个 Activity 即使它不是必需的?

为了让用户启动您的应用程序,您必须至少有一个 Activity 并且它必须在清单中有一个 ACTION=MAIN 和 CATEGORY=LAUNCHER 的条目,这样它就会显示在主页屏幕。

如果用户无法手动启动您的应用程序,那么它就无法启动,并且没有后台组件(ServiceBroadcastReceiver 等)将 运行。

Application 实例仅在 Android 创建一个 OS 进程来托管您的应用程序时创建,并且只有在用户手动启动您的应用程序时才会发生这种情况 安装后至少一次