Android:在onCreate()中创建停止/启动服务 [英] Android: Stop/start service created in onCreate()
问题描述
我目前有一项服务是在活动的onCreate方法中启动的,使用:
I currently have a service that is started within the onCreate method of an activity using:
Intent intentService = new Intent(this, MainService.class);
this.startService(intentService);
我现在需要按下按钮停止此服务并在另一个按钮上重新启动它按,但我不确定如何停止此服务并在onCreate方法的一侧再次启动它。
I need to now be able to stop this service on a button press and restart it again on another button press, however I am unsure how to stop this service and start it again out side of the onCreate method.
我想我需要以不同的方式启动服务比我现在做的更多?但我不确定最好的方法。
I guess I would need to start the service in a different way than what I am currently doing? But I am unsure on the best method for this.
我看过在Android中停止服务但他们启动服务的方法似乎不能在onCreate中工作。
I had looks at stop service in android but their method of starting the service seems not to work within onCreate.
更完整的视图代码:
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lock = (Button) this.findViewById(R.id.lock);
unlock = (Button) this.findViewById(R.id.unlock);
lock.setOnClickListener(btn_lock);
unlock.setOnClickListener(btn_unlock);
unlock.setVisibility(View.VISIBLE);
lock.setVisibility(View.GONE);
Intent intentService = new Intent(this, MainService.class);
this.startService(intentService);
}
private OnClickListener btn_lock = new OnClickListener() {
public void onClick(View v) {
unlock.setVisibility(View.VISIBLE);
lock.setVisibility(View.GONE);
}
};
private OnClickListener btn_unlock = new OnClickListener() {
public void onClick(View v) {
unlock.setVisibility(View.GONE);
lock.setVisibility(View.VISIBLE);
}
};
推荐答案
什么时候想要启动服务所需的一切是
When ever you want to start a service all you need is
startService(new Intent(this, MainService.class));
要随时停止服务,只需致电
And to Stop a service anytime just call
stopService(new Intent(this, MainService.class));
请记住,需要在AndroidManifest.xml中声明服务。正如您所说,您的服务正在运作。我相信你已经做到了。
仍然AndroidManifest.xml
Remember service needs to be declared in AndroidManifest.xml. As you said that your service is working. I'm sure you have done that. Still AndroidManifest.xml
<service android:enabled="true" android:name=".MainService" />
这篇关于Android:在onCreate()中创建停止/启动服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!