Android: Stop/start service created in onCreate()

二次信任 提交于 2019-11-30 08:08:52

问题


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);

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.

I had looks at stop service in android but their method of starting the service seems not to work within 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);

        }
    };

回答1:


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. 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" />


来源:https://stackoverflow.com/questions/16876538/android-stop-start-service-created-in-oncreate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!