Amir Panahandeh
Amir Panahandeh

Reputation: 9059

Getting object of service

I'm trying to get my Services object and I'm doing that with this code

public class Service extends android.app.Service {
private Handler handler = new Handler();
static Service SELF;
MainActivity mainActivity;
BluetoothSPP bluetoothSPP;

public static Service getInstance() {
    return SELF;
}

@Override
public void onCreate() {
    super.onCreate();
    SELF = this;
    }
}

but after starting service getInstance() gives null. why?

Upvotes: 1

Views: 129

Answers (1)

Alex Shutov
Alex Shutov

Reputation: 3282

Service and Activity is a different components, managed by Android, so you should not save reference to Activity insie Service. Solution in this case - use Service binding - you can move all your methods into separate interface, by which your Service and Activity will communicate and return it from Binder once Service is bound to Activity. See: https://developer.android.com/guide/components/bound-services.html, Bind service to activity in Android

Upvotes: 3

Related Questions