创建于Android的后台服务 [英] Creating Background Service in Android

查看:135
本文介绍了创建于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的后台服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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