简单的视频下载
实现简单的视频下载!
1.效果图
2加入权限
3.上代码
package demo.cdy.com.myvitamiodemo;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class DownLoadActivity extends AppCompatActivity {
private Button button;
private TextView mTextView;
private CompleteReceiver completeReceiver;
private DownloadManager downloadManager;
long reference;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_download);
button = (Button)findViewById(R.id.button);
mTextView = (TextView)findViewById(R.id.textView);
//下载任务
String serviceString = Context.DOWNLOAD_SERVICE;
//直接使用系统的下载管理器。是不是非常方便
downloadManager = (DownloadManager)getBaseContext().getSystemService(serviceString);
//下载
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = Uri.parse("http://www.midea.com/video/masvod/public/2015/02/28/20150228_14bcec18032_r1_800k.mp4");
DownloadManager.Request request =new DownloadManager.Request(uri);
//通知栏的标题
request.setTitle("视频下载");
//显示通知栏的说明
request.setDescription("测试的广告") ;
request.setVisibleInDownloadsUi(true ) ;
//下载到那个文件夹下,以及命名
request.setDestinationInExternalFilesDir(getApplicationContext(), Environment.DIRECTORY_DOWNLOADS ,"广告"+".mp4" );
//下载的唯一标识,可以用这个标识来控制这个下载的任务enqueue()开始执行这个任务
reference = downloadManager.enqueue(request);
}
});
//注册下载的广播监听
completeReceiver =new CompleteReceiver();
/** 注册下载监听的广播 **/
completeReceiver =new CompleteReceiver();
IntentFilter filter =new IntentFilter();
filter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
/** register download success broadcast **/
registerReceiver(completeReceiver,
filter);
}
//下载的状态广播接收
class CompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//下载完成之后监听
String action = intent.getAction();
//下载完成的监听
if(action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){
mTextView.setText("下载完成");
}
//点击通知栏,取消下载任务
if(action.equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)){
downloadManager.remove((Long)reference) ;
}
}
}
}
4.写xml布局
android:layout_width="match_parent"
android:layout_height="match_parent">
android:text="下载"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_weight="1"/>
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_weight="1"/>
网友评论