onServiceConnected never called after bindService method

后端 未结 12 623
醉话见心
醉话见心 2020-11-30 05:48

I have a particular situation: a service started by a broadcast receiver starts an activity. I want to make it possible for this activity to communicate back to the service.

相关标签:
12条回答
  • 2020-11-30 06:03

    One more thing is that if you are calling bindservice method inside the oncreate method then the onserviceconnected is called after the oncreate method is finished.

    So any references to the interface functions before the oncreate ends (or before onserviceconnected is called) shows null pointer exception.

    0 讨论(0)
  • 2020-11-30 06:03

    Yet another cause to the original question might be that the service isn't already running and you are passing 0 as flag to bindService. Like so:

    bindService(intent, serviceConnection, 0);
    

    When what you are looking for would be:

    bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    
    0 讨论(0)
  • 2020-11-30 06:07

    I was calling bind with an empty Intent - getContext().bindService(new Intent(), mConnection, Context.BIND_AUTO_CREATE). I have to make the intent more specific to indicate which service I want to bind to. This is obviously a code error, but the Logcat output was unfortunately not clear enough.

    0 讨论(0)
  • 2020-11-30 06:14

    I can't make up the exact problem out of your description, so I'm going to guess here!

    How can bindService() throw a NullPointerException? The only way this could (/should) happen is when you don't supply a Service or a ServiceConnection listener.

    bindService() can't throw a NullPointerException because onServiceConnected() isn't called. The call to onServiceConnected() is a product of bindService().

    So I guess you are calling a AIDL method, before the Service has actually bonded?

    0 讨论(0)
  • 2020-11-30 06:15

    You Must Wait To Complete onCreate() method. Example: Set Your Buy Service in Buttom:

    Button button_useservice=findViewById(R.id.button_useservice);
                button_useservice.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        UsinService();
                    }
                });
    
    0 讨论(0)
  • 2020-11-30 06:18

    I also encountered the same problem. And minutes later I found that my code had absolutely no problem. It was the manifest file that had the issue. Earlier I was declaring the service with its name only.

    <service android:name=".MyBoundService"/>
    

    Change it to the full name with the package name

    <service android:name="com.pb.servicedemo.MyBoundService"/>
    

    This way you will be able to see your service bound to the activity.

    0 讨论(0)
提交回复
热议问题