在没有主 Activity 的情况下启动 Android 应用程序并在启动应用程序时启动服务 [英] Launch Android application without main Activity and start Service on launching application

查看:40
本文介绍了在没有主 Activity 的情况下启动 Android 应用程序并在启动应用程序时启动服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有以下场景.我的应用程序中没有 UI;相反,有一个服务会在启动时启动并持续运行.

I have the following scenario in my application. There is no UI in my application; instead there is a Service which starts on boot up and will continuously run.

如何在没有主活动的情况下配置我的清单文件?我可以在没有任何活动的情况下启动我的应用程序吗?在启动我的应用程序时,我的服务应该启动.这可能吗?

How can I configure my manifest file without a main Activity? Can I launch my app without any Activity? And on launching my app, my Service should start. Is this possible?

我不想制作一个半透明的 Activity 来启动服务.

I don't want to make a translucent Activity to start the Service.

推荐答案

你说你不想使用半透明的 Activity,但这似乎是最好的方法:

You said you didn't want to use a translucent Activity, but that seems to be the best way to do this:

  1. 在您的清单中,将活动主题设置为 Theme.Translucent.NoTitleBar.
  2. 不要为 Activity 的布局而烦恼,也不要调用 setContentView().
  3. 在您的 Activity 的 onCreate() 中,使用 startService() 启动您的服务.
  4. 启动服务后,使用 finish() 退出活动.
  1. In your Manifest, set the Activity theme to Theme.Translucent.NoTitleBar.
  2. Don't bother with a layout for your Activity, and don't call setContentView().
  3. In your Activity's onCreate(), start your Service with startService().
  4. Exit the Activity with finish() once you've started the Service.

换句话说,您的 Activity 不必是可见的;它可以简单地确保您的服务正在运行,然后退出,这听起来像您想要的.

In other words, your Activity doesn't have to be visible; it can simply make sure your Service is running and then exit, which sounds like what you want.

我强烈建议至少显示一个 Toast 通知,表明您正在启动服务或服务已经在运行的用户.当你按下启动器图标时,它似乎什么也不做,这是非常糟糕的用户体验.

I would highly recommend showing at least a Toast notification indicating to the user that you are launching the Service, or that it is already running. It is very bad user experience to have a launcher icon that appears to do nothing when you press it.

这篇关于在没有主 Activity 的情况下启动 Android 应用程序并在启动应用程序时启动服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆