Android可能导致服务引用为null

时间:2014-08-23 16:56:47

标签: java android android-service android-mediaplayer

我正在执行以下代码,我通过调试器运行它,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) {
        }
    }

AudioPlayer

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();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您在调用bindService()的本地范围内声明audioPlayerService。对bindService的调用是异步的,并且在您(可能)尝试使用audioPlayerConnection之前没有调用onServiceConnected(),就像服务已经绑定一样。