Skip to content

Instantly share code, notes, and snippets.

@barbosa-renan
Created October 6, 2015 21:26
Show Gist options
  • Save barbosa-renan/f5f7d51220cada69583a to your computer and use it in GitHub Desktop.
Save barbosa-renan/f5f7d51220cada69583a to your computer and use it in GitHub Desktop.
package com.prologica.wizardplayer;
import java.io.File;
import java.util.concurrent.TimeUnit;
import com.prologica.wizardplayer.common.BundleKeys;
import com.prologica.wizardplayer.common.PreferencesKeys;
import com.prologica.wizardplayer.common.TagNames;
import com.prologica.wizardplayer.common.Utils;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class VideoActivity extends Activity
{
static View frame1;
static VideoPlayer textureView;
static TextView textProgress;
static boolean pause = false;
static Activity _activity;
private static Thread th;
private static String _videoURL;
PlaceholderFragment _placeHolderFragment;
private int currentApiVersion;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
EsconderBarraNavegacao();
_activity = this;
th = Thread.currentThread();
// URL DO VÍDEO
Bundle extras = getIntent().getExtras();
if (extras != null)
_videoURL = extras.getString(BundleKeys.CAMINHO_ARQUIVO);
if (savedInstanceState == null)
{
_placeHolderFragment = new PlaceholderFragment();
getFragmentManager().beginTransaction()
.add(R.id.container, _placeHolderFragment).commit();
}
}
private void EsconderBarraNavegacao()
{
currentApiVersion = android.os.Build.VERSION.SDK_INT;
final int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
// This work only for android 4.4+
if(currentApiVersion >= Build.VERSION_CODES.KITKAT)
{
getWindow().getDecorView().setSystemUiVisibility(flags);
// Code below is to handle presses of Volume up or Volume down.
// Without this, after pressing volume buttons, the navigation bar will
// show up and won't hide
final View decorView = getWindow().getDecorView();
decorView
.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener()
{
@Override
public void onSystemUiVisibilityChange(int visibility)
{
if((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0)
{
decorView.setSystemUiVisibility(flags);
}
}
});
}
else if(currentApiVersion >= Build.VERSION_CODES.JELLY_BEAN)
{
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);
if(currentApiVersion >= Build.VERSION_CODES.KITKAT && hasFocus)
{
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
@Override
protected void onDestroy()
{
Log.w(TagNames.TagVideoActivity, "onDestroy()");
pause = false;
super.onDestroy();
}
@Override
public void onPause()
{
Log.w(TagNames.TagVideoActivity, "onPause()");
pause = true;
super.onPause();
}
@Override
public void onResume()
{
if (textureView != null)
{
textureView.setDisplay();
}
EsconderBarraNavegacao();
super.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_settings)
{
System.gc();
System.exit(0);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
try
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && _placeHolderFragment != null)
{
super.onBackPressed();
_placeHolderFragment.onBackPressed();
}
}
catch (Exception ex)
{
// GRAVAR EM ARQUIVO DE LOG
Utils.AppendLog(TagNames.TagVideoActivity + " " +
"[ERRO] onKeyDown(): " + ex.getMessage(),
getApplicationContext());
}
return super.onKeyDown(keyCode, event);
}
/**
* Fragment para exibir o vídeo
* @author Renan Barbosa
*/
public static class PlaceholderFragment extends Fragment
{
// WIDGETS
private Button btnPlay, btnPause, btnForward, btnBackward, btnVolumeDown, btnVolumeUp, btnVoltar;
private TextView tvVolumeInfo;
private TextView tvTempoExecucao, tvTempoTotal;
private SeekBar seekbar;
// VARIÁVEIS
private int _forwardTime = 5000, _backwardTime = 5000;
private int _volumeMaximo = 0, _volumeAtual = 0;
private double startTime = 0, finalTime = 0;
public static int oneTimeOnly = 0;
// CLASSES
private AudioManager _audioManager = null;
private SharedPreferences _preferencias;
private Handler myHandler = new Handler();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_video, container, false);
InicializeControls(rootView);
BindPreferencias();
InicializeListeners();
return rootView;
}
private void InicializeControls(View rootView)
{
frame1 = rootView.findViewById(R.id.frame1);
textureView = (VideoPlayer) rootView.findViewById(R.id.textureView1);
if(textureView != null)
textureView.release();
textProgress = (TextView) rootView.findViewById(R.id.textView1);
textureView.setVideoPath(_videoURL);
textureView.openVideo();
textureView.requestLayout();
textureView.invalidate();
// BOTOES
btnPlay = (Button) rootView.findViewById(R.id.btnPlay);
btnPause = (Button) rootView.findViewById(R.id.btnPause);
btnForward = (Button) rootView.findViewById(R.id.btnFoward);
btnBackward = (Button) rootView.findViewById(R.id.btnBackward);
btnVolumeDown = (Button) rootView.findViewById(R.id.btnVolumeDown);
btnVolumeUp = (Button) rootView.findViewById(R.id.btnVolumeUp);
btnVoltar = (Button) rootView.findViewById(R.id.btnVoltar);
// TEXT VIEWS
tvTempoExecucao = (TextView) rootView.findViewById(R.id.tvTempoExecucao);
tvTempoTotal = (TextView) rootView.findViewById(R.id.tvTempoTotal);
tvVolumeInfo = (TextView) rootView.findViewById(R.id.tvVolumeInfo);
// SEEKBAR
seekbar = (SeekBar)rootView.findViewById(R.id.seekBar);
seekbar.setClickable(true);
btnPause.setEnabled(false);
// AUDIO MANAGER E CONTROLES DE VOLUME
_audioManager = (AudioManager) _activity.getSystemService(_activity.AUDIO_SERVICE);
_volumeMaximo = _audioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);
_volumeAtual = _audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);
tvVolumeInfo.setText(String.valueOf(_volumeAtual));
}
private void InicializeListeners()
{
btnPlay.setOnClickListener(PlayClickListener);
// PAUSAR PLAYER
btnPause.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
textureView.pause();
btnPause.setEnabled(false);
btnPlay.setEnabled(true);
}
});
btnForward.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
int temp = (int)startTime;
if((temp + _forwardTime) <= finalTime)
{
startTime = startTime + _forwardTime;
textureView.seekTo((int) startTime);
}
}
});
btnBackward.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
int temp = (int)startTime;
if((temp - _backwardTime ) > 0)
{
startTime = startTime - _backwardTime;
textureView.seekTo((int) startTime);
}
}
});
btnVolumeDown.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
try
{
int volumeDown = _volumeAtual;
volumeDown --;
if(volumeDown >= 0)
{
_audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, volumeDown, AudioManager.FLAG_PLAY_SOUND);
_volumeAtual = volumeDown;
tvVolumeInfo.setText(String.valueOf(_volumeAtual));
}
}
catch(Exception ex)
{
// GRAVAR EM ARQUIVO DE LOG
Utils.AppendLog(TagNames.TagVideoActivity + " " +
"[ERRO] btnVolumeDown.setOnClickListener(): " + ex.getMessage(),
_activity);
}
}
});
btnVolumeUp.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
try
{
int volumeUp = _volumeAtual;
volumeUp ++;
if(volumeUp <= _volumeMaximo)
{
_audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, volumeUp, AudioManager.FLAG_PLAY_SOUND);
_volumeAtual = volumeUp;
tvVolumeInfo.setText(String.valueOf(_volumeAtual));
}
}
catch(Exception ex)
{
//TODO: Gravar em log
Log.e(TagNames.TagVideoActivity, "" + ex.getMessage());
// GRAVAR EM ARQUIVO DE LOG
Utils.AppendLog(TagNames.TagVideoActivity + " " +
"[ERRO] btnVolumeUp.setOnClickListener(): " + ex.getMessage(),
_activity);
}
}
});
btnVoltar.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
onBackPressed();
_activity.onBackPressed();
}
});
// CONTROLAR EVENTOS DO SEEKBAR
seekbar.setOnSeekBarChangeListener(mOnSeekBarChangeListener);
}
private OnClickListener PlayClickListener = new View.OnClickListener()
{
@Override
public void onClick(View v)
{
textureView.start();
finalTime = textureView.getDuration();
startTime = textureView.getCurrentPosition();
if (oneTimeOnly == 0)
{
seekbar.setMax((int) finalTime);
oneTimeOnly = 1;
}
tvTempoTotal.setText(Utils.FormatarTempo((int)TimeUnit.MILLISECONDS.toSeconds((long)finalTime)));
tvTempoExecucao.setText(Utils.FormatarTempo((int)TimeUnit.MILLISECONDS.toSeconds((long)startTime)));
seekbar.setProgress((int)startTime);
myHandler.postDelayed(UpdateVideoTime, 100);
btnPause.setEnabled(true);
btnPlay.setEnabled(false);
}
};
private OnSeekBarChangeListener mOnSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener()
{
@Override
public void onStopTrackingTouch(SeekBar seekBar)
{
// TODO Auto-generated method stub
}
@Override
public void onStartTrackingTouch(SeekBar seekBar)
{
// TODO Auto-generated method stub
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
if(textureView != null && fromUser)
textureView.seekTo(progress);
}
};
/**
* Thread para atualizar o SeekBar com o tempo de execução do audio
*/
private Runnable UpdateVideoTime = new Runnable()
{
public void run()
{
startTime = textureView.getCurrentPosition();
tvTempoExecucao.setText(Utils.FormatarTempo((int)TimeUnit.MILLISECONDS.toSeconds((long)startTime)));
Log.w("Runnable", "StartTime" + startTime);
seekbar.setProgress((int)startTime);
myHandler.postDelayed(this, 100);
}
};
public class mediac extends MediaController
{
public mediac(Context context, View anchor)
{
super(context);
super.setAnchorView(anchor);
}
@Override
public void setAnchorView(View view)
{}
}
private void DeletarArquivoTemporario(String videoURL)
{
try
{
Boolean isDeletarArquivo = _preferencias.getBoolean(PreferencesKeys.PrefKeyDescriptografarArquivo, false)
&& !videoURL.contains("ENGLISH SERIE W");
if(isDeletarArquivo)
{
File file = new File(videoURL);
file.delete();
}
} catch (Exception ex)
{
// GRAVAR EM ARQUIVO DE LOG
Utils.AppendLog(TagNames.TagVideoActivity + " " +
"[ERRO] DeletarArquivoTemporario(): " + ex.getMessage(),
_activity);
return;
}
}
/**
* Restaura as preferencias gravadas
*/
private void BindPreferencias()
{
try
{
_preferencias = _activity.getSharedPreferences(PreferencesKeys.PrefConfigs, 0);
if(_preferencias != null)
{
// RECUPERAR VALOR, CASO NÃO ESTEJA CONFIGURADO É ATRIBUÍDO O TEMPO DE 5 SEGUNDOS
int tempoAvancoRetrocesso = Integer.parseInt(_preferencias.getString(PreferencesKeys.PrefKeyVideoTempo, "5"));
// PASSAR DE SEGUNDOS PARA MILISEGUNDOS
tempoAvancoRetrocesso *= 1000;
// ATRIBUIR AOS FIELDS DE AVANÇO E RETROCESSO
_forwardTime = tempoAvancoRetrocesso;
_backwardTime = tempoAvancoRetrocesso;
}
}
catch(Exception ex)
{
// GRAVAR EM ARQUIVO DE LOG
Utils.AppendLog(TagNames.TagVideoActivity + " " +
"[ERRO] BindPreferencias(): " + ex.getMessage(),
_activity);
}
}
@Override
public void onPause()
{
super.onPause();
textureView.pause();
btnPause.setEnabled(false);
btnPlay.setEnabled(true);
}
@Override
public void onStop()
{
super.onStop();
}
@Override
public void onDestroy()
{
super.onDestroy();
frame1 = null;
textureView = null;
textProgress = null;
DeletarArquivoTemporario(_videoURL);
}
public void onBackPressed()
{
textureView.stop();
textureView.reset();
myHandler.removeCallbacks(UpdateVideoTime);
seekbar = null;
oneTimeOnly = 0;
DeletarArquivoTemporario(_videoURL);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment