安卓DownloadManager下载视频并用VideoView播放

文章目录

      • 需要添加的权限
      • DownloadManager下载
      • VideoView播放

需要添加的权限

	<uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

DownloadManager下载

public void downAD(String URI){
	//URI为视频下载地址,如:http://img.tukuppt.com/video_show/3987418/00/02/84/5b9556857f5d9.mp4
	String serviceStr = Content.DOWN_SERVICE;
	DownloadManager downloadManager = (DownloadManager) getBaseContext().getSystemService(serviceStr);
	Uri uri = Uri.parse(URI);
	DownloadManager.Request request = new DownloadManager.Request(uri);
	//通知栏设置
	request.setTitle("视频下载");
	request.setDescription("测试");
	//下载至外部储存,路径为:/storage/emulated/0/Android/data/你的安卓包名/files/download/广告.mp4(广告.mp4为下载文件命名)
	request.setDestinationInExternalFilesDir(getApplicationContext(), Environment.DIRECTORY_DOWNLOADS,"广告"+".mp4");
	request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
	reference = downloadManager.enqueue(request);
	//设置监听器
    completeReceiver = new CompleteReceiver();
    IntentFilter filter = new IntentFilter();
    filter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
    filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
    registerReceiver(completeReceiver,filter);
}
public class CompleteReceiver extends BroadcastReceiver{
       @Override
       public void onReceive(Context context, Intent intent) {
          String action = intent.getAction();
          if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){
              Toast.makeText(getApplicationContext(),"下载完成",Toast.LENGTH_SHORT).show();
              PlayAD();
          }
          if (action.equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)){
               downloadManager.remove((Long)reference);
          }
       }
   }

DownloadManager其他相关资料
函数直接调用,下载成功后可在手机“/Android/data/你的安卓包名/files/download/广告.mp4”目录下查看

VideoView播放

public void PlayAD(){
	//getExternalFilesDir(null).getPath()获取的路径为:/storage/emulated/0/Android/data/安卓包名/files
	String adPath = getExternalFilesDir(null).getPath()+"/Download/广告.mp4";
	video.setVideoPath(adPath);
	video.start();
	//循环播放
	video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
		public void onPrepared(MediaPlayer mediaPlayer){
			mediaPlayer.start();
			mediaPlayer.setLooping(true);
		}
	}
}

更多VideoView的用法

你可能感兴趣的:(安卓DownloadManager下载视频并用VideoView播放)