从 Activity 启动服务
在我的应用程序中,我有一个活动,我想从中启动服务。有人可以帮助我吗?
In my app, I have an Activity from which I want to start a Service. Can anybody help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在您的代码中添加此内容
不要忘记在 AndroidManifest.xml 文件中添加服务标签
来自 Android 官方文档:
Add this in your code
Dont forget to add service tag in AndroidManifest.xml file
From the Android official documentation:
应用程序可以借助 Context.startService 方法启动服务。如果service还没有创建,该方法会调用service的onCreate方法;否则 onStart 方法将被调用。这是代码:
The application can start the service with the help of the Context.startService method. The method will call the onCreate method of the service if service is not already created; else onStart method will be called. Here is the code:
首先从 android
Manifest.xml
文件(即从应用程序选项卡)创建服务并为其指定一些名称。在某些事件(例如单击或触摸)的活动上包含来自服务的代码:
如果您想停止正在运行或已启动的服务,请包含以下代码:
First create service from android
Manifest.xml
file (i.e from application tab) and give some name to it.On the activity on some event like click or touch to include the code from the service:
If you want to stop the running or started service then include this code:
API 演示 有一些启动服务的示例。
The API Demos have some examples that launch services.
使用 Context.startService() 方法。
并阅读本文。
Use a Context.startService() method.
And read this.
在 kotlin 中,您可以从 Activity 启动服务,如下所示:
in
kotlin
you can start service from activity as follow :如果您想启动一项服务并且该服务应在后台运行,请在相应的服务中使用 START_STICKY。
您也可以在启动时启动服务,
并创建接收器,
在 Brodcast 接收器中添加,
您的服务就像,
If you want to start a service and it should run in background use START_STICKY in your corresponding service.
You can start service with on boot also,
And create receiver,
In Brodcast Receiver add,
And your service is like,