Example usage for android.widget VideoView VideoView

List of usage examples for android.widget VideoView VideoView

Introduction

In this page you can find the example usage for android.widget VideoView VideoView.

Prototype

public VideoView(Context context) 

Source Link

Usage

From source file:com.mllrsohn.videodialog.VideoDialogPlugin.java

private void playVideo(JSONObject params, final CallbackContext callbackContext) throws JSONException {

    loopVideo = params.optBoolean("loop", true);
    path = params.optString("url");

    uri = Uri.parse(path);/* w ww .ja  v  a 2 s. com*/

    if (path.contains(ASSETS)) {
        try {
            String filepath = path.replace(ASSETS, "");
            String filename = filepath.substring(filepath.lastIndexOf("/") + 1, filepath.length());
            File fp = new File(this.cordova.getActivity().getFilesDir() + "/" + filename);

            if (!fp.exists()) {
                this.copy(filepath, filename);
            }
            uri = Uri.parse("file://" + this.cordova.getActivity().getFilesDir() + "/" + filename);
        } catch (IOException e) {
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION));
        }

    }

    // Create dialog in new thread
    cordova.getActivity().runOnUiThread(new Runnable() {
        public void run() {

            // Set Basic Dialog
            dialog = new Dialog((Context) cordova.getActivity(), android.R.style.Theme_NoTitleBar_Fullscreen);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);

            // Layout View
            RelativeLayout main = new RelativeLayout((Context) cordova.getActivity());
            main.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

            // Video View
            mVideoView = new VideoView((Context) cordova.getActivity());
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            lp.addRule(RelativeLayout.CENTER_IN_PARENT);
            mVideoView.setLayoutParams(lp);

            mVideoView.setVideoPath(uri.toString());
            mVideoView.start();
            main.addView(mVideoView);

            dialog.setContentView(main);
            dialog.getWindow().setFlags(LayoutParams.FLAG_FULLSCREEN, LayoutParams.FLAG_FULLSCREEN);
            dialog.show();

            // Close on touch
            mVideoView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "stopped"));
                    dialog.dismiss();
                    return true;
                }
            });

            // Set Looping
            mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.setLooping(loopVideo);
                }
            });

            // On Completion
            mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaplayer) {
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, "Done"));
                    dialog.dismiss();
                }
            });

        }
    });
}

From source file:org.quantumbadger.redreader.activities.ImageViewActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    final boolean solidblack = PrefsUtility.appearance_solidblack(this, sharedPreferences);

    if (solidblack)
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.BLACK));

    final Intent intent = getIntent();

    mUrl = General.uriFromString(intent.getDataString());
    final RedditPost src_post = intent.getParcelableExtra("post");

    if (mUrl == null) {
        General.quickToast(this, "Invalid URL. Trying web browser.");
        revertToWeb();/* ww w  . j  ava  2  s .  c  om*/
        return;
    }

    Log.i("ImageViewActivity", "Loading URL " + mUrl.toString());

    final ProgressBar progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);

    final LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(progressBar);

    CacheManager.getInstance(this)
            .makeRequest(mRequest = new CacheRequest(mUrl, RedditAccountManager.getAnon(), null,
                    Constants.Priority.IMAGE_VIEW, 0, CacheRequest.DownloadType.IF_NECESSARY,
                    Constants.FileType.IMAGE, false, false, false, this) {

                private void setContentView(View v) {
                    layout.removeAllViews();
                    layout.addView(v);
                    v.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
                    v.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
                }

                @Override
                protected void onCallbackException(Throwable t) {
                    BugReportActivity.handleGlobalError(context.getApplicationContext(),
                            new RRError(null, null, t));
                }

                @Override
                protected void onDownloadNecessary() {
                    AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setVisibility(View.VISIBLE);
                            progressBar.setIndeterminate(true);
                        }
                    });
                }

                @Override
                protected void onDownloadStarted() {
                }

                @Override
                protected void onFailure(final RequestFailureType type, Throwable t, StatusLine status,
                        final String readableMessage) {

                    final RRError error = General.getGeneralErrorForFailure(context, type, t, status,
                            url.toString());

                    AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                        public void run() {
                            // TODO handle properly
                            mRequest = null;
                            progressBar.setVisibility(View.GONE);
                            layout.addView(new ErrorView(ImageViewActivity.this, error));
                        }
                    });
                }

                @Override
                protected void onProgress(final boolean authorizationInProgress, final long bytesRead,
                        final long totalBytes) {
                    AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setVisibility(View.VISIBLE);
                            progressBar.setIndeterminate(authorizationInProgress);
                            progressBar.setProgress((int) ((100 * bytesRead) / totalBytes));
                        }
                    });
                }

                @Override
                protected void onSuccess(final CacheManager.ReadableCacheFile cacheFile, long timestamp,
                        UUID session, boolean fromCache, final String mimetype) {

                    if (mimetype == null
                            || (!Constants.Mime.isImage(mimetype) && !Constants.Mime.isVideo(mimetype))) {
                        revertToWeb();
                        return;
                    }

                    final InputStream cacheFileInputStream;
                    try {
                        cacheFileInputStream = cacheFile.getInputStream();
                    } catch (IOException e) {
                        notifyFailure(RequestFailureType.PARSE, e, null,
                                "Could not read existing cached image.");
                        return;
                    }

                    if (cacheFileInputStream == null) {
                        notifyFailure(RequestFailureType.CACHE_MISS, null, null, "Could not find cached image");
                        return;
                    }

                    if (Constants.Mime.isVideo(mimetype)) {

                        AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                            public void run() {

                                if (mIsDestroyed)
                                    return;
                                mRequest = null;

                                try {
                                    final RelativeLayout layout = new RelativeLayout(context);
                                    layout.setGravity(Gravity.CENTER);

                                    final VideoView videoView = new VideoView(ImageViewActivity.this);

                                    videoView.setVideoURI(cacheFile.getUri());
                                    layout.addView(videoView);
                                    setContentView(layout);

                                    layout.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
                                    layout.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
                                    videoView.setLayoutParams(
                                            new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                                    ViewGroup.LayoutParams.MATCH_PARENT));

                                    videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                                        @Override
                                        public void onPrepared(MediaPlayer mp) {
                                            mp.setLooping(true);
                                            videoView.start();
                                        }
                                    });

                                    videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                                        @Override
                                        public boolean onError(final MediaPlayer mediaPlayer, final int i,
                                                final int i1) {
                                            revertToWeb();
                                            return true;
                                        }
                                    });

                                    videoView.setOnTouchListener(new View.OnTouchListener() {
                                        @Override
                                        public boolean onTouch(final View view, final MotionEvent motionEvent) {
                                            finish();
                                            return true;
                                        }
                                    });

                                } catch (OutOfMemoryError e) {
                                    General.quickToast(context, R.string.imageview_oom);
                                    revertToWeb();

                                } catch (Throwable e) {
                                    General.quickToast(context, R.string.imageview_invalid_video);
                                    revertToWeb();
                                }
                            }
                        });

                    } else if (Constants.Mime.isImageGif(mimetype)) {

                        final PrefsUtility.GifViewMode gifViewMode = PrefsUtility
                                .pref_behaviour_gifview_mode(context, sharedPreferences);

                        if (gifViewMode == PrefsUtility.GifViewMode.INTERNAL_BROWSER) {
                            revertToWeb();
                            return;

                        } else if (gifViewMode == PrefsUtility.GifViewMode.EXTERNAL_BROWSER) {
                            AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                                @Override
                                public void run() {
                                    LinkHandler.openWebBrowser(ImageViewActivity.this,
                                            Uri.parse(mUrl.toString()));
                                    finish();
                                }
                            });

                            return;
                        }

                        if (AndroidApi.isIceCreamSandwichOrLater()
                                && gifViewMode == PrefsUtility.GifViewMode.INTERNAL_MOVIE) {

                            AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                                public void run() {

                                    if (mIsDestroyed)
                                        return;
                                    mRequest = null;

                                    try {
                                        final GIFView gifView = new GIFView(ImageViewActivity.this,
                                                cacheFileInputStream);
                                        setContentView(gifView);
                                        gifView.setOnClickListener(new View.OnClickListener() {
                                            public void onClick(View v) {
                                                finish();
                                            }
                                        });

                                    } catch (OutOfMemoryError e) {
                                        General.quickToast(context, R.string.imageview_oom);
                                        revertToWeb();

                                    } catch (Throwable e) {
                                        General.quickToast(context, R.string.imageview_invalid_gif);
                                        revertToWeb();
                                    }
                                }
                            });

                        } else {

                            gifThread = new GifDecoderThread(cacheFileInputStream,
                                    new GifDecoderThread.OnGifLoadedListener() {

                                        public void onGifLoaded() {
                                            AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                                                public void run() {

                                                    if (mIsDestroyed)
                                                        return;
                                                    mRequest = null;

                                                    imageView = new ImageView(context);
                                                    imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                                                    setContentView(imageView);
                                                    gifThread.setView(imageView);

                                                    imageView.setOnClickListener(new View.OnClickListener() {
                                                        public void onClick(View v) {
                                                            finish();
                                                        }
                                                    });
                                                }
                                            });
                                        }

                                        public void onOutOfMemory() {
                                            General.quickToast(context, R.string.imageview_oom);
                                            revertToWeb();
                                        }

                                        public void onGifInvalid() {
                                            General.quickToast(context, R.string.imageview_invalid_gif);
                                            revertToWeb();
                                        }
                                    });

                            gifThread.start();

                        }

                    } else {

                        final ImageTileSource imageTileSource;
                        try {

                            final long bytes = cacheFile.getSize();
                            final byte[] buf = new byte[(int) bytes];

                            try {
                                new DataInputStream(cacheFileInputStream).readFully(buf);
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }

                            try {
                                imageTileSource = new ImageTileSourceWholeBitmap(buf);

                            } catch (Throwable t) {
                                Log.e("ImageViewActivity", "Exception when creating ImageTileSource", t);
                                General.quickToast(context, R.string.imageview_decode_failed);
                                revertToWeb();
                                return;
                            }

                        } catch (OutOfMemoryError e) {
                            General.quickToast(context, R.string.imageview_oom);
                            revertToWeb();
                            return;
                        }

                        AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                            public void run() {

                                if (mIsDestroyed)
                                    return;
                                mRequest = null;
                                mImageViewDisplayerManager = new ImageViewDisplayListManager(imageTileSource,
                                        ImageViewActivity.this);
                                surfaceView = new RRGLSurfaceView(ImageViewActivity.this,
                                        mImageViewDisplayerManager);
                                setContentView(surfaceView);

                                surfaceView.setOnClickListener(new View.OnClickListener() {
                                    public void onClick(View v) {
                                        finish();
                                    }
                                });

                                if (mIsPaused) {
                                    surfaceView.onPause();
                                } else {
                                    surfaceView.onResume();
                                }
                            }
                        });
                    }
                }
            });

    final RedditPreparedPost post = src_post == null ? null
            : new RedditPreparedPost(this, CacheManager.getInstance(this), 0, src_post, -1, false, false, false,
                    false, RedditAccountManager.getInstance(this).getDefaultAccount(), false);

    final FrameLayout outerFrame = new FrameLayout(this);
    outerFrame.addView(layout);

    if (post != null) {

        final SideToolbarOverlay toolbarOverlay = new SideToolbarOverlay(this);

        final BezelSwipeOverlay bezelOverlay = new BezelSwipeOverlay(this,
                new BezelSwipeOverlay.BezelSwipeListener() {

                    public boolean onSwipe(BezelSwipeOverlay.SwipeEdge edge) {

                        toolbarOverlay.setContents(
                                post.generateToolbar(ImageViewActivity.this, false, toolbarOverlay));
                        toolbarOverlay.show(edge == BezelSwipeOverlay.SwipeEdge.LEFT
                                ? SideToolbarOverlay.SideToolbarPosition.LEFT
                                : SideToolbarOverlay.SideToolbarPosition.RIGHT);
                        return true;
                    }

                    public boolean onTap() {

                        if (toolbarOverlay.isShown()) {
                            toolbarOverlay.hide();
                            return true;
                        }

                        return false;
                    }
                });

        outerFrame.addView(bezelOverlay);
        outerFrame.addView(toolbarOverlay);

        bezelOverlay.getLayoutParams().width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;
        bezelOverlay.getLayoutParams().height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;

        toolbarOverlay.getLayoutParams().width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;
        toolbarOverlay.getLayoutParams().height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;

    }

    setContentView(outerFrame);
}

From source file:com.example.damerap_ver1.IntroVideoActivity.java

/**
* Create the view in which the video will be rendered.
*///from w w w  .  ja va 2  s . c o  m
private void setupView() {
    LinearLayout lLinLayout = new LinearLayout(this);
    lLinLayout.setId(1);
    lLinLayout.setOrientation(LinearLayout.VERTICAL);
    lLinLayout.setGravity(Gravity.CENTER);
    lLinLayout.setBackgroundColor(Color.BLACK);

    LayoutParams lLinLayoutParms = new LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
            ViewGroup.LayoutParams.FILL_PARENT);
    lLinLayout.setLayoutParams(lLinLayoutParms);

    this.setContentView(lLinLayout);

    RelativeLayout lRelLayout = new RelativeLayout(this);
    lRelLayout.setId(2);
    lRelLayout.setGravity(Gravity.CENTER);
    lRelLayout.setBackgroundColor(Color.BLACK);
    android.widget.RelativeLayout.LayoutParams lRelLayoutParms = new android.widget.RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
    lRelLayout.setLayoutParams(lRelLayoutParms);
    lLinLayout.addView(lRelLayout);

    mVideoView = new VideoView(this);
    mVideoView.setId(3);
    android.widget.RelativeLayout.LayoutParams lVidViewLayoutParams = new android.widget.RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    lVidViewLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
    mVideoView.setLayoutParams(lVidViewLayoutParams);
    lRelLayout.addView(mVideoView);

    mProgressBar = new ProgressBar(this);
    mProgressBar.setId(4);
    android.widget.RelativeLayout.LayoutParams lProgressBarLayoutParms = new android.widget.RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    lProgressBarLayoutParms.addRule(RelativeLayout.CENTER_IN_PARENT);
    mProgressBar.setLayoutParams(lProgressBarLayoutParms);
    lRelLayout.addView(mProgressBar);

    mProgressMessage = new TextView(this);
    mProgressMessage.setId(5);
    android.widget.RelativeLayout.LayoutParams lProgressMsgLayoutParms = new android.widget.RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    lProgressMsgLayoutParms.addRule(RelativeLayout.CENTER_HORIZONTAL);
    lProgressMsgLayoutParms.addRule(RelativeLayout.BELOW, 4);
    mProgressMessage.setLayoutParams(lProgressMsgLayoutParms);
    mProgressMessage.setTextColor(Color.LTGRAY);
    mProgressMessage.setTextSize(TypedValue.COMPLEX_UNIT_PT, 8);
    mProgressMessage.setText("...");
    lRelLayout.addView(mProgressMessage);
}

From source file:com.codename1.impl.android.AndroidImplementation.java

/**
 * @inheritDoc/*  www  .  java 2 s  . c o  m*/
 */
@Override
public Media createMedia(final String uri, boolean isVideo, final Runnable onCompletion) throws IOException {
    if (getActivity() == null) {
        return null;
    }
    if (!uri.startsWith(FileSystemStorage.getInstance().getAppHomePath())) {
        if (!checkForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, "This is required to play media")) {
            return null;
        }
    }
    if (uri.startsWith("file://")) {
        return createMedia(removeFilePrefix(uri), isVideo, onCompletion);
    }
    File file = null;
    if (uri.indexOf(':') < 0) {
        // use a file object to play to try and workaround this issue:
        // http://code.google.com/p/android/issues/detail?id=4124
        file = new File(uri);
    }

    Media retVal;

    if (isVideo) {
        final AndroidImplementation.Video[] video = new AndroidImplementation.Video[1];
        final boolean[] flag = new boolean[1];
        final File f = file;
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                VideoView v = new VideoView(getActivity());
                v.setZOrderMediaOverlay(true);
                if (f != null) {
                    v.setVideoURI(Uri.fromFile(f));
                } else {
                    v.setVideoURI(Uri.parse(uri));
                }
                video[0] = new AndroidImplementation.Video(v, getActivity(), onCompletion);
                flag[0] = true;
                synchronized (flag) {
                    flag.notify();
                }
            }
        });
        while (!flag[0]) {
            synchronized (flag) {
                try {
                    flag.wait(100);
                } catch (InterruptedException ex) {
                }
            }
        }
        return video[0];
    } else {
        MediaPlayer player;
        if (file != null) {
            FileInputStream is = new FileInputStream(file);
            player = new MediaPlayer();
            player.setDataSource(is.getFD());
            player.prepare();
        } else {
            player = MediaPlayer.create(getActivity(), Uri.parse(uri));
        }
        retVal = new Audio(getActivity(), player, null, onCompletion);
    }
    return retVal;
}

From source file:com.codename1.impl.android.AndroidImplementation.java

/**
 * @inheritDoc//ww  w  .  j a va2 s. com
 */
@Override
public Media createMedia(InputStream stream, String mimeType, final Runnable onCompletion) throws IOException {
    if (getActivity() == null) {
        return null;
    }
    /*if(!checkForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, "This is required to play media")){
    return null;
    }*/
    boolean isVideo = mimeType.contains("video");

    if (!isVideo && stream instanceof FileInputStream) {
        MediaPlayer player = new MediaPlayer();
        player.setDataSource(((FileInputStream) stream).getFD());
        player.prepare();
        return new Audio(getActivity(), player, stream, onCompletion);
    }
    String extension = MimeTypeMap.getFileExtensionFromUrl(mimeType);
    final File temp = File.createTempFile("mtmp", extension == null ? "dat" : extension);
    temp.deleteOnExit();
    OutputStream out = createFileOuputStream(temp);

    byte buf[] = new byte[256];
    int len = 0;
    while ((len = stream.read(buf, 0, buf.length)) > -1) {
        out.write(buf, 0, len);
    }
    out.close();
    stream.close();

    final Runnable finish = new Runnable() {

        @Override
        public void run() {
            if (onCompletion != null) {
                Display.getInstance().callSerially(onCompletion);

                // makes sure the file is only deleted after the onCompletion was invoked
                Display.getInstance().callSerially(new Runnable() {
                    @Override
                    public void run() {
                        temp.delete();
                    }
                });
                return;
            }
            temp.delete();
        }
    };

    if (isVideo) {
        final AndroidImplementation.Video[] retVal = new AndroidImplementation.Video[1];
        final boolean[] flag = new boolean[1];

        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                VideoView v = new VideoView(getActivity());
                v.setZOrderMediaOverlay(true);
                v.setVideoURI(Uri.fromFile(temp));
                retVal[0] = new AndroidImplementation.Video(v, getActivity(), finish);
                flag[0] = true;
                synchronized (flag) {
                    flag.notify();
                }
            }
        });
        while (!flag[0]) {
            synchronized (flag) {
                try {
                    flag.wait(100);
                } catch (InterruptedException ex) {
                }
            }
        }

        return retVal[0];
    } else {
        return createMedia(createFileInputStream(temp), mimeType, finish);
    }

}