android - 从 Activity 启动服务

标签 android android-activity android-service

在我的应用中,我有一个 Activity,我想从中启动一个服务。有人可以帮帮我吗?

最佳答案

在你的代码中添加这个

Intent serviceIntent = new Intent(this, ServiceName.class);
    startService(serviceIntent);

别忘了在 AndroidManifest.xml 文件中添加服务标签

<service android:name="com.example.ServiceName"></service>

来自 Android official documentation :

Caution: A service runs in the same process as the application in which it is declared and in the main thread of that application, by default. So, if your service performs intensive or blocking operations while the user interacts with an activity from the same application, the service will slow down activity performance. To avoid impacting application performance, you should start a new thread inside the service.

关于android - 从 Activity 启动服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2334955/

相关文章:

android - DBAdapter设计问题

java - androidx.gridlayout.widget.GridLayout 无法转换为 android.widget.GridLayout

没有 Activity 的 Android 应用程序将充当服务并在设备启动时启动?

android - 尝试向 ListView 添加页脚时出现 ClassCastException

android - 如何在 Android 中解析来自网站的 Html 标签

Android SDK 相机 API 演示崩溃

Android "Back"按钮操作

java - 从 fragment 访问主要 Activity View

android - 想在特定时间一个接一个地上传一堆文件

Android Service及其引擎