У меня есть музыкальное приложение. Я пытаюсь обновить интерфейс с прогрессом медиаплеера (например, текущее время, текущая песня, обложка альбома) каждый раз, когда песня меняется. Я обнаружил, что использование интерфейсов - удивительный волшебный способ общения между действиями и фрагментами, поэтому я реализовал интерфейс в своем классе MusicManger. Мой код покажет, что и как он сделал.Обновления динамического пользовательского интерфейса с использованием интерфейса + ExecutorService Issue
Две проблемы
1) комментируемые взгляд ниже, ExecutorService, кажется, останавливается после одного цикла. Нет ошибок в блоке catch (вот почему я пометил java)
2) Прокомментировал, пожалуйста, посмотрите, все методы System.out печатаются, но пользовательский интерфейс не обновляется. Я верю, что я вызвал метод из mainThread, поэтому он должен обновляться.
Я покажу код в логическом порядке, добавит заголовки полужирным до сегмента кода, чтобы рассказать вам основную идею кода.
Попутный ссылки UI от фрагмента к классу MusicManager, ниже код в классе Фрагмент
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item_songlist, container, false);
// Set the adapter
TextView musicManagerSongName, musicManagerCurrent, musicManagerTotal;
ProgressBar musicManagerProgress;
ImageView musicManagerImageView;
mListView = (AbsListView) view.findViewById(R.id.slist);
musicManagerSongName = (TextView)view.findViewById(R.id.textView12);
musicManagerCurrent = (TextView)view.findViewById(R.id.textView10);
musicManagerTotal = (TextView)view.findViewById(R.id.textView11);
musicManagerProgress = (ProgressBar)view.findViewById(R.id.progressBar);
musicManagerImageView = (ImageView)view.findViewById(R.id.imageView2);
MainActivity.mediaPlayer.passUIReferences(musicManagerSongName, musicManagerCurrent, musicManagerTotal, musicManagerProgress, musicManagerImageView, view);
// line above is a method within MusicManager that takes the references will show code next!
ImageButton playbutton = (ImageButton)view.findViewById(R.id.playbuttonbar);
ImageButton nextButton = (ImageButton)view.findViewById(R.id.nextbuttonbar);
ImageButton backButton = (ImageButton)view.findViewById(R.id.backbuttonbar);
ImageButton toggleButton = (ImageButton)view.findViewById(R.id.shufflebuttonbar);
ImageButton pausebutton = (ImageButton)view.findViewById(R.id.pausebuttonbar);
playbutton.setBackgroundResource(R.drawable.playbuttonbar);
playbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
MainActivity.mediaPlayer.stateChange(1);
}catch(Exception e) {
}
}
});
backButton.setBackgroundResource(R.drawable.backbutton1);
nextButton.setBackgroundResource(R.drawable.nextbutton1);
toggleButton.setBackgroundResource(R.drawable.shufflebuttonselected);
pausebutton.setBackgroundResource(R.drawable.pausebutton1);
pausebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
MainActivity.mediaPlayer.stateChange(0);
} catch (Exception e){
}
}
});
mListView.setAdapter(mAdapter);
((MainActivity) mListener).restoreActionBar();
return view;
}
Как Высокую выше код, который находится в MusicManager класса, который принимает ссылки и сохраняет их. Также показана реализация интерфейса с классом MusicManager. И обслуживание Палач
public void passUIReferences(View... views) {
this.uiElements = views;
}
private ExecutorService executorService = Executors.newSingleThreadExecutor();
private MediaplayerUpdateInterface uiUpdateInterface;
public MediaPlayerManager(MediaplayerUpdateInterface inter) {
this.player = new MediaPlayer();
this.uiUpdateInterface = inter;
// The below line starts the single thread while loop for excutorservice and only loops and prints "this" once after I start one song then it never loops again
executorService.submit(new Runnable() {
@Override
public void run() {
while(true) {
if (player.isPlaying() && uiElements != null) {
System.out.println("this");
uiUpdateInterface.updateUI(uiElements, 0);
}
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
public interface MediaplayerUpdateInterface {
public void updateUI(View[] views, int type);
}
Наконец некоторый код из класса MainActivity, что на самом деле, предполагают, чтобы обновить пользовательский интерфейс к сведению, что работы как Println, как ожидается, но только один раз, как указано выше, из-за проблемы ExecutorService
public static MediaPlayerManager mediaPlayer = new MediaPlayerManager(new MediaPlayerManager.MediaplayerUpdateInterface() {
@Override
public void updateUI(View[] views, int type) {
System.out.println("check1 " + type);
updateMediaplayerViews(views, type);
}
});
private static void updateMediaplayerViews(View[] views, int type)
{
switch(type) {
case 0:
System.out.println("that?");
((TextView)views[0]).setText(mediaPlayer.getCurrentSongInfo().getName().length() > 22? mediaPlayer.getCurrentSongInfo().getName().substring(0, 19)+"..." : mediaPlayer.getCurrentSongInfo().getName());
break;
}
views[views.length - 1].invalidate();
}
Массив представления показан первичным! Также последний вид в массиве показан как основной вид фрагмента списка песен.
Прошу прощения за весь код, который я пытался отладить, как вы можете видеть из моего println, есть только то, о чем я не знаю, что происходит здесь.