1

I am trying to start a service in android after it is constructed:

String ip = ((EditText)findViewById(R.id.ip)).getText().toString();
int port = Integer.valueOf( ((EditText)findViewById(R.id.port)).
                                          getText().toString() );

        try {
            IConnectionManager connectionManager = 
                new SocketConnectionManager(ip, port);
            Alerter alerter = new Alerter(connectionManager);
                            **//tell android to start alerter**
        } catch (IOException e) {
            // show a dialog 
            e.printStackTrace();
        }

It seems that android insists on instantiating the class it self. Does anyone know a way of injecting the dependencie without resorting to global state?

Anthony Forloney
  • 90,123
  • 14
  • 117
  • 115
Keynan
  • 11
  • 1
  • I think you need more explanation or a clearer example. What "dependency" do you think you're trying to inject? In general, DI will not work with major Android components (Activity, Service, etc.). If you are trying to pass the IP address and port to the service, use extras on the Intent you use with startService() or bindService(). – CommonsWare Feb 09 '10 at 22:29
  • 1
    http://stackoverflow.com/questions/2135378/android-and-dependency-injection – Mauricio Scheffer Feb 10 '10 at 01:16
  • Thanks, that sounds like it would work. Were, then is it appropiate to retrieve the bundle? – Keynan Feb 11 '10 at 02:42
  • @CommonsWare the problem is, that Android instantiates reinstantiates certain classes (fragment, activity) e.g. onDeviceRotate(). I ran into this problem too, when I was working on my own [Android DI framework](http://www.baracus.org). I solved the problem inventing a [ManagedFragment](http://www.baracus.org/apidocs/0.8.1/net/mantucon/baracus/context/ManagedFragment.html) and a [ManagedActivity](http://www.baracus.org/apidocs/0.8.1/net/mantucon/baracus/context/ManagedActivity.html) provided by the framework and taking care for DI on reinstantiation. Trick is overriding the constructors. – gorefest Oct 17 '14 at 06:09

0 Answers0