我正在执行以下代码,我正在通过调试器运行此代码,audioPlayerConnection.service始终为null。为什么会这样呢?

各种日志调用似乎也不总是被执行(我想这可能与已经启动的服务有关)。

    Intent intent = new Intent(this, AudioPlayer.class);
    AudioPlayerConnection audioPlayerConnection = new AudioPlayerConnection();
    startService(intent);
    bindService(intent, audioPlayerConnection, Context.BIND_AUTO_CREATE);


AudioPlayerConnection

    public class AudioPlayerConnection implements ServiceConnection {
        public IBinder service;

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            this.service = service;
            Log.d("hmm", "audio service connected!!!");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }


音频播放器

public class AudioPlayer extends Service {

    public ArrayList<MediaPlayer> audioResources = new ArrayList<MediaPlayer>();

    public AudioPlayer() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d("hmm", "audio service binded!!!");
        return new AudioPlayerBinder();
    }

    public class AudioPlayerBinder extends Binder {
        public void stopAll()
        {
            int i = 0;
            for (MediaPlayer mp : audioResources)
            {
                mp.stop();
                mp.release();
                audioResources.remove(i);
                i++;
            }
        }

        public void add(Integer resourceId, boolean loop)
        {
            MediaPlayer mp = MediaPlayer.create(null, resourceId);

            if (loop)
            {
                mp.setLooping(true);
                audioResources.add(mp);
            }

            mp.start();
        }
    }
}

最佳答案

您在要调用bindService()的本地范围内声明audioPlayerService。对bindService的调用是异步的,并且在(大概)尝试使用audioPlayerConnection之前(好像已经绑定了Service一样),不会调用onServiceConnected()。

10-05 22:59