1

How to start a service on its own?? I dont want to start the service from another activity.but i want to bind to the service to the activity.. my problem is exactly as described in this link. onServiceConnected never called after bindService method i.e my onserviceconnected is never called.

Messenger mService = null;
public void onServiceConnected(ComponentName className, IBinder service) {
            mService = new Messenger(service);
            Log.d("IMSLogging", "inside onServiceConnected");
        }

from oncreate of my activity i am calling bindService.but i am getting a nullpointerexception when i am doing mService.send(msg); from oncreate.(after the bindService is called, of course.) though bindService is returning true.,

Community
  • 1
  • 1
scooby
  • 493
  • 11
  • 31
  • I believe i have posted the code. The problem is mService stays null even after i call bindservice from oncreate method.also the log.d that i have mentioned in the code is never found in the logs.. – scooby Jul 23 '12 at 11:58

1 Answers1

2

You can't call mService.send() until after you get the onServiceConnected() callback. That means you can't do both bindService() and mService.send() in onCreate(). You need to move the mService.send() call into either onResume() or into onServiceConnected() or somewhere else.

David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • Even I was thinking of the same.But all these happens onclick of a button.and the setonClickListener and onCreate and all. they are defined in onCreate only. Do I then shift every thing ??? – scooby Jul 23 '12 at 12:03
  • 1
    You can post your code and I can help you some more. However, you should be able to setup your UI in `onCreate()`, you just cannot use the service until **after** the `onServiceConnected()` callback comes back. – David Wasser Jul 23 '12 at 12:27
  • Hey,Thanks, i got it solved. Actually i was calling the onBind within the onclick listener.Thanks. :) – scooby Jul 23 '12 at 14:00
  • @scooby: Whats the issue calling onBind within the onclick listener? – Kavitha Feb 09 '13 at 02:37