我有方法,通过按下通知中的按钮来完成操作。
private void handleIncomingActions(Intent playbackAction) {
if (playbackAction == null || playbackAction.getAction() == null) {
return;
}
String actionString = playbackAction.getAction();
if (actionString.equalsIgnoreCase(ACTION_PLAY)) {
if (mediaPlayer != null) {
playMedia();
}
}
if (actionString.equalsIgnoreCase(ACTION_PAUSE)) {
if (mediaPlayer != null) {
pauseMedia();
//HERE NEED TO CHANGE SRC
}
}
if (actionString.equalsIgnoreCase(ACTION_CLOSE)) {
if (mediaPlayer != null) {
stopService(new Intent(this, MediaService.class));
getApplicationContext().unbindService(PlayerActivity.serviceConnection);
PlayerActivity.serviceBound = false;
//HERE NEED TO CHANGE SRC
}
}
}
在两种情况下,我需要从Service.class更改我的PlayerActivity类中的FAB图标。 如何在不使用“静态”和没有单例的情况下访问FAB?
答案 0 :(得分:1)
在服务中:
public static final String SERVICE_REQUEST = "com.example.app.service.SERVICE_REQUEST";
// ...
Intent data = new Intent(SERVICE_REQUEST);
LocalBroadcastManager.getInstance(ServiceClass.this).sendBroadcast(data);
活动:
// in onCreate for example
reseiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// update your fab here
}
}
// ...
@Override
public void onStop() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(reseiver);
super.onStop();
}
@Override
public void onStart() {
super.onStart();
LocalBroadcastManager.getInstance(this).registerReceiver(reseiver, new IntentFilter(ServiceClass.SERVICE_REQUEST));
}
答案 1 :(得分:0)
尝试一下:
将其添加到PlayerActivity
:
public void changeFloatingActionButtonIcon(int fabIcon) {
fab.setImageResource(fabIcon);
};
将此添加到Services.class:
((PlayerActivity) getActivity()).changeFloatingActionButtonIcon(R.drawable.icon);