从Fragment将侦听器设置为Android Service

时间:2014-03-17 09:08:22

标签: android service android-fragments

我的服务中有以下方法,可让我听取对服务执行的某些操作

public interface PlayerServiceListener {
    public void onTrackChange(HashMap<String, String> newtrack);
    public void onTrackStop();
    public void onTrackPause();
    public void onTrackPlay();
}
public void setListener(PlayerServiceListener listener) {
    this.listener = listener;
}

然后从我实现PlayerServiceListener的Fragment中得到以下ServiceConnection

private ServiceConnection mConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName className, IBinder service) {

            loader.dismiss();

            LocalBinder binder = (LocalBinder) service;
            mService = binder.getService();

            mService.setListener(getActivity()); //The method setListener(playerService.PlayerServiceListener) 
            //in the type playerService is not applicable for the arguments (FragmentActivity)

            previous.setEnabled(true);
            play.setEnabled(true);
            next.setEnabled(true);

            if (mService.status == BNMplayerService.TRACK_STOP)
                mService.nextTrack();
            else { 
                if (mService.status == BNMplayerService.TRACK_PAUSED) {
                    play.setImageDrawable(getResources().getDrawable(R.drawable.play));

                } 
                if (mService.status == BNMplayerService.TRACK_PLAYING) {
                    play.setImageDrawable(getResources().getDrawable(R.drawable.pause));
                }

                onTrackChange(mService.getInfo());
            }
        }

        // Called when the connection with the service disconnects unexpectedly
        public void onServiceDisconnected(ComponentName className) {
             mService = null;
        }
    };

我想使用行

设置此服务的监听器
mService.setListener(getActivity());

但是我收到一个错误(方法setListener(playerService.PlayerServiceListener) 在类型playerService中不适用于参数(FragmentActivity))

怎么办?

1 个答案:

答案 0 :(得分:2)

您声明当地mService

的地方
private MyPlayerServiceWithMyCustomMethod mService;

在ServiceConnection中投射本地变量:

LocalBinder binder = (LocalBinder) service;
mService = (MyPlayerServiceWithMyCustomMethod)binder.getService();
mService.setListener(MyFragmentThatImplementsMyInterface.this);