[英]Android: Stop/start service created in onCreate()
I currently have a service that is started within the onCreate method of an activity using: 我目前有一个在活动的onCreate方法中启动的服务,使用:
Intent intentService = new Intent(this, MainService.class);
this.startService(intentService);
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. 我现在需要能够在按下按钮时停止此服务并在另一个按钮上再次重新启动它,但是我不确定如何停止此服务并在onCreate方法之外再次启动它。
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. 但我不确定最好的方法。
I had looks at stop service in android but their method of starting the service seems not to work within onCreate. 我曾在android中查看停止服务但是他们启动服务的方法似乎不能在onCreate中工作。
A more complete over view of my code: 更完整的代码视图:
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));
Remember service needs to be declared in AndroidManifest.xml. 记住服务需要在AndroidManifest.xml中声明。 As you said that your service is working. 正如您所说,您的服务正在运作。 I'm sure you have done that. 我相信你已经做到了。 Still AndroidManifest.xml 还是AndroidManifest.xml
<service android:enabled="true" android:name=".MainService" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.