1

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?

Amir_P
  • 8,322
  • 5
  • 43
  • 92

1 Answers1

3

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

Community
  • 1
  • 1
Alex Shutov
  • 3,217
  • 2
  • 13
  • 11
  • but with this method I will not be able to keep service in background while application is closed – Amir_P Nov 09 '16 at 13:47
  • You can start service AND bind to it, so it will remain active after application is closed – Alex Shutov Nov 09 '16 at 13:49
  • so you say after starting service I should make a new object and bind it? It doesn't make sense – Amir_P Nov 09 '16 at 13:58
  • Service will be running by itself and can keep all objects. You define interface for interfaction with that Service and acquire it when Service is bound. If Activity is paused or stopped, you unbind from service and bind again when it re- created. If it was started and bound to, it will run until you call .stopService() – Alex Shutov Nov 09 '16 at 14:02
  • can you post code? I don't know how to implement it – Amir_P Nov 09 '16 at 14:06