ServiceConnection.onServiceConnected() never called after binding to started service

后端 未结 3 1914
渐次进展
渐次进展 2021-01-06 18:25

In a game application I have the following scenario:

  • From the main game Activity, the player starts several game tasks that run in the background
相关标签:
3条回答
  • 2021-01-06 18:36

    ServiceConnection's onServiceConnected() is called, but nobody guarantees that it will be called before onCreate continues execution. So, what happens here - you successfuly bind to the service (that's why onBind returns true), but you're not fully connected - onServiceConnected() has not yet been called, so your local mProgressService object is not yet initalized, and therefore you get the NullPointerException.

    Solution:

    Move these two lines:

    mProgressBarList = mProgressService.getProgressBarList();
    mStaffNameList = mProgressService.getStaffNameList();
    

    from onCreate() to onServiceConnected() function (use the service object after it is initialized in onServiceConnected()).

    0 讨论(0)
  • 2021-01-06 18:46

    Check AndroidManifest.xml of yours and add service that you tried to bind.

    0 讨论(0)
  • 2021-01-06 18:47

    You have to return your Binder inner class from

    private final IBinder mBinder = new ServiceBinder();
    
     public class ServiceBinder extends Binder {
       public PlayerActivity getService() {
       return PlayerActivity.this;
         }
      }
    
    @Nullable
    @Override
               public IBinder onBind(Intent intent) {
                 return mBinder;
               }
    
    0 讨论(0)
提交回复
热议问题