Service 和 BroadcastReceiver下载播放视频

利用广播接收器和service下载简短的视频并播放

布局部分:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.syc.intentservice.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="download"
        android:text="下载视频"/>
    <VideoView
        android:id="@+id/vv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

MainActivity部分

package com.lt.intentservice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {

    //private ImageView ivShow;
    private MyReceiver mReceiver;
    private VideoView vv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        vv = (VideoView) findViewById(R.id.vv);


    }

    @Override
    protected void onStart() {
        super.onStart();
        mReceiver = new MyReceiver();
        IntentFilter filter = new IntentFilter("succeed");
        registerReceiver(mReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
    }

    public void download(View view) {
        Intent intent = new Intent(this, DownService.class);
        startService(intent);
    }

    //广播接收器
    class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("succeed".equals(action)) {

                String path = SDUtil.getSDPath()+"/video/mv.mp4";
                vv.setVideoPath(path);
                MediaController controller = new MediaController(context);
                vv.setMediaController(controller);
                vv.start();
                }
            }
        }
    }

DownServicer

package com.lt.intentservice;

import android.app.IntentService;
import android.content.Intent;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 类描述:
 * 创建人:世Gai第一涛
 * 创建时间:16/9/8 16:25
 * 备注:
 */
public class DownService extends IntentService {

    //private String path = "http://pimg1.126.net/movie/product/movie/147193589241710760_520_692_webp.jpg";
    private String path = "http://flv.bn.netease.com/videolib3/1608/26/kbGDc9442/HD/kbGDc9442-mobile.mp4";
    //必须要有一个无参的构造方法!
    public DownService() {
        super("");
    }

    //处理intent.该方法属于worker thread.
    //当该方法把所有的intent处理完成后,会自动停止自身,不需要我们手动调用stopSelf()方法.
    @Override
    protected void onHandleIntent(Intent intent) {
        try {
            //下载
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() == 200) {

                InputStream is = conn.getInputStream();

                //转换成字节码
                int len;
                byte[] buffer = new byte[1024];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                while ((len = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                    baos.flush();
                }

                //保存电影
                boolean result = SDUtil.saveData("mv.mp4",baos.toByteArray());

                if (result) {


                    Intent succeedIntent = new Intent("succeed");
                    sendBroadcast(succeedIntent);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

SD工具类

package com.lt.intentservice;

import android.os.Build;
import android.os.Environment;
import android.os.StatFs;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 类描述:
 * 创建人:世Gai第一涛
 * 创建时间:16/8/25 14:31
 * 备注:
 */
public class SDUtil {

    public static final String STORAGE_PATH = "video";

    //判断外部存储设备是否已挂载
    public static boolean isMounted() {
        //得到外部存储设备中DCIM这个公共文件夹的路径
        //Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    //获取SD根路径
    public static String getSDPath() {
        if (isMounted()) {
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        }
        return null;
    }

    //计算总大小
    public static long getSDTotalSize() {
        if (isMounted()) {
            //获取某个文件的大小.
            StatFs stat = new StatFs(getSDPath());
            //判断API的版本.
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                //获取总大小的方法
                // stat.getTotalBytes();
                //机械硬盘---->盘片--->扇区
                //磁道;机械臂;
                //获取块的数量
                //int blockCount = stat.getBlockCount();
                long blockCount = stat.getBlockCountLong();
                //获取块的大小
                //int blockSize = stat.getBlockSize();
                long blockSize = stat.getBlockSizeLong();
                return blockCount * blockSize / 1024 / 1024;
            }
        }
        return 0;
    }

    //计算可用空间
    public static long getSDFreeSize() {
        if (isMounted()) {
            //获取某个文件的大小.
            StatFs stat = new StatFs(getSDPath());
            //判断API的版本.
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                //获取可用空间总大小的方法
                //stat.getAvailableBytes();
                //机械硬盘---->盘片--->扇区
                //磁道;机械臂;
                //获取块的数量
                //int blockCount = stat.getBlockCount();
                long blockCount = stat.getAvailableBlocksLong();
                //获取块的大小
                //int blockSize = stat.getBlockSize();
                long blockSize = stat.getBlockSizeLong();
                return blockCount * blockSize / 1024 / 1024;
            }
        }
        return 0;
    }

    //存储数据
    public static boolean saveData(String fileName, byte[] data) {
        if (isMounted()) {
            String path = getSDPath() + File.separator + STORAGE_PATH;
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }

            try {
                FileOutputStream fileOut = new FileOutputStream(new File(file, fileName));
                fileOut.write(data);
                fileOut.close();
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    //读取信息
    public static byte[] readData(String fileName) {
        if (isMounted()) {
            String path = getSDPath() + File.separator + STORAGE_PATH;
            File file = new File(path);
            if (file.exists()) {
                try {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    FileInputStream fileIn = new FileInputStream(new File(path, fileName));
                    int len = 0;
                    byte[] buffer = new byte[1024];
                    while ((len = fileIn.read(buffer)) != -1) {
                        out.write(buffer, 0, len);
                        out.flush();
                    }

                    fileIn.close();
                    byte[] data = out.toByteArray();
                    out.close();
                    return data;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}

清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.syc.intentservice">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <service android:name=".DownService"/>
    </application>

</manifest>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值