DownLoadService.java 7.98 KB
package com.cnlive.downloadfile.download.limit;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Config;
import android.widget.Toast;

import com.cnlive.downloadfile.AudioDialogActivity;
import com.cnlive.downloadfile.MyApplication;
import com.cnlive.downloadfile.R;
import com.cnlive.downloadfile.download.util.NetWorkUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import static com.cnlive.downloadfile.download.util.CheckNetworkStatusChangeListener.Status.TYPE_MOBILE;
import static com.cnlive.downloadfile.download.util.CheckNetworkStatusChangeListener.Status.TYPE_UN_NETWORK;
import static com.cnlive.downloadfile.download.util.CheckNetworkStatusChangeListener.Status.TYPE_WIFI;

/**
 * 下载服务
 */
public class DownLoadService extends Service {
    private NetConnectionReceiver netConnectionReceiver;
    private DownloadInfo info = null;
    public static final String ACTION_START = "ACTION_START";
    public static final String ACTION_WAITING = "ACTION_WAITING";
    public static final String ACTION_PAUSE = "ACTION_PAUSE";
    public static final String ACTION_ALLPAUSE = "ACTION_ALLPAUSE";
    public static final String ACTION_ALLSTART = "ACTION_ALLSTRAT";
    public static final String ACTION_DELECT = "ACTION_DELECT";
    public static final String ACION_CLEAR = "ACION_CLEAR";
    private String isNet;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //判断Intent的值,获得Activity传来的参数
        if(intent != null){
            info = (DownloadInfo) intent.getSerializableExtra("fileUrl");
        }else {
            return super.onStartCommand(intent, flags, startId);
        }

        if(intent.getAction().equals(ACTION_DELECT)){
            //取消
            mHandle.obtainMessage(4, info).sendToTarget();
        }else if(intent.getAction().equals(ACION_CLEAR)){
            //清空
            mHandle.obtainMessage(5).sendToTarget();
        }

        if(intent.getStringExtra("isNet") != null){
            showData(intent.getAction(),info);
            return super.onStartCommand(intent, flags, startId);
        }
        if(NetWorkUtil.getNetworkConnectionType(this).equals(TYPE_UN_NETWORK)){
            Toast.makeText(this,"无网络",Toast.LENGTH_SHORT).show();
            return super.onStartCommand(intent, flags, startId);
        }

        if(NetWorkUtil.getNetworkConnectionType(this).equals(TYPE_WIFI)){
            showData(intent.getAction(),info);
        }

        if(NetWorkUtil.getNetworkConnectionType(this).equals(TYPE_MOBILE)){
            //弹框...保存用户习惯,拒绝或者是允许,允许的话是仅允许一次还是都允许
            tipClick(intent.getAction(),info);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        netConnectionReceiver = new NetConnectionReceiver();
        registerReceiver(netConnectionReceiver, filter);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netConnectionReceiver);
    }

    //用于Service和MyThread之间的通信
    @SuppressLint("HandlerLeak")
    Handler mHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            DownloadInfo info = (DownloadInfo) msg.obj;
            switch (msg.what) {
                case 0:
                    //启动一个下载任务
                    DownloadLimitManager.getInstance().download(info);
                    break;
                case 1://暂停一个
                    DownloadLimitManager.getInstance().pauseDownload(info,false);
                    break;
                case 2://全部暂停
                    DownloadLimitManager.getInstance().pauseAllDownload();
                    break;
                case 3:
                    DownloadLimitManager.getInstance().startAllDownload();
                    break;
                case 4:
                    DownloadLimitManager.getInstance().cancelDownload(info,true);
                    break;
                case 5:
                    DownloadLimitManager.getInstance().clearDownload();
                    break;
                case 6:
                    DownloadLimitManager.getInstance().pauseToWaitDownload(info);
                    break;
            }
        }
    };


    //子线程  获取文件长度
    class MyThread extends Thread {
        private DownloadInfo fileInfo = null;
        private int num = 0;
        public MyThread(DownloadInfo fileInfo,int num) {
            this.fileInfo = fileInfo;
            this.num = num;
        }
        public void run() {
            mHandle.obtainMessage(num, fileInfo).sendToTarget();
        }
    }


    public DownLoadService getService() {
        return DownLoadService.this;
    }

    public void tipClick(final String type, final DownloadInfo info) {
        AudioDialogActivity.startActivity(DownLoadService.this,type,info);
    }

    public void showData(String type,DownloadInfo info){
        if (type.equals(ACTION_START)) {
            //启动初始化线程
            new MyThread(info,0).start();
        }else if(type.equals(ACTION_PAUSE)){
            //暂停
            mHandle.obtainMessage(1, info).sendToTarget();
        }else if(type.equals(ACTION_ALLPAUSE)){
            //全部暂停
            mHandle.obtainMessage(2).sendToTarget();
        }else if(type.equals(ACTION_ALLSTART)){
            //全部开始
            new MyThread(info,3).start();
        }else if(type.equals(ACTION_WAITING)){
            mHandle.obtainMessage(6,info).sendToTarget();
        }
    }

    private class NetConnectionReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            NetworkInfo wifiNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            if (!wifiNetInfo.isConnected()) {
                //网络断开
                DownloadLimitManager.getInstance().pauseErrorDownload();
            } else {
                //网络连接
                //启动初始化线程
                List<DownloadInfo> list = MyApplication.getInstances().getDaoSession().loadAll(DownloadInfo.class);
                DownloadInfo info = null;
               for(int i = 0;i < list.size();i++){
                   if(list.get(i).getDownloadStatus().equals(DownloadStatus.DOWNLOAD)){
                       info = list.get(i);
                   }else if(list.get(i).getDownloadStatus().equals(DownloadStatus.DOWNLOAD_NET_PAUSE)){
                       list.get(i).setDownloadStatus(DownloadStatus.DOWNLOAD_WAIT);
                       EventBus.getDefault().post(list.get(i));//通知页面
                       MyApplication.getInstances().getDaoSession().update(list.get(i));
                   }
               }
               if(DownloadLimitManager.getInstance().getCurremtDownload() != null){
                   info = DownloadLimitManager.getInstance().getCurremtDownload();
               }
               if(info != null){
                   new MyThread(info,0).start();
               }else {
                   DownloadLimitManager.getInstance().downNext();
               }
            }
        }
    }
}