summaryrefslogtreecommitdiff
path: root/src/de/danoeh/antennapod/activity/MediaplayerActivity.java
blob: 309f658a292afcc04c923ccf60a38a825dd044fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
package de.danoeh.antennapod.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.VideoView;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.viewpagerindicator.TabPageIndicator;

import de.danoeh.antennapod.AppConfig;
import de.danoeh.antennapod.PodcastApp;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.adapter.SCListAdapter;
import de.danoeh.antennapod.feed.FeedManager;
import de.danoeh.antennapod.feed.FeedMedia;
import de.danoeh.antennapod.feed.SimpleChapter;
import de.danoeh.antennapod.fragment.CoverFragment;
import de.danoeh.antennapod.fragment.ItemDescriptionFragment;
import de.danoeh.antennapod.service.PlaybackService;
import de.danoeh.antennapod.service.PlayerStatus;
import de.danoeh.antennapod.util.Converter;
import de.danoeh.antennapod.util.MediaPlayerError;
import de.danoeh.antennapod.util.StorageUtils;
import de.danoeh.antennapod.util.menuhandler.FeedItemMenuHandler;

public class MediaplayerActivity extends SherlockFragmentActivity implements
		SurfaceHolder.Callback {

	private final String TAG = "MediaplayerActivity";

	private static final int DEFAULT_SEEK_DELTA = 30000; // Seek-Delta to use
															// when using FF or
															// Rev Buttons
	/** Current screen orientation. */
	private int orientation;

	/** True if video controls are currently visible. */
	private boolean videoControlsShowing = true;
	/** True if media information was loaded. */
	private boolean mediaInfoLoaded = false;

	private PlaybackService playbackService;
	private MediaPositionObserver positionObserver;
	private VideoControlsHider videoControlsToggler;

	private FeedMedia media;
	private PlayerStatus status;
	private FeedManager manager;

	// Widgets
	private CoverFragment coverFragment;
	private ItemDescriptionFragment descriptionFragment;
	private ViewPager viewpager;
	private TabPageIndicator tabs;
	private MediaPlayerPagerAdapter pagerAdapter;
	private VideoView videoview;
	private TextView txtvStatus;
	private TextView txtvPosition;
	private TextView txtvLength;
	private SeekBar sbPosition;
	private ImageButton butPlay;
	private ImageButton butRev;
	private ImageButton butFF;
	private LinearLayout videoOverlay;

	@Override
	protected void onStop() {
		super.onStop();
		if (AppConfig.DEBUG)
			Log.d(TAG, "Activity stopped");
		try {
			unregisterReceiver(statusUpdate);
		} catch (IllegalArgumentException e) {
			// ignore
		}

		try {
			unregisterReceiver(notificationReceiver);
		} catch (IllegalArgumentException e) {
			// ignore
		}

		try {
			unbindService(mConnection);
		} catch (IllegalArgumentException e) {
			// ignore
		}
		if (positionObserver != null) {
			positionObserver.cancel(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = new MenuInflater(this);
		inflater.inflate(R.menu.mediaplayer, menu);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {

		menu.findItem(R.id.support_item).setVisible(
				media != null && media.getItem().getPaymentLink() != null);
		menu.findItem(R.id.share_link_item).setVisible(
				media != null && media.getItem().getLink() != null);
		menu.findItem(R.id.visit_website_item).setVisible(
				media != null && media.getItem().getLink() != null);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			startActivity(new Intent(MediaplayerActivity.this,
					MainActivity.class));
			break;
		default:
			return FeedItemMenuHandler.onMenuItemClicked(this, item,
					media.getItem());
		}
		return true;
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (AppConfig.DEBUG)
			Log.d(TAG, "Resuming Activity");
		StorageUtils.checkStorageAvailability(this);
		bindToService();

	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (AppConfig.DEBUG)
			Log.d(TAG, "Configuration changed");
		orientation = newConfig.orientation;
		if (positionObserver != null) {
			positionObserver.cancel(true);
		}
		setupGUI();
		handleStatus();

	}

	@Override
	protected void onPause() {
		super.onPause();
		if (PlaybackService.isRunning && playbackService != null
				&& playbackService.isPlayingVideo()) {
			playbackService.stop();
		}
		if (videoControlsToggler != null) {
			videoControlsToggler.cancel(true);
		}
		finish();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (AppConfig.DEBUG)
			Log.d(TAG, "Creating Activity");
		StorageUtils.checkStorageAvailability(this);

		orientation = getResources().getConfiguration().orientation;
		manager = FeedManager.getInstance();
		getWindow().setFormat(PixelFormat.TRANSPARENT);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		bindToService();
	}

	private void bindToService() {
		Intent serviceIntent = new Intent(this, PlaybackService.class);
		boolean bound = false;
		if (!PlaybackService.isRunning) {
			if (AppConfig.DEBUG)
				Log.d(TAG, "Trying to restore last played media");
			SharedPreferences prefs = getApplicationContext()
					.getSharedPreferences(PodcastApp.PREF_NAME, 0);
			long mediaId = prefs.getLong(PlaybackService.PREF_LAST_PLAYED_ID,
					-1);
			long feedId = prefs.getLong(
					PlaybackService.PREF_LAST_PLAYED_FEED_ID, -1);
			if (mediaId != -1 && feedId != -1) {
				serviceIntent.putExtra(PlaybackService.EXTRA_FEED_ID, feedId);
				serviceIntent.putExtra(PlaybackService.EXTRA_MEDIA_ID, mediaId);
				serviceIntent.putExtra(
						PlaybackService.EXTRA_START_WHEN_PREPARED, false);
				serviceIntent.putExtra(PlaybackService.EXTRA_SHOULD_STREAM,
						prefs.getBoolean(PlaybackService.PREF_LAST_IS_STREAM,
								true));
				startService(serviceIntent);
				bound = bindService(serviceIntent, mConnection,
						Context.BIND_AUTO_CREATE);
			} else {
				if (AppConfig.DEBUG)
					Log.d(TAG, "No last played media found");
				status = PlayerStatus.STOPPED;
				setupGUI();
				handleStatus();
			}
		} else {
			bound = bindService(serviceIntent, mConnection, 0);
		}
		if (AppConfig.DEBUG)
			Log.d(TAG, "Result for service binding: " + bound);
	}

	private void handleStatus() {
		switch (status) {

		case ERROR:
			setStatusMsg(R.string.player_error_msg, View.VISIBLE);
			break;
		case PAUSED:
			setStatusMsg(R.string.player_paused_msg, View.VISIBLE);
			loadMediaInfo();
			if (positionObserver != null) {
				positionObserver.cancel(true);
				positionObserver = null;
			}
			butPlay.setImageResource(R.drawable.av_play);
			break;
		case PLAYING:
			setStatusMsg(R.string.player_playing_msg, View.INVISIBLE);
			loadMediaInfo();
			setupPositionObserver();
			butPlay.setImageResource(R.drawable.av_pause);
			break;
		case PREPARING:
			setStatusMsg(R.string.player_preparing_msg, View.VISIBLE);
			loadMediaInfo();
			break;
		case STOPPED:
			setStatusMsg(R.string.player_stopped_msg, View.VISIBLE);
			break;
		case PREPARED:
			loadMediaInfo();
			setStatusMsg(R.string.player_ready_msg, View.VISIBLE);
			butPlay.setImageResource(R.drawable.av_play);
			break;
		case SEEKING:
			setStatusMsg(R.string.player_seeking_msg, View.VISIBLE);
			break;
		case AWAITING_VIDEO_SURFACE:
			if (AppConfig.DEBUG)
				Log.d(TAG, "Preparing video playback");
			this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		}
	}

	private void setStatusMsg(int resId, int visibility) {
		if (orientation == Configuration.ORIENTATION_PORTRAIT) {
			if (visibility == View.VISIBLE) {
				txtvStatus.setText(resId);
			}
			txtvStatus.setVisibility(visibility);
		}
	}

	@SuppressLint("NewApi")
	private void setupPositionObserver() {
		if (positionObserver == null || positionObserver.isCancelled()) {
			if (AppConfig.DEBUG)
				Log.d(TAG, "Setting up position observer");
			positionObserver = new MediaPositionObserver() {

				@Override
				protected void onProgressUpdate(Void... v) {
					super.onProgressUpdate();
					txtvPosition.setText(Converter
							.getDurationStringLong(playbackService.getPlayer()
									.getCurrentPosition()));
					txtvLength.setText(Converter
							.getDurationStringLong(playbackService.getPlayer()
									.getDuration()));
					updateProgressbarPosition();
					pagerAdapter.notifyMediaPositionChanged();
				}

			};
			if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
				positionObserver.executeOnExecutor(
						AsyncTask.THREAD_POOL_EXECUTOR,
						playbackService.getPlayer());
			} else {
				positionObserver.execute(playbackService.getPlayer());
			}

		}
	}

	private void updateProgressbarPosition() {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Updating progressbar info");
		MediaPlayer player = playbackService.getPlayer();
		float progress = ((float) player.getCurrentPosition())
				/ player.getDuration();
		sbPosition.setProgress((int) (progress * sbPosition.getMax()));
	}

	private void loadMediaInfo() {
		if (!mediaInfoLoaded) {
			if (AppConfig.DEBUG)
				Log.d(TAG, "Loading media info");
			if (media != null) {
				getSupportActionBar().setSubtitle(media.getItem().getTitle());
				getSupportActionBar().setTitle(
						media.getItem().getFeed().getTitle());
				if (orientation == Configuration.ORIENTATION_PORTRAIT) {
					pagerAdapter.notifyDataSetChanged();

				}

				txtvPosition.setText(Converter.getDurationStringLong((media
						.getPosition())));

				if (!playbackService.isShouldStream()) {
					txtvLength.setText(Converter.getDurationStringLong(media
							.getDuration()));
					float progress = ((float) media.getPosition())
							/ media.getDuration();
					sbPosition.setProgress((int) (progress * sbPosition
							.getMax()));
				}
			}
			mediaInfoLoaded = true;
		}
	}

	private void setupGUI() {
		setContentView(R.layout.mediaplayer_activity);
		sbPosition = (SeekBar) findViewById(R.id.sbPosition);
		txtvPosition = (TextView) findViewById(R.id.txtvPosition);
		txtvLength = (TextView) findViewById(R.id.txtvLength);
		butPlay = (ImageButton) findViewById(R.id.butPlay);
		butRev = (ImageButton) findViewById(R.id.butRev);
		butFF = (ImageButton) findViewById(R.id.butFF);

		// SEEKBAR SETUP

		sbPosition.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			int duration;
			float prog;

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				if (fromUser) {
					prog = progress / ((float) seekBar.getMax());
					duration = playbackService.getPlayer().getDuration();
					txtvPosition.setText(Converter
							.getDurationStringLong((int) (prog * duration)));
				}

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// interrupt position Observer, restart later
				if (positionObserver != null) {
					positionObserver.cancel(true);
					positionObserver = null;
				}
			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				playbackService.seek((int) (prog * duration));
				setupPositionObserver();
			}
		});

		// BUTTON SETUP

		butPlay.setOnClickListener(playbuttonListener);

		butFF.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (status == PlayerStatus.PLAYING) {
					playbackService.seekDelta(DEFAULT_SEEK_DELTA);
				}
			}
		});

		butRev.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (status == PlayerStatus.PLAYING) {
					playbackService.seekDelta(-DEFAULT_SEEK_DELTA);
				}
			}
		});

		// PORTRAIT ORIENTATION SETUP

		if (orientation == Configuration.ORIENTATION_PORTRAIT) {
			txtvStatus = (TextView) findViewById(R.id.txtvStatus);
			viewpager = (ViewPager) findViewById(R.id.viewpager);
			tabs = (TabPageIndicator) findViewById(R.id.tabs);

			int tabcount = 2;
			if (media != null && media.getItem().getSimpleChapters() != null) {
				tabcount = 3;
			}
			pagerAdapter = new MediaPlayerPagerAdapter(
					getSupportFragmentManager(), tabcount, this);
			viewpager.setAdapter(pagerAdapter);
			tabs.setViewPager(viewpager);
		} else {
			videoOverlay = (LinearLayout) findViewById(R.id.overlay);
			videoview = (VideoView) findViewById(R.id.videoview);
			videoview.getHolder().addCallback(this);
			videoview.setOnClickListener(playbuttonListener);
			videoview.setOnTouchListener(onVideoviewTouched);
			setupVideoControlsToggler();
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
					WindowManager.LayoutParams.FLAG_FULLSCREEN);
		}
	}

	private OnClickListener playbuttonListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			if (status == PlayerStatus.PLAYING) {
				playbackService.pause(true);
			} else if (status == PlayerStatus.PAUSED
					|| status == PlayerStatus.PREPARED) {
				playbackService.play();
			}
		}
	};

	private View.OnTouchListener onVideoviewTouched = new View.OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				if (videoControlsToggler != null) {
					videoControlsToggler.cancel(true);
				}
				toggleVideoControlsVisibility();
				if (videoControlsShowing) {
					setupVideoControlsToggler();
				}

				return true;
			} else {
				return false;
			}
		}
	};

	@SuppressLint("NewApi")
	private void setupVideoControlsToggler() {
		if (videoControlsToggler != null) {
			videoControlsToggler.cancel(true);
		}
		videoControlsToggler = new VideoControlsHider();
		if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
			videoControlsToggler
					.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		} else {
			videoControlsToggler.execute();
		}
	}

	private void toggleVideoControlsVisibility() {
		if (videoControlsShowing) {
			getSupportActionBar().hide();
			videoOverlay.setVisibility(View.GONE);
		} else {
			getSupportActionBar().show();
			videoOverlay.setVisibility(View.VISIBLE);
		}
		videoControlsShowing = !videoControlsShowing;
	}

	private void handleError(int errorCode) {
		final AlertDialog.Builder errorDialog = new AlertDialog.Builder(this);
		errorDialog.setTitle(R.string.error_label);
		errorDialog
				.setMessage(MediaPlayerError.getErrorString(this, errorCode));
		errorDialog.setNeutralButton("OK",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						finish();
					}
				});
		errorDialog.create().show();
	}

	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			playbackService = ((PlaybackService.LocalBinder) service)
					.getService();

			registerReceiver(statusUpdate, new IntentFilter(
					PlaybackService.ACTION_PLAYER_STATUS_CHANGED));

			registerReceiver(notificationReceiver, new IntentFilter(
					PlaybackService.ACTION_PLAYER_NOTIFICATION));

			queryService();
			if (AppConfig.DEBUG)
				Log.d(TAG, "Connection to Service established");
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			playbackService = null;
			if (AppConfig.DEBUG)
				Log.d(TAG, "Disconnected from Service");

		}
	};

	/**
	 * Called when connection to playback service has been established or
	 * information has to be refreshed
	 */
	private void queryService() {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Querying service info");
		if (playbackService != null) {
			int requestedOrientation;
			status = playbackService.getStatus();
			media = playbackService.getMedia();
			invalidateOptionsMenu();

			if (playbackService.isPlayingVideo()) {
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
				requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
			} else {
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
				requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
			}
			// check if orientation is correct
			if ((requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE && orientation == Configuration.ORIENTATION_LANDSCAPE)
					|| (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT && orientation == Configuration.ORIENTATION_PORTRAIT)) {
				if (AppConfig.DEBUG)
					Log.d(TAG, "Orientation correct");
				setupGUI();
				handleStatus();
			} else {
				if (AppConfig.DEBUG)
					Log.d(TAG,
							"Orientation incorrect, waiting for orientation change");
			}
		} else {
			Log.e(TAG,
					"queryService() was called without an existing connection to playbackservice");
		}
	}

	private BroadcastReceiver statusUpdate = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (AppConfig.DEBUG)
				Log.d(TAG, "Received statusUpdate Intent.");
			status = playbackService.getStatus();
			handleStatus();
		}
	};

	private BroadcastReceiver notificationReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			int type = intent.getIntExtra(
					PlaybackService.EXTRA_NOTIFICATION_TYPE, -1);
			int code = intent.getIntExtra(
					PlaybackService.EXTRA_NOTIFICATION_CODE, -1);
			if (code != -1 && type != -1) {
				switch (type) {
				case PlaybackService.NOTIFICATION_TYPE_ERROR:
					handleError(code);
					break;
				case PlaybackService.NOTIFICATION_TYPE_BUFFER_UPDATE:
					if (sbPosition != null) {
						float progress = ((float) code) / 100;
						sbPosition.setSecondaryProgress((int) progress
								* sbPosition.getMax());
					}
					break;
				case PlaybackService.NOTIFICATION_TYPE_RELOAD:
					if (positionObserver != null) {
						positionObserver.cancel(true);
						positionObserver = null;
					}
					mediaInfoLoaded = false;
					queryService();

					break;
				}

			} else {
				if (AppConfig.DEBUG)
					Log.d(TAG, "Bad arguments. Won't handle intent");
			}

		}

	};

	private boolean holderCreated;

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		holder.setFixedSize(width, height);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		holderCreated = true;
		if (AppConfig.DEBUG)
			Log.d(TAG, "Videoview holder created");
		if (status == PlayerStatus.AWAITING_VIDEO_SURFACE) {
			if (playbackService != null) {
				playbackService.setVideoSurface(holder);
			} else {
				Log.e(TAG,
						"Could'nt attach surface to mediaplayer - reference to service was null");
			}
		}

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		holderCreated = false;
	}

	public static class MediaPlayerPagerAdapter extends
			FragmentStatePagerAdapter {
		private int numItems;
		private MediaplayerActivity activity;

		private SherlockListFragment sCChapterFragment;

		private static final int POS_COVER = 0;
		private static final int POS_DESCR = 1;
		private static final int POS_CHAPTERS = 2;

		public MediaPlayerPagerAdapter(FragmentManager fm, int numItems,
				MediaplayerActivity activity) {
			super(fm);
			this.numItems = numItems;
			this.activity = activity;
		}

		@Override
		public Fragment getItem(int position) {
			if (activity.media != null) {
				switch (position) {
				case POS_COVER:
					activity.coverFragment = CoverFragment
							.newInstance(activity.media.getItem());
					return activity.coverFragment;
				case POS_DESCR:
					activity.descriptionFragment = ItemDescriptionFragment
							.newInstance(activity.media.getItem(), true);
					return activity.descriptionFragment;
				case POS_CHAPTERS:
					sCChapterFragment = new SherlockListFragment() {

						@Override
						public void onListItemClick(ListView l, View v,
								int position, long id) {
							super.onListItemClick(l, v, position, id);
							SimpleChapter chapter = (SimpleChapter) this
									.getListAdapter().getItem(position);
							if (activity.playbackService != null) {
								activity.playbackService.seekToChapter(chapter);
							}
						}

					};

					sCChapterFragment.setListAdapter(new SCListAdapter(
							activity, 0, activity.media.getItem()
									.getSimpleChapters()));
					return sCChapterFragment;
				default:
					return CoverFragment.newInstance(null);
				}
			} else {
				return CoverFragment.newInstance(null);
			}
		}

		@Override
		public CharSequence getPageTitle(int position) {
			switch (position) {
			case POS_COVER:
				return activity.getString(R.string.cover_label);
			case POS_DESCR:
				return activity.getString(R.string.shownotes_label);
			case POS_CHAPTERS:
				return activity.getString(R.string.chapters_label);
			default:
				return super.getPageTitle(position);
			}
		}

		@Override
		public int getCount() {
			return numItems;
		}

		@Override
		public int getItemPosition(Object object) {
			return POSITION_UNCHANGED;
		}

		public void notifyMediaPositionChanged() {
			if (sCChapterFragment != null) {
				ArrayAdapter<SimpleChapter> adapter = (ArrayAdapter<SimpleChapter>) sCChapterFragment
						.getListAdapter();
				adapter.notifyDataSetChanged();
			}
		}

	}

	// ---------------------- ASYNC TASKS

	/** Refreshes the current position of the media file that is playing. */
	public class MediaPositionObserver extends
			AsyncTask<MediaPlayer, Void, Void> {

		private static final String TAG = "MediaPositionObserver";
		private static final int WAITING_INTERVALL = 1000;
		private MediaPlayer player;

		@Override
		protected void onCancelled() {
			if (AppConfig.DEBUG)
				Log.d(TAG, "Task was cancelled");
		}

		@Override
		protected Void doInBackground(MediaPlayer... p) {
			if (AppConfig.DEBUG)
				Log.d(TAG, "Background Task started");
			player = p[0];
			try {
				while (player.isPlaying() && !isCancelled()) {
					try {
						Thread.sleep(WAITING_INTERVALL);
					} catch (InterruptedException e) {
						if (AppConfig.DEBUG)
							Log.d(TAG,
									"Thread was interrupted while waiting. Finishing now");
						return null;
					}
					publishProgress();

				}
			} catch (IllegalStateException e) {
				if (AppConfig.DEBUG)
					Log.d(TAG, "player is in illegal state, exiting now");
			}
			if (AppConfig.DEBUG)
				Log.d(TAG, "Background Task finished");
			return null;
		}
	}

	/** Hides the videocontrols after a certain period of time. */
	public class VideoControlsHider extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onCancelled() {
			videoControlsToggler = null;
		}

		@Override
		protected void onPostExecute(Void result) {
			videoControlsToggler = null;
		}

		private static final int WAITING_INTERVALL = 5000;
		private static final String TAG = "VideoControlsToggler";

		@Override
		protected void onProgressUpdate(Void... values) {
			if (videoControlsShowing) {
				if (AppConfig.DEBUG)
					Log.d(TAG, "Hiding video controls");
				getSupportActionBar().hide();
				videoOverlay.setVisibility(View.GONE);
				videoControlsShowing = false;
			}
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				Thread.sleep(WAITING_INTERVALL);
			} catch (InterruptedException e) {
				return null;
			}
			publishProgress();
			return null;
		}

	}

}