summaryrefslogtreecommitdiff
path: root/src/de/danoeh/antennapod/activity/MediaplayerActivity.java
blob: eb2fb028a0228fb5a3d56ba52ac91145973078f7 (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
package de.danoeh.antennapod.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import de.danoeh.antennapod.AppConfig;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.asynctask.FlattrClickWorker;
import de.danoeh.antennapod.dialog.TimeDialog;
import de.danoeh.antennapod.preferences.UserPreferences;
import de.danoeh.antennapod.service.playback.PlaybackService;
import de.danoeh.antennapod.util.Converter;
import de.danoeh.antennapod.util.ShareUtils;
import de.danoeh.antennapod.util.StorageUtils;
import de.danoeh.antennapod.util.playback.MediaPlayerError;
import de.danoeh.antennapod.util.playback.Playable;
import de.danoeh.antennapod.util.playback.PlaybackController;

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

	protected PlaybackController controller;

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

	private PlaybackController newPlaybackController() {
		return new PlaybackController(this, false) {

			@Override
			public void setupGUI() {
				MediaplayerActivity.this.setupGUI();
			}

			@Override
			public void onPositionObserverUpdate() {
				MediaplayerActivity.this.onPositionObserverUpdate();
			}

			@Override
			public void onBufferStart() {
				MediaplayerActivity.this.onBufferStart();
			}

			@Override
			public void onBufferEnd() {
				MediaplayerActivity.this.onBufferEnd();
			}

			@Override
			public void onBufferUpdate(float progress) {
				MediaplayerActivity.this.onBufferUpdate(progress);
			}

			@Override
			public void handleError(int code) {
				MediaplayerActivity.this.handleError(code);
			}

			@Override
			public void onReloadNotification(int code) {
				MediaplayerActivity.this.onReloadNotification(code);
			}

			@Override
			public void onSleepTimerUpdate() {
				supportInvalidateOptionsMenu();
			}

			@Override
			public ImageButton getPlayButton() {
				return butPlay;
			}

			@Override
			public void postStatusMsg(int msg) {
				MediaplayerActivity.this.postStatusMsg(msg);
			}

			@Override
			public void clearStatusMsg() {
				MediaplayerActivity.this.clearStatusMsg();
			}

			@Override
			public void loadMediaInfo() {
				MediaplayerActivity.this.loadMediaInfo();
			}

			@Override
			public void onAwaitingVideoSurface() {
				MediaplayerActivity.this.onAwaitingVideoSurface();
			}

			@Override
			public void onServiceQueried() {
				MediaplayerActivity.this.onServiceQueried();
			}

			@Override
			public void onShutdownNotification() {
				finish();
			}

			@Override
			public void onPlaybackEnd() {
				finish();
			}

			@Override
			public void onPlaybackSpeedChange() {
				MediaplayerActivity.this.onPlaybackSpeedChange();
			}
		};

	}

	protected void onPlaybackSpeedChange() {

	}

	protected void onServiceQueried() {
		supportInvalidateOptionsMenu();
	}

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

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

	@Override
	protected void onPause() {
		super.onPause();
		controller.reinitServiceIfPaused();
		controller.pause();
	}

	/**
	 * 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 void onBufferUpdate(float progress) {
		if (sbPosition != null) {
			sbPosition.setSecondaryProgress((int) progress
					* sbPosition.getMax());
		}
	}

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

	@Override
	protected void onStart() {
		super.onStart();
		if (controller != null) {
			controller.release();
		}
		controller = newPlaybackController();
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (AppConfig.DEBUG)
			Log.d(TAG, "Activity stopped");
		if (controller != null) {
			controller.release();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (AppConfig.DEBUG)
			Log.d(TAG, "Activity destroyed");
	}

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

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
		Playable media = controller.getMedia();

		menu.findItem(R.id.support_item).setVisible(
				media != null && media.getPaymentLink() != null);
		menu.findItem(R.id.share_link_item).setVisible(
				media != null && media.getWebsiteLink() != null);
		menu.findItem(R.id.visit_website_item).setVisible(
				media != null && media.getWebsiteLink() != null);
		menu.findItem(R.id.skip_episode_item).setVisible(media != null);
		boolean sleepTimerSet = controller.sleepTimerActive();
		boolean sleepTimerNotSet = controller.sleepTimerNotActive();
		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) {
		Playable media = controller.getMedia();
		if (item.getItemId() == android.R.id.home) {
			Intent intent = new Intent(MediaplayerActivity.this,
					MainActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
			return true;
		} else if (media != null) {
			switch (item.getItemId()) {
			case R.id.disable_sleeptimer_item:
				if (controller.serviceAvailable()) {
					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) controller
									.getSleepTimerTimeLeft()));
					stDialog.setPositiveButton(
							R.string.disable_sleeptimer_label,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
									controller.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 (controller.serviceAvailable()) {
					TimeDialog td = new TimeDialog(this,
							R.string.set_sleeptimer_label,
							R.string.set_sleeptimer_label) {

						@Override
						public void onTimeEntered(long millis) {
							controller.setSleepTimer(millis);
						}
					};
					td.show();
					break;

				}
			case R.id.visit_website_item:
				Uri uri = Uri.parse(media.getWebsiteLink());
				startActivity(new Intent(Intent.ACTION_VIEW, uri));
				break;
			case R.id.support_item:
				new FlattrClickWorker(this, media.getPaymentLink())
						.executeAsync();
				break;
			case R.id.share_link_item:
				ShareUtils.shareLink(this, media.getWebsiteLink());
				break;
			case R.id.skip_episode_item:
				sendBroadcast(new Intent(
						PlaybackService.ACTION_SKIP_CURRENT_EPISODE));
				break;
			default:
				return false;

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

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

	/**
	 * 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() {
		if (controller != null) {
			int currentPosition = controller.getPosition();
			int duration = controller.getDuration();
			if (currentPosition != PlaybackService.INVALID_TIME
					&& duration != PlaybackService.INVALID_TIME
					&& controller.getMedia() != null) {
				controller.getMedia().setPosition(currentPosition);
				txtvPosition.setText(Converter
						.getDurationStringLong(currentPosition));
				txtvLength.setText(Converter.getDurationStringLong(duration));
				updateProgressbarPosition(currentPosition, duration);
			} else {
				Log.w(TAG,
						"Could not react to position observer update because of invalid time");
			}
		}
	}

	private void updateProgressbarPosition(int position, int duration) {
		if (AppConfig.DEBUG)
			Log.d(TAG, "Updating progressbar info");
		float progress = ((float) position) / duration;
		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 (AppConfig.DEBUG)
			Log.d(TAG, "Loading media info");
		Playable media = controller.getMedia();
		if (media != null) {
			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()));
			}
		}
	}

	protected void setupGUI() {
		setContentView(getContentViewResourceId());
		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(controller.newOnPlayButtonClickListener());

		butFF.setOnClickListener(controller.newOnFFButtonClickListener());

		butRev.setOnClickListener(controller.newOnRevButtonClickListener());

	}

	protected abstract int getContentViewResourceId();

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

	float prog;

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		prog = controller.onSeekBarProgressChanged(seekBar, progress, fromUser,
				txtvPosition);
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		controller.onSeekBarStartTrackingTouch(seekBar);
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		controller.onSeekBarStopTrackingTouch(seekBar, prog);
	}

}