从BroadcastReceiver类更改ToggleButton状态

时间:2018-01-21 19:30:52

标签: java android togglebutton

我正在尝试构建一个收音机应用,其中包含mainactivity togglebutton播放和暂停音乐,并且还有一个通知媒体控制器,用于点击我想要的播放/暂停音乐从通知暂停togglebutton将状态从true更改为false,反之亦然。

MainActivity

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyIntentSerice.myActivityforservice = this;
}
  @Subscribe
public void handlePlaybackEvent(PlaybackEvent event) {
    switch (event) {
        case PLAY:
            if (mediaPlayer.isPlaying())
                mediaPlayer.pause();
            break;
        case PAUSE:
            if (!mediaPlayer.isPlaying())
                mediaPlayer.start();
            break;
    }
}
 @Override
protected void onResume() {
    super.onResume();
    try {
        MApplication.sBus.register(this);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    try {
        MApplication.sBus.unregister(this);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

BroadcastReceiver

public class MyIntentSerice extends BroadcastReceiver {
    public static final String RESUME_ACTION = "RESUME_ACTION";
    public static final String STOP_ACTION = "STOP_ACTION";
    public static int REQUEST_CODE_NOTIFICATION = 1212;
    public static Activity myActivityforservice;

    @Override
    public void onReceive(Context context, Intent intent) {
        ToggleButton music = MyIntentSerice.myActivityforservice.findViewById(R.id.toggleButton);
        if (music != null && intent.getAction() != null) {
            switch (intent.getAction()) {
                case RESUME_ACTION:
                    MApplication.sBus.post(PlaybackEvent.PAUSE);
                    music.setChecked(false);
                    break;
                case STOP_ACTION:
                    MApplication.sBus.post(PlaybackEvent.PLAY);
                    music.setChecked(true);
                    break;
            }
        }
    }
}

MApplication

public class MApplication extends MultiDexApplication {
    public static Bus sBus = new Bus(ThreadEnforcer.MAIN);

    @Override
    public void onCreate() {
        super.onCreate();
        sBus.register(this);
    }
}

PlaybackEvent

public enum PlaybackEvent {
    PLAY, PAUSE
}

我的代码不起作用:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference

0 个答案:

没有答案