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>
發佈了30 篇原創文章 · 獲贊 17 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章