1

我有一个片段,我想与服务器通信,但问题是我总是得到空指针

我在我的片段 onCreateView 中有这个:

public class BrowseFragment extends Fragment implements View.OnClickListener{

private MusicService mMusicService;


@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment, container, false);



    mMusicService = new MusicService(this);
             mMusicService.setCallback(new MusicService.Callback() {


                                @Override
                                public void onPlayPause(String state) {
                                    //Do something
                                }
                            });

}
}

这是我的服务:

 public class MusicService extends MediaBrowserServiceCompat {


public interface Callback {
        public void onPlayPause(String state);
    }

    public void setCallback(Callback callback) {
        this.mCallback = callback;
    }





private void PauseRequest() {
        mPlayback.pause();
        //if (mCallback != null) {
            mCallback.onPlayPause("PAUSE");
        //}
}

}

我得到了这个致命的例外:主要

Process: com.geobytenet.mediaplayer, PID: 3262
java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.android.mediabrowserservice.MusicService$Callback.onPlayPause(java.lang.String)' on a null object reference

我希望你能帮帮我

4

2 回答 2

0

您不能像简单的类一样在 Android 中创建 MusicService。这是一项服务,必须以正确的方式启动https://medium.com/google-developers/mediabrowserservicecompat-and-the-modern-media-playback-app-7959a5196d90

于 2017-07-28T19:23:05.987 回答
0

在 MusicService 中,我添加了这个方法

    public void pausePlay() {
        PauseRequest();
    }

然后在 BrowseFragment 中,在onCreateView()

    Button button = (Button)rootView.findViewById(R.id.button_play_pause);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mMusicService.pausePlay();
        }
    });
于 2017-08-03T20:33:51.910 回答