Android uses Vitamio to build its own universal player (7)--Play Online (download video) _android

Source: Internet
Author: User
Tags int size volatile


Objective



This chapter will implement a very useful feature--download online video. Related to multithreading, thread update UI technology, but also need to think about product design, how the new added function better integration into the existing products, not simply add an interface on the line, welcome everyone to exchange product design and technical details to achieve!



Series



1. Android uses Vitamio to build its own universal player (1)--ready



2, Android uses Vitamio to build its own universal player (2)--gesture control brightness, volume, zoom



3, Android use Vitamio to build their own universal player (3)--local playback (main interface, video list)



4, Android use Vitamio to build their own universal player (4)--Local playback (fast search, data storage)



5, Android use Vitamio to build their own universal player (5)--Play online (play cool video)



6. Android uses Vitamio to build its own universal player (6)--Play Online (playlist)



Body



I. Objectives



This chapter realizes the function of the video downloading









Instructions: To enter the online video, click on the play will be pop-up selection box to ask for playback or download, click on the download of the LIFO bar will be displayed at the top of the local video. If you want to download it, click on the video you are downloading in the local playlist.



Ii. implementation (part of the main implementation code)



filedownloadhelper


Public class FileDownloadHelper {
Private static final String TAG = "FileDownloadHelper";
/** thread pool */
Private ThreadPool mPool = new ThreadPool();
/** start downloading */
Public static final int MESSAGE_START = 0;
/** update progress */
Public static final int MESSAGE_PROGRESS = 1;
/** download ends */
Public static final int MESSAGE_STOP = 2;
/** download error */
Public static final int MESSAGE_ERROR = 3;
/** terminate halfway */
Private volatile Boolean mIsStop = false;
Private Handler mHandler;
Public volatile HashMap<string, string=""> mDownloadUrls = new HashMap<string, string="">();</string,></string,>

Public FileDownloadHelper (Handler Handler) {
If (handler = = null)
Throw new IllegalArgumentException("handler cannot be empty!" );

Enclosing mHandler = handler;
}

Public void stopALl () {
MIsStop = true;
MPool. Stop ();
}

Public void newDownloadFile(final String url) {
NewDownloadFile (url, and the Environment. External.getexternalstoragedirectory () + "/" + FileUtils getUrlFileName (url));
}

/ * *
* download a new file
*
* @ param url
* @ param savePath
* /
Public void newDownloadFile(final String url, final String savePath) {
If (mDownloadUrls. Either containsKey (url))
The return;
The else
MDownloadUrls. Put (url, savePath);
MPool. Start (new Runnable () {

@ Override
Public void the run () {
MHandler. SendMessage (mHandler. ObtainMessage (MESSAGE_START, url));
HttpClient = new DefaultHttpClient();
HttpGet = new HttpGet(url);
InputStream InputStream = null;
FileOutputStream outputStream = null;
Try {
HttpResponse response = client. The execute (get);
HttpEntity entity = response. GetEntity ();
Final int size = (int) entity.getcontentlength ();
InputStream = entity. GetContent ();
If (size > 0 && inputStream! = null) {
OutputStream = new FileOutputStream (savePath);
Int ch = 1;
Byte [] buf = new byte[1024];
// update the progress once per second
New Timer (). The schedule (new TimerTask () {

@ Override
Public void the run () {
Try {
FileInputStream fis = new FileInputStream(new File(savePath));
Int downloadedSize = fis. Available ();
If (downloadedSize > = the size)
The cancel ();
MHandler. SendMessage (mHandler. ObtainMessage (MESSAGE_PROGRESS downloadedSize, size, url));
} catch (Exception e) {

}
}
}, 50, 1000);

While ((ch = inputstream.read (buf))! = 1 &&! MIsStop) {
OutputStream. Write (buf, 0, ch);
}
OutputStream. Flush ();
}
} catch (Exception e) {
The e (TAG, um participant etMessage (), e);
Mhandler. sendMessage(mhandler. obtainMessage(MESSAGE_ERROR, url + ":" + getmessage ()));
} the finally {
Try {
If (outputStream! = null)
OutputStream. Close ();
} catch (IOException ex) {
}
Try {
If (inputStream! = null)
InputStream. Close ();
} catch (IOException ex) {
}
}
MDownloadUrls. Remove (url);
MHandler. SendMessage (mHandler. ObtainMessage (MESSAGE_STOP, url));
}
});
}
}


Code Description:



A. ThreadPool is a thread pool, please refer to the project code.
B. Here the time is used to brush the progress, but not directly in the Write data update progress, such as higher write per second, update the UI too often, may cause timeouts and so on.



Handle


 Public Handler Mdownloadhandler = new Handler () {@Override public void Handlemessage (msg) {PFile
      P
      String URL = msg.obj.toString ();
        Switch (msg.what) {case filedownloadhelper.message_start://start downloading p = new PFile ();
        P.path = mParent.mFileDownload.mDownloadUrls.get (URL);
        P.title = new File (P.path). GetName ();
        P.status = 0;
        p.file_size = 0; 
          if (Mdownloadadapter = = null) {Mdownloadadapter = new Fileadapter (getactivity (), New arraylist<pfile> ());
          Mdownloadadapter.add (P, URL);
          Mtemplistview.setadapter (Mdownloadadapter);
        Mtemplistview.setvisibility (view.visible);
          else {mdownloadadapter.add (P, URL);
        Mdownloadadapter.notifydatasetchanged ();
      } break;
        Case filedownloadhelper.message_progress://is downloading p = mdownloadadapter.getitem (URL);
        P.temp_file_size = MSG.ARG1;
P.file_size = MSG.ARG2;        int status = (int) ((MSG.ARG1 * 1.0/msg.arg2) * 10);
        if (status >) status = 10;
        P.status = status;
        Mdownloadadapter.notifydatasetchanged ();
      Break
        Case filedownloadhelper.message_stop://Download End p = mdownloadadapter.getitem (URL);
        Filebusiness.insertfile (Getactivity (), p);
      Break
        Case FileDownloadHelper.MESSAGE_ERROR:Toast.makeText (getactivity (), URLs, Toast.length_long). Show ();
      Break
    Super.handlemessage (msg);  }
  };Public Handler mDownloadHandler = new Handler() {
@ Override
Public void handleMessage(Message MSG) {
PFile p;
The String url = MSG. Obj. ToString ();
The switch (MSG. What) {
Case FileDownloadHelper. MESSAGE_START: / / download
P = new PFile ();
P.p. Ath = mParent mFileDownload. MDownloadUrls. Get (url);
P.t itle = new File (p.p ath). The getName ();
P. tatus = 0;
P.f ile_size = 0;
If (mDownloadAdapter == null) {
MDownloadAdapter = new FileAdapter(getActivity(), new ArrayList());</pfile>
MDownloadAdapter. Add (p, url);
MTempListView. SetAdapter (mDownloadAdapter);
MTempListView. SetVisibility (the VISIBLE);
} else {
MDownloadAdapter. Add (p, url);
MDownloadAdapter. NotifyDataSetChanged ();
}
Break;
Case FileDownloadHelper. MESSAGE_PROGRESS: / / is being downloaded
P = mDownloadAdapter. The getItem (url);
P.t emp_file_size = MSG. Arg1;
P.f ile_size = MSG. Arg2;
Int status = (int) (MSG. Arg1 * 1.0 / MSG. Arg2) * 10);
If (status > 10)
Status = 10;
P. tatus = status;
MDownloadAdapter. NotifyDataSetChanged ();
Break;
Case FileDownloadHelper. MESSAGE_STOP: / / end of download
P = mDownloadAdapter. The getItem (url);
FileBusiness. InsertFile (getActivity (), p);
Break;
Case FileDownloadHelper. MESSAGE_ERROR:
Toast. MakeText (getActivity (), url, Toast. LENGTH_LONG), show ();
Break;
}
Super. HandleMessage (MSG);
}
};


Code Description:



A. Mtemplistview is new and is hidden by default, see the Project Code Layout section.
B. Download process: Start (show Mtemplistview)-> downloading (update progress picture and size)-> finish (into trousers)



Dialog


If (FileUtils isVideoOrAudio (url)) {
Dialog = new alertdialog.builder (getActivity()).seticon (android.r.rawable.btn_star).settitle (" play/download ").setmessage (url).setpositivebutton (" play ", new OnClickListener() {
@ Override
Public void onClick(DialogInterface dialog, int which) {
Intent Intent = new Intent (getActivity (), VideoPlayerActivity. Class);
Intent. PutExtra (" path ", url);
StartActivity (intent);
}
}). SetNeutralButton (" download ", new OnClickListener() {
@ Override
Public void onClick(DialogInterface dialog, int which) {
MainFragmentActivity activity = (MainFragmentActivity) getActivity();
Activity. MFileDownload. NewDownloadFile (url);
Toast.maketext (getActivity(), "downloading.." + fileutils.geturlfilename (url) + "to see progress from local video!" Toast), LENGTH_LONG), show ();
}
}). SetNegativeButton (" cancel ", null). Create ();
Dialog. The show ();
Return true;
} 


Third, download



After this section, the code is no longer available for download, please move to Google Code:



Http://code.google.com/p/android-oplayer



The above is the Android Vitamio development player download video player data collation, there is a need to develop Android player friends can refer to.


Related Article

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.