在我的项目,我需要在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的后台服务
发布评论