Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - bindService at fragment

I have an Activity Class and at it's onResume part I've used the next code -

    @Override
protected void onResume() {

    super.onResume();
    bindService(new Intent(MainActivity.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
}

At the onPause I've used the next code -

@Override
protected void onPause() 
{       
    unbindService(mConnection);
    super.onPause();
}

As you can understand I'm binding and unbinding to a Service.

Now the thing is that I want to use fragment instead of Activity.

In order to do that I've changed the onPuse code into this -

    @Override
protected void onPause() 
{       
    getActivity().unbindService(mConnection);
    super.onPause();
}

And it seems fine.

But the thing I have problem with is the bind part at the onResume, I've tried the next code -

            @Override
    protected void onResume() {

        super.onResume();
 bindService(new Intent(getActivity(), IMService.class), mConnection , Context.BIND_AUTO_CREATE);
    }

But Eclipse gives me an error saying -

The method bindService(Intent, ServiceConnection, int) is undefined for the type MainFragment

the service is showing like this at the manifest -

    <service android:name="com.example.test.services.IMService" >
    </service>

So why I can't bind the Service into the fragment? Maybe I need to add something to the getActivity code?

Thnks for any kind of help

Thanks for @Raghunandan help - this is the solution-

getActivity().bindService(new Intent(getActivity(), IMService.class), mConnection , Context.BIND_AUTO_CREATE);
like image 938
4this Avatar asked Apr 24 '14 11:04

4this


1 Answers

Use

getActivity().bindService(params)

It requires a Context

like image 137
Raghunandan Avatar answered Sep 22 '22 07:09

Raghunandan