summaryrefslogtreecommitdiff
path: root/src/de/danoeh/antennapod/activity/MediaplayerActivity.java
blob: c55b0685563db02085077541151aa343f752f51b (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
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.res.Configuration;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

import de.danoeh.antennapod.AppConfig;
import de.danoeh.antennapod.PodcastApp;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.dialog.TimeDialog;
import de.danoeh.antennapod.feed.FeedManager;
import de.danoeh.antennapod.feed.FeedMedia;
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;

/**
 * Provides general features which are both needed for playing audio and video
 * files.
 */
public abstract class MediaplayerActivity extends SherlockFragmentActivity
		implements OnSeekBarChangeListener {
	private static final String TAG = "MediaplayerActivity";

	static final int DEFAULT_SEEK_DELTA = 30000;

	/** True if media information was loaded. */
	protected boolean mediaInfoLoaded = false;
	protected PlaybackService playbackService;
	protected MediaPositionObserver positionObserver;
	protected FeedMedia media;
	protected PlayerStatus status;
	protected FeedManager manager;

	protected TextView txtvPosition;
	protected TextView txtvLength;
	protected SeekBar sbPosition;
	protected ImageButton butPlay;
	protected ImageButton butRev;
	protected ImageButton butFF;

	@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();
	}

	@Override
	protected void onPause() {
		super.onPause();
		mediaInfoLoaded = false;
	}

	protected 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();
			}
		}
	};
	protected 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");

		}
	};
	protected BroadcastReceiver statusUpdate = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (AppConfig.DEBUG)
				Log.d(TAG, "Received statusUpdate Intent.");
			if (playbackService != null) {
				status = playbackService.getStatus();
				handleStatus();
			} else {
				Log.w(TAG,
						"Couldn't receive status update: playbackService was null");
			}
		}
	};

	/**
	 * Should be used to switch to another player activity if the mime type is
	 * not the correct one for the current activity.
	 */
	protected abstract void onReloadNotification(int notificationCode);

	/**
	 * Should be used to inform the user that the PlaybackService is currently
	 * buffering.
	 */
	protected abstract void onBufferStart();

	/**
	 * Should be used to hide the view that was showing the 'buffering'-message.
	 */
	protected abstract void onBufferEnd();

	protected 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;
					onReloadNotification(intent.getIntExtra(
							PlaybackService.EXTRA_NOTIFICATION_CODE, -1));
					queryService();

					break;
				case PlaybackService.NOTIFICATION_TYPE_SLEEPTIMER_UPDATE:
					invalidateOptionsMenu();
					break;
				case PlaybackService.NOTIFICATION_TYPE_BUFFER_START:
					onBufferStart();
					break;
				case PlaybackService.NOTIFICATION_TYPE_BUFFER_END:
					onBufferEnd();
					break;
				}

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

		}

	};

	/** Current screen orientation. */
	protected int orientation;

	@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);

		boolean sleepTimerSet = playbackService != null
				&& playbackService.sleepTimerActive();
		boolean sleepTimerNotSet = playbackService != null
				&& !playbackService.sleepTimerActive();
		menu.findItem(R.id.set_sleeptimer_item).setVisible(sleepTimerNotSet);
		menu.findItem(R.id.disable_sleeptimer_item).setVisible(sleepTimerSet);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			startActivity(new Intent(MediaplayerActivity.this,
					MainActivity.class));
			break;
		case R.id.disable_sleeptimer_item:
			if (playbackService != null) {
				AlertDialog.Builder stDialog = new AlertDialog.Builder(this);
				stDialog.setTitle(R.string.sleep_timer_label);
				stDialog.setMessage(getString(R.string.time_left_label)
						+ Converter.getDurationStringLong((int) playbackService
								.getSleepTimerTimeLeft()));
				stDialog.setPositiveButton(R.string.disable_sleeptimer_label,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
								if (playbackService != null) {
									playbackService.disableSleepTimer();
								}
							}
						});
				stDialog.setNegativeButton(R.string.cancel_label,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
				stDialog.create().show();
			}
			break;
		case R.id.set_sleeptimer_item:
			if (playbackService != null) {
				TimeDialog td = new TimeDialog(this,
						R.string.set_sleeptimer_label,
						R.string.set_sleeptimer_label) {

					@Override
					public void onTimeEntered(long millis) {
						if (playbackService != null) {
							playbackService.setSleepTimer(millis);
						}
					}
				};
				td.show();
				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);
		// ignore orientation change

	}

	/**
	 * Tries to establish a connection to the PlaybackService. If it isn't
	 * running, the PlaybackService will be started with the last played media
	 * as the arguments of the launch intent.
	 */
	protected 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);
	}

	/**
	 * Is called whenever the PlaybackService changes it's status. This method
	 * should be used to update the GUI or start/cancel AsyncTasks.
	 */
	private void handleStatus() {
		switch (status) {

		case ERROR:
			postStatusMsg(R.string.player_error_msg);
			break;
		case PAUSED:
			postStatusMsg(R.string.player_paused_msg);
			loadMediaInfo();
			if (positionObserver != null) {
				positionObserver.cancel(true);
				positionObserver = null;
			}
			butPlay.setImageResource(R.drawable.av_play);
			break;
		case PLAYING:
			clearStatusMsg();
			loadMediaInfo();
			setupPositionObserver();
			butPlay.setImageResource(R.drawable.av_pause);
			break;
		case PREPARING:
			postStatusMsg(R.string.player_preparing_msg);
			loadMediaInfo();
			break;
		case STOPPED:
			postStatusMsg(R.string.player_stopped_msg);
			break;
		case PREPARED:
			loadMediaInfo();
			postStatusMsg(R.string.player_ready_msg);
			butPlay.setImageResource(R.drawable.av_play);
			break;
		case SEEKING:
			postStatusMsg(R.string.player_seeking_msg);
			break;
		case AWAITING_VIDEO_SURFACE:
			onAwaitingVideoSurface();
			break;
		}
	}

	/**
	 * Called by 'handleStatus()' when the PlaybackService is in the
	 * AWAITING_VIDEO_SURFACE state.
	 */
	protected abstract void onAwaitingVideoSurface();

	protected abstract void postStatusMsg(int resId);

	protected abstract void clearStatusMsg();

	protected void onPositionObserverUpdate() {
		int currentPosition = playbackService.getPlayer().getCurrentPosition();
		media.setPosition(currentPosition);
		txtvPosition.setText(Converter.getDurationStringLong(currentPosition));
		txtvLength.setText(Converter.getDurationStringLong(playbackService
				.getPlayer().getDuration()));
		updateProgressbarPosition();
	}

	@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();
					onPositionObserverUpdate();
				}

			};
			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()));
	}

	/**
	 * Load information about the media that is going to be played or currently
	 * being played. This method will be called when the activity is connected
	 * to the PlaybackService to ensure that the activity has the right
	 * FeedMedia object.
	 */
	protected 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());
				txtvPosition.setText(Converter.getDurationStringLong((media
						.getPosition())));

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

	protected 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(this);

		// 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);
				}
			}
		});
	}

	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();
	}

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

			setupGUI();
			handleStatus();

		} else {
			Log.e(TAG,
					"queryService() was called without an existing connection to playbackservice");
		}
	}

	/** 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;
		}
	}

	// OnSeekbarChangeListener
	private int duration;
	private float prog;

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		if (fromUser && PlaybackService.isRunning) {
			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) {
		if (PlaybackService.isRunning) {
			playbackService.seek((int) (prog * duration));
			setupPositionObserver();
		}
	}

}