简体   繁体   中英

Android Service restarting multiple times

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;

    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM