I was developing an app to show videos. A BroadCastReceiver receives a AC_PPWER_CONNECTED an starts the VideoViewActivity. I can hear the sound of the Video, but the screen is off, either i want to turn it on with a wahe lock.
Following Code doesn't work.
package org.adem.activities;
import java.util.ArrayList;
import org.adem.R;
import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
public class VideoViewActivity extends Activity implements
OnBufferingUpdateListener, OnCompletionListener,
OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback {
private static final String TAG = VideoViewActivity.class.getSimpleName();
private int mVideoWidth;
private int mVideoHeight;
private MediaPlayer mMediaPlayer;
private SurfaceView mPreview;
private SurfaceHolder holder;
private Bundle extras;
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
private ArrayList<String> pathList;
private int videoQueueSize;
private int currentPosition;
PowerManager.WakeLock wl;
KeyguardLock lock;
/**
*
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.player);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, TAG);
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE);
lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();
mPreview = (SurfaceView) findViewById(R.id.surfaceView);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
extras = getIntent().getExtras();
}
private void playVideo() {
if ("".equals(pathList.get(currentPosition))) {
// Tell the user to provide a media file URL.
Toast.makeText(
VideoViewActivity.this,
"Please edit MediaPlayerDemo_Video Activity, "
+ "and set the path variable to your media file path."
+ " Your media file must be stored on sdcard.",
Toast.LENGTH_LONG).show();
return;
} else {
try {
// Create a new media player and set the listeners
releaseMediaPlayer();
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.setDataSource(pathList.get(currentPosition));
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepare();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
}
}
}
public void onBufferingUpdate(MediaPlayer arg0, int percent) {
Log.d(TAG, "onBufferingUpdate percent:" + percent);
}
public void onCompletion(MediaPlayer arg0) {
if (currentPosition >= videoQueueSize) {
Toast.makeText(VideoViewActivity.this, "Video Playback finished", Toast.LENGTH_LONG).show();
this.finish();
} else {
playVideo();
currentPosition++;
}
Log.d(TAG, "onCompletion called");
}
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.v(TAG, "onVideoSizeChanged called");
if (width == 0 || height == 0) {
Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
return;
}
mIsVideoSizeKnown = true;
mVideoWidth = width;
mVideoHeight = height;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void onPrepared(MediaPlayer mediaplayer) {
Log.d(TAG, "onPrepared called");
mIsVideoReadyToBePlayed = true;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
Log.d(TAG, "surfaceChanged called");
}
public void surfaceDestroyed(SurfaceHolder surfaceholder) {
Log.d(TAG, "surfaceDestroyed called");
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated called");
pathList = extras.getStringArrayList("Path");
currentPosition = 0;
videoQueueSize = pathList.size();
if (!wl.isHeld()) {
Log.d(TAG, "surfaceCreated - wl.acquire()");
wl.acquire();
}
playVideo();
Log.d(TAG, pathList.get(currentPosition));
currentPosition++;
}
#Override
protected void onPause() {
super.onPause();
releaseMediaPlayer();
doCleanUp();
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
doCleanUp();
}
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
private void doCleanUp() {
mVideoWidth = 0;
mVideoHeight = 0;
mIsVideoReadyToBePlayed = false;
mIsVideoSizeKnown = false;
if (wl.isHeld()) {
Log.d(TAG, "doCleanUp - wl.release()");
wl.release();
}
}
private void startVideoPlayback() {
Log.v(TAG, "startVideoPlayback");
holder.setFixedSize(mVideoWidth, mVideoHeight);
mMediaPlayer.start();
}
}
What is wron with the wake lock command. What i'm wondering is, that the screen turns on when wl.release was called at the ent of the of the doCleanUp method.
Thanks for help
Try this below Snippet :
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP, "WakeClock");
Related
I have a small project. I need to implement a motion detection in android to close the device screen when more than 5 mins have passed, and wake it up if motion is detected.
The problem is that the camera preview freezes when the device is going to sleep, and doesn't send any more previews to the activity, so the application is stuck with the screen turned off.
I tried with wake locks but it doesn't work. It still makes the app call onPause, onStop.
My camera service:
import android.annotation.TargetApi;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.camera2.*;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class CameraHandler extends Service {
private static final String TAG = "CameraHandler";
private static final String START_SERVICE_COMMAND = "startServiceCommands";
private static final int COMMAND_NONE = -1;
private static final int COMMAND_START_RECORDING = 0;
private Context context;
private Camera camera;
private boolean inPreview;
private AtomicReference<byte[]> nextData = new AtomicReference<>();
private AtomicInteger nextWidth = new AtomicInteger();
private AtomicInteger nextHeight = new AtomicInteger();
private IBinder cameraServiceBinder = new CameraServiceBinder();
private Camera.PreviewCallback previewCallback;
//private SurfaceHolder.Callback surfaceCallback;
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CameraHandler() {
}
public static void starService(Context context){
Intent intent = new Intent(context, CameraHandler.class);
intent.putExtra(START_SERVICE_COMMAND, COMMAND_START_RECORDING);
context.startService(intent);
}
private void setPreviewHolder() {
// previewHolder = this.surfaceView.getHolder();
//previewHolder.addCallback(surfaceCallback);
//previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// surfaceCallback.surfaceCreated(previewHolder);
//surfaceCallback.surfaceChanged(previewHolder, 0, 0, 0);
Log.i(TAG, "Surface was set");
}
public AtomicReference<byte[]> getNextData() {
return nextData;
}
public AtomicInteger getNextWidth() {
return nextWidth;
}
public AtomicInteger getNextHeight() {
return nextHeight;
}
private boolean checkCameraHardware() {
// if this device has a camera or not
return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
public void releaseCamera(){
//if (previewHolder != null) {
// previewHolder.removeCallback(surfaceCallback);
// }
if (camera != null){
camera.setPreviewCallback(null);
if (inPreview) camera.stopPreview();
inPreview = false;
camera.release(); // release the camera for other applications
camera = null;
Log.i(TAG, "Released camera");
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null) {
throw new IllegalStateException("Must start the service with intent");
}
switch (intent.getIntExtra(START_SERVICE_COMMAND, COMMAND_NONE)) {
case COMMAND_START_RECORDING:
initialize();
break;
default:
throw new UnsupportedOperationException("Cannot start service with illegal commands");
}
return START_NOT_STICKY;
}
private void initialize(){
camera = initializeCameraInstance();
previewCallback = createCameraPreviewCallback();
setPreviewHolder();
if (camera != null) {
SurfaceView sv = new SurfaceView(this);
Log.i(TAG, "aci is still null!");
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(1, 1,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
SurfaceHolder sh = sv.getHolder();
sh.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
sv.setZOrderOnTop(true);
sh.setFormat(PixelFormat.TRANSPARENT);
sh.addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
Camera.Parameters params = camera.getParameters();
camera.setParameters(params);
Camera.Parameters parameters = camera.getParameters();
Camera.Size size = getWorstPreviewSize(parameters);
if (size != null) {
parameters.setPreviewSize(size.width, size.height);
Log.d(TAG, "Using width=" + size.width + " height=" + size.height);
}
camera.setParameters(parameters);
try {
camera.setPreviewDisplay(holder);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
camera.setPreviewCallback(previewCallback);
camera.startPreview();
//mCamera.unlock();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
});
wm.addView(sv, params);
}
}
private Camera initializeCameraInstance() {
/*if (this.camera != null) {
releaseCamera();
}*/
Camera camera = null;
try {
if (Camera.getNumberOfCameras() > 1) {
//if you want to open front facing camera use this line
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
} else {
camera = Camera.open();
}
}
catch (Exception e){
// Camera is not available (in use or does not exist)
Log.i(TAG, "Kamera nicht zur Benutzung freigegeben");
}
return camera; // returns null if camera is unavailable
}
private void consumeData(byte[] data, int width, int height) {
nextData.set(data);
nextWidth.set(width);
nextHeight.set(height);
}
private Camera.PreviewCallback createCameraPreviewCallback() {
return new Camera.PreviewCallback() {
#Override
public void onPreviewFrame(byte[] data, Camera camera) {
Log.i(TAG, "-----Preview frame received-----");
if (data == null) return;
Camera.Size size = camera.getParameters().getPreviewSize();
if (size == null) return;
consumeData(data, size.width, size.height);
}
};
}
private static Camera.Size getWorstPreviewSize(Camera.Parameters parameters) {
Camera.Size result = null;
int width = Integer.MAX_VALUE;
int height = Integer.MAX_VALUE;
for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
if (size.width <= width && size.height <= height) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea < resultArea) result = size;
}
}
}
return result;
}
private static Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
if (size.width <= width && size.height <= height) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea > resultArea) result = size;
}
}
}
return result;
}
public class CameraServiceBinder extends Binder {
public CameraHandler getService() {
return CameraHandler.this;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return cameraServiceBinder;
}
}
My Activity:
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.SurfaceView;
import android.widget.TextView;
import android.util.Log;
public class MotionDetectorActivity extends Activity {
private static final String TAG = "MotionDetectorActivity";
//private SurfaceView surfaceView;
private TextView txtStatus;
private MotionDetectorService motionDetectorService;
private boolean serviceBounded = false;
private ServiceConnection serviceConnection = createServiceConnection();
// private CameraHandler cameraHandler;
private AndroidScreenManager screenManager;
private long lastMotion;
PowerManager.WakeLock partialWakeLock;
private void createWakeLocks() {
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
//fullWakeLock = powerManager.newWakeLock(/*PowerManager.PARTIAL_WAKE_LOCK | */PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK,
// "MotionDetectorActivity::FullWakelockTag");
partialWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK,
"MotionDetectorActivity::PartialWakelockTag");
}
private ServiceConnection createServiceConnection() {
return new ServiceConnection() {
public void onServiceConnected(ComponentName cName, IBinder serviceBinder) {
Log.i(TAG, "Service is getting connected");
MotionDetectorServiceBinder binder = (MotionDetectorServiceBinder) serviceBinder;
MotionDetectorActivity.this.motionDetectorService = binder.getService();
serviceBounded = true;
//motionDetectorService.setCameraHandler(cameraHandler);
motionDetectorService.setMotionDetectorCallback(new IMotionDetectorCallback() {
#Override
public void onMotionDetected() {
Log.v(TAG, "Motion detected");
txtStatus.setText("Motion detected");
lastMotion = System.currentTimeMillis();
if (!screenManager.isScreenOn()) {
Log.v(TAG, "Screen is turned off so waking it up");
screenManager.turnOn();
if (partialWakeLock.isHeld()) {
partialWakeLock.release();
}
}
/*if (!fullWakeLock.isHeld()) {
fullWakeLock.acquire();
}*/
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
txtStatus.setText("No motion detected");
/*if (fullWakeLock.isHeld()) {
fullWakeLock.release();
}*/
}
}, 750);
}
#Override
public void onNoMotionDetected() {
long now = System.currentTimeMillis();
if (now - lastMotion > 5*1000) {
Log.i(TAG, "No motion for more than 5 seconds, turning screen off");
//screenManager.turnOff();
}
}
#Override
public void onTooDark() {
Log.v(TAG, "Too dark here");
txtStatus.setText("Too dark here");
}
});
// Custom config options
motionDetectorService.setCheckIntervalMs(500);
motionDetectorService.setLeniency(30);
motionDetectorService.setMinLuma(500);
}
public void onServiceDisconnected(ComponentName cName){
serviceBounded = false;
}
};
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
screenManager = new AndroidScreenManager(this);
CameraHandler.starService(this);
createWakeLocks();
txtStatus = (TextView) findViewById(R.id.txtStatus);
lastMotion = System.currentTimeMillis();
}
#Override
protected void onStart() {
super.onStart();
Intent motionDetectorServiceIntent = new Intent(this, MotionDetectorService.class);
bindService(motionDetectorServiceIntent, serviceConnection, BIND_AUTO_CREATE);
startService(motionDetectorServiceIntent);
}
#Override
protected void onResume() {
Log.i(TAG, "-----onResume-----");
super.onResume();
/*if (motionDetectorService != null) {
motionDetectorService.releasePartialWakeLocK();
}
if (partialWakeLock.isHeld()) {
partialWakeLock.release();
Log.v(TAG, "Released partial wake lock in the activity");
}*/
}
private void acquirePartialWakeLock() {
if (!partialWakeLock.isHeld()) {
partialWakeLock.acquire();
Log.v(TAG, "Acquired partial wake lock in the activity");
}
}
#Override
protected void onPause() {
Log.i(TAG, "-----onPause-----");
//CameraHandler cameraHandler = new CameraHandler(this, surfaceView);
/*motionDetectorService.acquirePartialWakeLocK();*/
//acquirePartialWakeLock();
super.onPause();
}
private void unbindServiceIfBounded() {
if (serviceBounded) {
unbindService(serviceConnection);
serviceBounded = false;
Log.i(TAG, "Service is unbounded");
}
}
#Override
protected void onDestroy() {
Log.v(TAG, "Destroying app");
motionDetectorService.onDestroy();
unbindServiceIfBounded();
super.onDestroy();
}
#Override
protected void onStop() {
Log.i(TAG, "-----onStop-----");
//cameraHandler.releaseCamera();
//CameraHandler cameraHandler = new CameraHandler(this, surfaceView);
//acquirePartialWakeLock();
//unbindServiceIfBounded();
super.onStop();
}
}
I have been streaming videos on my Android App that are on Server But I want to Stream videos that are currently running on the TV
channels as live.
If there is any way i can run live videos of TV channels into my Android App, please guide me.
I have used this URL http://blindy.tv/all.m3u to stream video but when it runs I got error, that This video can not be played.
I think this URL is fine, but my application is not able to play videos, like fetch video and then play continuously as this url is
streaming videos.
I have an assignment to show videos of a TV channel into Android App.
How can i show it.?
My Code is Following that is working fine for some video that is placed on server. but i want my code to work to display live tv
channels streaming in my android app. How can i do this as to cover my
Assignment ???
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
public class Main5Activity extends AppCompatActivity implements MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnVideoSizeChangedListener, SurfaceHolder.Callback {
private static final String TAG = "TAG";
private int mVideoWidth;
private int mVideoHeight;
private MediaPlayer mMediaPlayer;
private SurfaceView mPreview;
private SurfaceHolder holder;
private String path;
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
/*OnCreate() function */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
mPreview = (SurfaceView) findViewById(R.id.surface);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
/*playVideo() function */
private void playVideo() {
doCleanUp();
try {
path = "http://devimages.apple.com/iphone/samples/bipbop/gear1/prog_index.m3u8";
if (path == "") {
// Tell the user to provide a media file URL.
Toast.makeText(
this,
"Please edit MediaPlayerDemo_Video Activity,"
+ " and set the path variable to your media file URL.",
Toast.LENGTH_LONG).show();
}
Log.e("PATH", "Path = " + path);
// Create a new media player and set the listeners
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepare();
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
}
}
public void onBufferingUpdate(MediaPlayer arg0, int percent) {
Log.d(TAG, "onBufferingUpdate percent:" + percent);
}
public void onCompletion(MediaPlayer arg0) {
Log.d(TAG, "onCompletion called");
}
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.v(TAG, "onVideoSizeChanged called");
if (width == 0 || height == 0) {
Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
return;
}
mIsVideoSizeKnown = true;
mVideoWidth = width;
mVideoHeight = height;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void onPrepared(MediaPlayer mediaplayer) {
Log.d(TAG, "onPrepared called");
mIsVideoReadyToBePlayed = true;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
Log.d(TAG, "surfaceChanged called");
}
public void surfaceDestroyed(SurfaceHolder surfaceholder) {
Log.d(TAG, "surfaceDestroyed called");
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated called");
playVideo();
}
#Override
protected void onPause() {
super.onPause();
releaseMediaPlayer();
doCleanUp();
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
doCleanUp();
}
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
private void doCleanUp() {
mVideoWidth = 0;
mVideoHeight = 0;
mIsVideoReadyToBePlayed = false;
mIsVideoSizeKnown = false;
}
/*startVideoPlayback() function */
private void startVideoPlayback() {
Log.v(TAG, "startVideoPlayback");
holder.setFixedSize(mVideoWidth, mVideoHeight);
mMediaPlayer.start();
}
}
I updated Vitamio 4.2.2 to 5.0.0 as Google requested because of security issues in developer console. But with the same codes. Only changed Vitamio.isInitialized(getApplicationContext()); There is not error. Application was installed. But video not playing. How can i do for this?
public class MainActivity extends Activity implements MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnVideoSizeChangedListener, SurfaceHolder.Callback {
private static String TAG = MainActivity.class.getSimpleName();
private static String ShowTV = "http://mn-i.mncdn.com/showtv_ios/smil:showtv.smil/playlist.m3u8";";
private TextView tvLoader;
private int mVideoWidth;
private int mVideoHeight;
public MediaPlayer mMediaPlayer;
private SurfaceView mPreview;
private SurfaceHolder holder;
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Vitamio.isInitialized(getApplicationContext());
if (Build.VERSION.SDK_INT < 16)
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
else
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
tvLoader = (TextView) findViewById(R.id.tvLoader);
mPreview = (SurfaceView) findViewById(R.id.surface);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setFormat(PixelFormat.RGBA_8888);
}
public void playVideo() {
doCleanUp();
try {
// Create a new media player and set the listeners
mMediaPlayer = new MediaPlayer(this);
mMediaPlayer.setDataSource(ShowTv);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepareAsync();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
}
}
public void onBufferingUpdate(MediaPlayer arg0, int percent) {
// Log.d(TAG, "onBufferingUpdate percent:" + percent);
}
public void onCompletion(MediaPlayer arg0) {
Log.d(TAG, "onCompletion called");
}
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.v(TAG, "onVideoSizeChanged called");
if (width == 0 || height == 0) {
Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
return;
}
mIsVideoSizeKnown = true;
mVideoWidth = width;
mVideoHeight = height;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void onPrepared(MediaPlayer mediaplayer) {
Log.d(TAG, "onPrepared called");
mIsVideoReadyToBePlayed = true;
tvLoader.setVisibility(View.GONE);
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
Log.d(TAG, "surfaceChanged called");
}
public void surfaceDestroyed(SurfaceHolder surfaceholder) {
Log.d(TAG, "surfaceDestroyed called");
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated called");
playVideo();
}
#Override
protected void onPause() {
super.onPause();
releaseMediaPlayer();
doCleanUp();
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
doCleanUp();
}
public void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
private void doCleanUp() {
tvLoader = (TextView) findViewById(R.id.tvLoader);
tvLoader.setVisibility(View.VISIBLE);
mVideoWidth = 0;
mVideoHeight = 0;
mIsVideoReadyToBePlayed = false;
mIsVideoSizeKnown = false;
}
private void startVideoPlayback() {
Log.v(TAG, "startVideoPlayback");
holder.setFixedSize(mVideoWidth, mVideoHeight);
mMediaPlayer.start();
}
}
I have been working on video playback of progressive videos from my android application. I am able to stream videos from internet.
But the video starts after buffering the whole data.
Here is the code I am using-
private static final String MOVIEURL = "movieUrl";
private static final String TAG = "VideoPlayerActivity";
private int mVideoWidth;
private int mVideoHeight;
private MediaPlayer mMediaPlayer;
private SurfaceView mPreview;
private SurfaceHolder holder;
private String path;
private Bundle extras;
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.mediaplayer_2);
mPreview = (SurfaceView) findViewById(R.id.surface);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
extras = getIntent().getExtras();
}
private void playVideo(String movieUrl) {
doCleanUp();
try {
path=movieUrl;
// Create a new media player and set the listeners
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepare();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
return false;
}
}
public void onBufferingUpdate(MediaPlayer arg0, int percent) {
Log.d(TAG, "onBufferingUpdate percent:" + percent);
}
public void onCompletion(MediaPlayer arg0) {
Log.d(TAG, "onCompletion called");
}
private void doCleanUp() {
mVideoWidth = 0;
mVideoHeight = 0;
mIsVideoReadyToBePlayed = false;
mIsVideoSizeKnown = false;
}
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.v(TAG, "onVideoSizeChanged called");
if (width == 0 || height == 0) {
Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
return;
}
mIsVideoSizeKnown = true;
mVideoWidth = width;
mVideoHeight = height;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void onPrepared(MediaPlayer mediaplayer) {
Log.d(TAG, "onPrepared called");
mIsVideoReadyToBePlayed = true;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
Log.d(TAG, "surfaceChanged called");
}
public void surfaceDestroyed(SurfaceHolder surfaceholder) {
Log.d(TAG, "surfaceDestroyed called");
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated called");
playVideo(extras.getString(MOVIEURL));
}
#Override
protected void onPause() {
super.onPause();
releaseMediaPlayer();
doCleanUp();
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
doCleanUp();
}
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
private void startVideoPlayback() {
Log.v(TAG, "startVideoPlayback");
holder.setFixedSize(mVideoWidth, mVideoHeight);
mMediaPlayer.start();
}
This code is working fine, but not playing before the whole video gets buffered.
Is there anyway we can stream the video while buffering it in the background.
Thanks.
Instead of
mMediaPlayer.prepare();
Use :
mMediaPlayer.prepareAsync();
I'm new to Android programming and as a part of learning i tried to run this open source project(below) which ends up in an error at the import com.example.android.apis.R;. Also where and all there is R. As far as i know R.java is automatically generated and we don't need to create it or edit it. What is the reason for this error. Can anyone please explain this. I used Eclipse to run this project.
package com.example.android.apis.media;
import com.example.android.apis.R;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
public class MediaPlayerDemo_Video extends Activity implements
OnBufferingUpdateListener, OnCompletionListener,
OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback {
private static final String TAG = "MediaPlayerDemo";
private int mVideoWidth;
private int mVideoHeight;
private MediaPlayer mMediaPlayer;
private SurfaceView mPreview;
private SurfaceHolder holder;
private String path;
private Bundle extras;
private static final String MEDIA = "media";
private static final int LOCAL_AUDIO = 1;
private static final int STREAM_AUDIO = 2;
private static final int RESOURCES_AUDIO = 3;
private static final int LOCAL_VIDEO = 4;
private static final int STREAM_VIDEO = 5;
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
/**
*
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.mediaplayer_2);
mPreview = (SurfaceView) findViewById(R.id.surface);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
extras = getIntent().getExtras();
}
private void playVideo(Integer Media) {
doCleanUp();
try {
switch (Media) {
case LOCAL_VIDEO:
/*
* TODO: Set the path variable to a local media file path.
*/
path = "";
if (path == "") {
// Tell the user to provide a media file URL.
Toast
.makeText(
MediaPlayerDemo_Video.this,
"Please edit
MediaPlayerDemo_Video Activity, "
+ "and set the path
variable to your media file path."
+ " Your media file
must be stored on sdcard.",
Toast.LENGTH_LONG).show();
}
break;
case STREAM_VIDEO:
/*
* TODO: Set path variable to progressive streamable mp4 or
* 3gpp format URL. Http protocol should be used.
* Mediaplayer can only play "progressive streamable
* contents" which basically means: 1. the movie atom has to
* precede all the media data atoms. 2. The clip has to be
* reasonably interleaved.
*
*/
path = "";
if (path == "") {
// Tell the user to provide a media file URL.
Toast
.makeText(
MediaPlayerDemo_Video.this,
"Please edit
MediaPlayerDemo_Video Activity,"
+ " and set the path
variable to your media file URL.",
Toast.LENGTH_LONG).show();
}
break;
}
// Create a new media player and set the listeners
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepare();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
}
}
public void onBufferingUpdate(MediaPlayer arg0, int percent) {
Log.d(TAG, "onBufferingUpdate percent:" + percent);
}
public void onCompletion(MediaPlayer arg0) {
Log.d(TAG, "onCompletion called");
}
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.v(TAG, "onVideoSizeChanged called");
if (width == 0 || height == 0) {
Log.e(TAG, "invalid video width(" + width + ") or height("
+ height + ")");
return;
}
mIsVideoSizeKnown = true;
mVideoWidth = width;
mVideoHeight = height;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void onPrepared(MediaPlayer mediaplayer) {
Log.d(TAG, "onPrepared called");
mIsVideoReadyToBePlayed = true;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void surfaceChanged(SurfaceHolder surfaceholder, int i, int
j, int k) {
Log.d(TAG, "surfaceChanged called");
}
public void surfaceDestroyed(SurfaceHolder surfaceholder) {
Log.d(TAG, "surfaceDestroyed called");
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated called");
playVideo(extras.getInt(MEDIA));
}
#Override
protected void onPause() {
super.onPause();
releaseMediaPlayer();
doCleanUp();
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
doCleanUp();
}
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
private void doCleanUp() {
mVideoWidth = 0;
mVideoHeight = 0;
mIsVideoReadyToBePlayed = false;
mIsVideoSizeKnown = false;
}
private void startVideoPlayback() {
Log.v(TAG, "startVideoPlayback");
holder.setFixedSize(mVideoWidth, mVideoHeight);
mMediaPlayer.start();
}
}
This is the code i tried to run.
I fixed this problem by changing the project build target from Android 1.6 to Android 4.2 in Project Property/*Android*.
Some new syntax in layout xml files are not supported in old version but these error information is not display in the source code but in the output window.
This can have several causes.
Make sure that you don't have any XML errors in all your files. The R. file will not be built when you have XML errors. After you fixed the errors the R. file should be built automatically. If not, try cleaning your project.
Also, make sure you do not have this line:
import android.R;
in your class.
That implies errors on the layout or Manifest file , which are XML .
I think the common mistakes can be the error of layout design , missing tags , and so on
please Fix them first and clean the project again