0

When I launch the app on my phone the service's onCreate is called 3-4 times in less than a second.

on other hand the oncreate is set to start a thread derived class that prints the network ip of the device on the logcat.

weirdly each call to oncreate gives randomly either the actual ip (192.168.1.xxx) or the loopback (127.0.0.1)

@Override
public void onCreate() {
    super.onCreate();

    TheService=this;

    chargingState = GetChargingState();

    if(mainActivity!=null)
        mainActivity.UpdateDisplay(chargingState);

    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

    registerReceiver(new ChargingStateListener(),ifilter);

    new NetworkHandler().findServer();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {


    return START_STICKY;
}

Function to get the IP in the threaded class

    public String GetOwnIPAddress()
    {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;

    }
Allahjane
  • 1,920
  • 3
  • 24
  • 42

1 Answers1

1

You're misarchitecting your service.

OnCreate should never start a Thread. Anything like that should be done in onStartCommand or later. Creation of your service doesn't mean its running, that's what onStartCommand means. Your service may be created or killed at the will of the system, onCreate should do a bear minimum.

On a side note- never use your service as a singleton like you are with TheService=this. It can get you into all sorts of trouble such as querying a stopped service. If you need to call functions on a service, bind to it and return a Binder in onBind that accesses your API. What you're doing will cause memory leaks and crashes.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • Thanks moving stuff to onStartCommand worked, however the address printed by the thread is now stuck at the loopback address of 127.0.0.1, but that should be its own question – Allahjane Jul 30 '16 at 16:54
  • Well, that isn't actually wrong- the local host's IP is 127.0.0.1 :) See http://stackoverflow.com/questions/6064510/how-to-get-ip-address-of-the-device for other ways of getting it – Gabe Sechan Jul 30 '16 at 16:59