Search code examples
androidonclicktogglebutton

Error in calling StartService while in setOnClickListener onCreate


I have an activity which calls a service through

startService(new android.content.Intent(this,NeglectedService.class);

I am trying to add a ToggleButton, that while isChecked(True) the service will run, and vice versa.

        toggleService = (ToggleButton)findViewById(R.id.btnStopStartService);
    toggleService.setOnClickListener(new View.OnClickListener() 
    {
        @Override
        public void onClick(View v) 
        {
            if(toggleService.isChecked())
            {
                // Start the service
                showToast("true");
                startService(new Intent(this,NeglectedService.class));
            }
            else
            {
                // Pause/Stop the service
                showToast("false");
            }
        }
    });

But calling this way returns an error, I don't know how to tackle

The constructor Intent(new View.OnClickListener(){}, Class<NeglectedService>) is undefined

If I remove the new Intent(this, NeglectedService.class) than the error dissappears, but the service is not called (ofc, the activity doesn't know who to call)

So, my question: - How can I monitor and start/stop a service from my activity?

Question: How can I control a service state from the activity that created it? I have a togglebutton.onclicklistener. I want that when the toggle is ON, the service will run, and stop wehn toggled to off. I will use sharedpreferences to store the service state, but I get an error when calling startService(new android.content.Intent(this,NeglectedService.class); from the if(toggleService.isChecked())


Solution

  • The constructor that you are trying to use takes a Context as its first argument, but this isn't an instance of Context, it's the anonymous on-click listener that you are declaring. To pass the outer instance you need to qualify it:

    startService(new Intent(MyActivity.this, NeglectedService.class));
    

    where MyActivity is the name of your activity class.