Android Custom video player (Network/local)

Source: Internet
Author: User

Recently, because of the company's project requirements need to write a player, comes with not very good, also not very nice. Self-customizable. See a lot of information, there is no perfect, fortunately for the guidance of the predecessors to be completed , thank Yang. I may have some places in this article that are poorly written (with comments attached). Hope that the way the great God guidance, humbly educated.

Take a picture first ( the source is attached to the back )

The data in the video list is local, and if you need to use the network, just get the data display of the server here. The playback page is in the back.

Package Com.eteng.moblieplayer.video;import Android.content.contentresolver;import Android.content.intent;import Android.database.cursor;import Android.net.uri;import Android.os.bundle;import Android.os.Handler;import Android.os.message;import Android.provider.mediastore;import Android.view.view;import Android.widget.AdapterView; Import Android.widget.listview;import Android.widget.textview;import Com.eteng.moblieplayer.baseactivity;import Com.eteng.moblieplayer.r;import Com.eteng.moblieplayer.adapter.videoadapter;import Com.eteng.moblieplayer.beans.videobenas;import Com.eteng.moblieplayer.utils.stringtimeutil;import Org.xutils.view.annotation.viewinject;import Java.util.arraylist;import Java.util.formatter;import java.util.List ;/** * Created by ZQF on 2016/7/6. */public class Videoactivity extends Baseactivity implements Adapterview.onitemclicklistener {private ListView video_l    Istview;    Private TextView Noresources_tv;    private Videobenas beans; Private List<videobenas>    data = new arraylist<videobenas> ();    Private Videoadapter adapter;    Private Stringtimeutil util; Public Handler Handler = new Handler () {@Override public void Handlemessage (Message msg) {Super            . Handlemessage (msg);                        Switch (msg.what) {case 0:if (data! = NULL && data.size ()! = 0) {                        Noresources_tv.setvisibility (View.gone);                        adapter = new Videoadapter (data, videoactivity.this, util);                    Video_listview.setadapter (adapter);                    } else {noresources_tv.setvisibility (view.visible);            } break;    }        }    };        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Settabtitle ("video list");        Setrightvisible (View.gone);     Video_listview = (ListView) Findviewbyid (R.ID.VIDEO_LISTVIW);   NORESOURCES_TV = (TextView) Findviewbyid (R.ID.NORESOURCES_TV);        Util = new Stringtimeutil ();        Getallvideo ();    Video_listview.setonitemclicklistener (this);                } private void Getallvideo () {New Thread (new Runnable () {@Override public void run () {                Contentresolver resolver = Getcontentresolver ();                Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; Find condition string[] projection = {MediaStore.Video.Media.TITLE,//title Mediastore.video . Media.description,//Description MediaStore.Video.Media.SIZE,//Size Mediast Ore.   Video.Media.DURATION,//Duration MediaStore.Video.Media.DATA};                Absolute path cursor cursor = resolver.query (URI, projection, NULL, NULL, NULL);                    while (Cursor.movetonext ()) {//Judging video size &GT;3MB only add in. if (Cursor.getlong (2)> 3 * 1024x768 * 1024x768) {beans = new Videobenas ();                        Beans.settitle (cursor.getstring (0));                        Beans.setdescribe (cursor.getstring (1));                        Beans.setsize (Cursor.getlong (2));                        Beans.setlongtime (Cursor.getstring (3));                        Beans.setpath (Cursor.getstring (4));                    Data.add (beans);            }} handler.sendemptymessage (0);    }}). Start ();    } @Override public void Leftonclick () {finish (); } @Override public void Rightonclick () {}//Load child layout contents @Override public View setcontent () {return    View.inflate (videoactivity.this, r.layout.activity_video, NULL); } @Override public void Onitemclick (adapterview<?> parent, view view, int position, long id) {Videoben        As item = data.get (position); Intent Intent = new Intent (Videoactivity.this, VideopLayeractivity.class);        Intent.setdata (Uri.parse (Item.getpath ()));        Intent.putextra ("Videotitle", Item.gettitle ());    StartActivity (Intent); }}

Okay, here's the player page.

Package Com.eteng.moblieplayer.video;import Android.content.broadcastreceiver;import Android.content.Context; Import Android.content.intent;import Android.content.intentfilter;import Android.media.mediaplayer;import Android.net.uri;import Android.os.bundle;import Android.os.handler;import Android.os.message;import Android.util.log;import Android.view.gesturedetector;import Android.view.motionevent;import Android.view.View; Import Android.view.windowmanager;import Android.widget.imageview;import Android.widget.linearlayout;import Android.widget.progressbar;import Android.widget.relativelayout;import Android.widget.seekbar;import Android.widget.textview;import Android.widget.toast;import Com.eteng.moblieplayer.baseactivity;import Com.eteng.moblieplayer.r;import Com.eteng.moblieplayer.utils.stringtimeutil;import com.eteng.moblieplayer.view.videoview;/** * Created by ZQF on 2016/7/6. * Play page */public class Videoplayeractivity extends Baseactivity implements Mediaplayer.onpreparedlistener, MedIaplayer.oninfolistener {private Videoview videoview;    --Play the address URI private URI Uri;    Private ImageView Play_imag, Fullview_imag, Back_imag, Battery_imag;    Private SeekBar Mseekbar;    Private TextView videotitle, SystemTime;    Private TextView videocurrent_time, Videototal_time;    Private Stringtimeutil utils;    Private Mybrodcastreceiver receiver;    Set the power private int leave;    Gesture Recognizer Private Gesturedetector detector;    Top layout private relativelayout top_layout;    Bottom layout private linearlayout bottom_layout;    /** * Determines whether to play */private Boolean isplayer = false;    /*** * Determine if activity is destroyed *--true--> destroyed *--false not destroyed */private Boolean isdestory = false;    private static final int PROGRESS = 1;    Hide the top and bottom variables private static final int hide_topbottomlayout = 2;    /** * Network Load wait layout */private linearlayout ll_loading;    /*** * appears the card buffer loading * * Private ProgressBar Pg_buff; Private Handler MhandlER = new Handler () {@Override public void Handlemessage (Message msg) {super.handlemessage (msg);  Switch (msg.what) {case PROGRESS://Set Progress int currenttime                    = Videoview.getcurrentposition ();                    Videocurrent_time.settext (Utils.stringfortime (currenttime));                    Updated Seekbar mseekbar.setprogress (currenttime);                    Update the Power//battery display and the system time can be set to the time of self-update setbattery ();                    Set the system time SetSystemTime (); /*** * Get video Cache Level *--Cache Scale value -0~100 */int Perce                    Ntage = Videoview.getbufferpercentage ();                    int total = Percentage * Mseekbar.getmax ();                    int secondaryprogress = total/100;                    Mseekbar.setsecondaryprogress (secondaryprogress); if (!isdesTory) {mhandler.removemessages (PROGRESS);                    Dead loop of message--used to update playback progress mhandler.sendemptymessagedelayed (PROGRESS, 1000);                } break;                    Case Hide_topbottomlayout:hidelayout ();            Break    }        }    };        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Settabvisible (View.gone);        Initview ();        InitData ();        Setonclick ();        Get the playback address URI = Getintent (). GetData (); Videoview.setvideouri (URI);  Set path Videoview.setonpreparedlistener (this);    Prepared listener event} private void SetSystemTime () {Systemtime.settext (Utils.getsystemtime ()); } private void Setbattery () {if (leave <= 5) {Battery_imag.setimageresource (r.mipmap.icv_power_0        0); } else if (leave <=) {Battery_imag.setimagerEsource (R.MIPMAP.ICV_POWER_01);        } else if (leave <=) {Battery_imag.setimageresource (r.mipmap.icv_power_02);        } else if (leave <=) {Battery_imag.setimageresource (r.mipmap.icv_power_03);        } else if (leave <=) {Battery_imag.setimageresource (r.mipmap.icv_power_04);        } else if (leave <=) {Battery_imag.setimageresource (r.mipmap.icv_power_05);    }}/*** * true--show--false--hidden */Private Boolean isshowlayout = false;        private void InitData () {Videotitle.settext (Getintent (). Getstringextra ("Videotitle"));        Isdestory = false;        Utils = new Stringtimeutil ();        Registered Power Monitor broadcast Intentfilter intentfilter = new Intentfilter ();        Intentfilter.addaction (intent.action_battery_changed);        Receiver = new Mybrodcastreceiver ();        Registerreceiver (receiver, intentfilter); Instantiate detector = new Gesturedetector (Videoplayeractivity.this,New Gesturedetector.ongesturelistener () {//Click @Override Public boolean Ondown (Motioneven                T e) {LOG.E ("TAG", "Ondown");                    if (isshowlayout) {removehidetopbottomlayoutmessage ();                Hidelayout ();                    } else {senddelayedhidetopbottomlayout ();                Showlayout ();            } return true; }//Long press the order of execution---1.ondown-->2.onshowpress-->onlongpress @Override public void ONSHOWPR            ESS (Motionevent e) {log.e ("TAG", "onshowpress");                ///Click to execute Ondown then execute the method @Override public boolean onsingletapup (Motionevent e) {                LOG.E ("TAG", "Onsingletapup");            return false;  }//Slide @Override public boolean onscroll (Motionevent E1, motionevent E2, float Distancex,      Float Distancey) {          LOG.E ("TAG", "onscroll");            return false; }//Long press @Override public void onlongpress (Motionevent e) {log.e ("TAG", "on            Longpress ");  } @Override public boolean onfling (Motionevent E1, motionevent E2, float Velocityx, float velocityy)            {return false;    }        }); }/*** * Send delay hide */private void Senddelayedhidetopbottomlayout () {mhandler.sendemptymessagedelayed (H    Ide_topbottomlayout, 5000); }/*** * Remove deferred hidden handler message */private void Removehidetopbottomlayoutmessage () {Mhandler.removemessage    S (hide_topbottomlayout);        }/*** * Shows the method */private void Showlayout () {isshowlayout = true;        Top_layout.setvisibility (view.visible);    Bottom_layout.setvisibility (view.visible);        }/*** * Hidden method */private void Hidelayout () {isshowlayout = false; Top_layout. setvisibility (View.gone);    Bottom_layout.setvisibility (View.gone); }/*** * Use gesture Adapter * * @param event * @return */@Override public boolean ontouchevent (Motionev        Ent event) {super.ontouchevent (event);        Detector.ontouchevent (event);    return true;     Returns true depending on the callback that occurs when the card is processed by the/*** * card or when you drag it * * @param MP * @param what * @param extra * @return  */@Override public Boolean oninfo (MediaPlayer MP, int. what, int extra) {switch                Mediaplayer.media_info_buffering_start://start to appear card or drag card pg_buff.setvisibility (view.visible);            Break                Case Mediaplayer.media_info_buffering_end://End card or drag card condition pg_buff.setvisibility (View.gone);        Break    } return true; } private class Mybrodcastreceiver extends Broadcastreceiver {@Override public void OnReceive (Context Co ntext, Intent Intent){//returns the range value of a charge leave = Intent.getintextra ("level", 0);        }} @Override protected void OnDestroy () {Super.ondestroy ();        Isdestory = true;        Unregisterreceiver (receiver);        receiver = null;    Videoview.stopplayback ();        } public void Initview () {Pg_buff = (ProgressBar) Findviewbyid (R.id.pg_buff);        Videoview = (videoview) Findviewbyid (R.id.videoview);        ll_loading = (linearlayout) Findviewbyid (r.id.ll_loading);        Top_layout = (relativelayout) Findviewbyid (r.id.toplayout);        Bottom_layout = (linearlayout) Findviewbyid (r.id.bottomlayout);        SystemTime = (TextView) Findviewbyid (r.id.videosystemtime);        Battery_imag = (ImageView) Findviewbyid (r.id.videopower);        Back_imag = (ImageView) Findviewbyid (r.id.videoback);        Play_imag = (ImageView) Findviewbyid (R.id.videoplay);        Fullview_imag = (ImageView) Findviewbyid (R.id.videofullscreen); Mseekbar = (SeekBar) findviewbYid (r.id.videoplayprogress);        Videotitle = (TextView) Findviewbyid (r.id.videotitle);        Videocurrent_time = (TextView) Findviewbyid (r.id.videocurrentprogress);    Videototal_time = (TextView) Findviewbyid (r.id.videototaltime);        } public void Setonclick () {Back_imag.setonclicklistener (Onclicklistener);        Play_imag.setonclicklistener (Onclicklistener);        Fullview_imag.setonclicklistener (Onclicklistener);        Videoview.setoninfolistener (this); Mseekbar.setonseekbarchangelistener (New Seekbar.onseekbarchangelistener () {/*** * * @p Aram seekbar--> Own SEEKBA * @param progress-->seekbar location, length of video and location of SeekBar one by one corresponding to * @param fromus Er--> if it is an artificial drag value of--true, such as Seekbar itself in the changed value--false */@Override public void Onprogresschang Ed (SeekBar SeekBar, int progress, Boolean fromuser) {if (Fromuser) {Videoview.seekto (P            rogress);    }}/** * Callback when the finger starts to drag * @param seekBar */@Overri            De public void Onstarttrackingtouch (SeekBar SeekBar) {removehidetopbottomlayoutmessage (); }/** * Finger left callback * @param seekBar */@Override P            ublic void Onstoptrackingtouch (SeekBar SeekBar) {senddelayedhidetopbottomlayout ();        }        }); /*** * When video loading error occurs *--true--> man-made error-handling results */videoview.setonerrorlistener (new MediaPlayer.                Onerrorlistener () {@Override public boolean onError (MediaPlayer MP, int. what, int extra) {                Toast.maketext (videoplayeractivity.this, "video error", Toast.length_long). Show ();                Finish ();            return true;    }        });        } view.onclicklistener Onclicklistener = new View.onclicklistener () {@Overridepublic void OnClick (View v) {switch (V.getid ()) {Case R.id.videoplay:if (i                        Splayer) {videoview.pause ();                    Play_imag.setimageresource (R.mipmap.icv_play);                        } else {Videoview.start ();                    Play_imag.setimageresource (R.mipmap.icv_pause);                    } Isplayer =!isplayer;                Break                    Case R.id.videoback:finish ();                    Videoview.stopplayback ();            Break    }        }    };    @Override public void Leftonclick () {} @Override public void Rightonclick () {}//Set sub-layout @Override    Public View setcontent () {return view.inflate (videoplayeractivity.this, r.layout.activity_videoplayer, NULL);     }/*** * Monitor is ready * * @param MP */@Override public void onprepared (MediaPlayer MP) {   Videoview.start ();        Play_imag.setimageresource (R.mipmap.icv_pause);        Isplayer = true;        Gets the total duration int duration = Videoview.getduration ();        Videototal_time.settext ("/" + utils.stringfortime (duration));        Sets the maximum value of Seekbar Mseekbar.setmax (duration);        SetSystemTime ();        Mhandler.sendemptymessagedelayed (PROGRESS, 1000);        Senddelayedhidetopbottomlayout ();    Ll_loading.setvisibility (View.gone); }}
Let's end with a picture!

Last forgotten the Origin code address, to fill up, sorry.

Source Address

Android Custom video player (Network/local)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.