创建于Android的后台服务

编程入门 行业动态 更新时间:2024-10-24 23:20:25
本文介绍了创建于Android的后台服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在我的项目,我需要在Android中创建服务。我能够注册服务是这样的:

In my project I need to create a service in android. I am able to register the service like this :

<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <service android:enabled="true" android:name=".ServiceTemplate"/> <activity android:name=".SampleServiceActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>

我打电话的活动像下面这里面的服务: -

I am calling this service inside an activity like below:-

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Intent service = new Intent(getApplicationContext(), ServiceTemplate.class); this.startService(service); }

但是,如果我杀了当前的活动,该服务也被毁坏。我需要这个服务始终在后台运行。 我需要做什么? 如何注册该服务? 我如何启动服务?

But if I kill the current activity , the service is also destroyed. I need this service always running in the background. What I need to do? How do I register the service? How do I start the service?

推荐答案

尝试启动该服务在不同的线程,因此,当你将摧毁你的活动的服务将不会受到影响。它将运行没有任何中断。此外,在服务回报 Service.START_STICKY 从 onStartCommand(意向,标志,startId),以确保该服务重新创建,如果它是由系统(Android操作系统)。杀

Try to start the service in separate thread, so that when you will destroy your activity the service will not be affected. It will run without any interruption. Also, in the service return Service.START_STICKY from onStartCommand(intent, flags, startId) to make sure that the service is re-created if it is killed by the system (Android OS).

更多推荐

创建于Android的后台服务

本文发布于:2023-11-27 09:30:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637519.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:后台   创建于   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!