com.ericsun.duom.DuoMApplication.java Source code

Java tutorial

Introduction

Here is the source code for com.ericsun.duom.DuoMApplication.java

Source

/*
 * MIT License
 *
 * Copyright (c) 2016 Eric
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.ericsun.duom;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v4.view.ViewCompat;

import com.ericsun.duom.Bean.BaseFile;
import com.ericsun.duom.Database.DbService;
import com.ericsun.duom.Framework.Application.BaseApplication;
import com.ericsun.duom.Framework.Network.MySSLSocketFactory;
import com.ericsun.duom.Utils.FileUtils;
import com.liulishuo.filedownloader.FileDownloadConnectListener;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.ArrayList;

import javax.net.ssl.SSLSocketFactory;

import cn.finalteam.filedownloaderfinal.DbUpgradeListener;
import cn.finalteam.filedownloaderfinal.DownloaderManager;
import cn.finalteam.filedownloaderfinal.DownloaderManagerConfiguration;
import cn.finalteam.filedownloaderfinal.FileDownloaderCallback;
import cn.finalteam.filedownloaderfinal.FileDownloaderModel;
import cn.finalteam.okhttpfinal.OkHttpFinal;
import cn.finalteam.okhttpfinal.OkHttpFinalConfiguration;
import cn.finalteam.okhttpfinal.https.SkirtHttpsHostnameVerifier;
import cn.finalteam.toolsfinal.StorageUtils;
import okhttp3.Cache;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Response;

/**
 * Created by Eric on 16/8/25.
 */
public class DuoMApplication extends BaseApplication {

    public DbService mDbService;
    private static DuoMApplication app;
    public final String rootDir = "DuoMPictures";
    public String root = null;
    private int unFinishCount = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        initHttpFinal();
        mDbService = new DbService(getApplicationContext());

        initDownloaderManager();
    }

    public static DuoMApplication app() {
        return app;
    }

    public void initHttpFinal() {
        OkHttpFinalConfiguration.Builder builder = new OkHttpFinalConfiguration.Builder();
        builder.setFollowSslRedirects(true);
        builder.setRetryOnConnectionFailure(true);
        builder.setTimeout(22000);
        builder.setSSLSocketFactory(createSocketFactory());
        builder.setHostnameVerifier(new SkirtHttpsHostnameVerifier());
        builder.setNetworkInterceptors(createNetworkInterceptor());
        Headers.Builder headerBuilder = new Headers.Builder();
        createCommonHeader(headerBuilder);
        builder.setCommenHeaders(headerBuilder.build());
        Cache mCache = new Cache(getApplicationContext().getCacheDir(), 20 * 1024 * 1024);
        builder.setCache(mCache);

        OkHttpFinal.getInstance().init(builder.build());
    }

    public String addChannelId() {
        ApplicationInfo appInfo = null;
        try {
            appInfo = getApplicationContext().getPackageManager()
                    .getApplicationInfo(getApplicationContext().getPackageName(), PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (null != appInfo && null != appInfo.metaData) {
            return "" + appInfo.metaData.get("UMENG_CHANNEL");
        }
        return "";
    }

    private void createCommonHeader(Headers.Builder headerBuilder) {
        headerBuilder.add("platform", "android");
        headerBuilder.add("appVersion", BuildConfig.VERSION_NAME);
        headerBuilder.add("Accept", "*/*");
        headerBuilder.add("Content-Type", "text/html;charset=utf-8");
        headerBuilder.add("x-channelId", addChannelId());
    }

    private ArrayList<Interceptor> createNetworkInterceptor() {
        ArrayList<Interceptor> interceptorList = new ArrayList<>();
        interceptorList.add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response response = chain.proceed(chain.request());

                if (null != response) {
                    int errorCode = response.code();
                    if (errorCode >= 200 && errorCode < 300) {//OK
                        //add your code or nothing
                    } else if (errorCode == 401) {//unauthenticated
                        Intent intent = new Intent(Configure.UNAUTHEN);
                        getApplicationContext().sendBroadcast(intent);

                    } else if (errorCode >= 400 && errorCode < 500) {//CLIENT error

                    } else if (errorCode >= 500 && errorCode < 600) {//server error

                    } else {//Unexpected response 
                    }
                }
                return response;
            }
        });

        return interceptorList;
    }

    private SSLSocketFactory createSocketFactory() {
        SSLSocketFactory sf = null;
        try {
            MySSLSocketFactory sslFy = new MySSLSocketFactory(null);
            sf = sslFy.sslContext.getSocketFactory();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            e.printStackTrace();
        }

        return sf;
    }

    public void initDownloaderManager() {
        //?
        root = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + rootDir;
        FileUtils.createDirFile(root);

        final DownloaderManagerConfiguration.Builder dmBulder = new DownloaderManagerConfiguration.Builder(this)
                .setMaxDownloadingCount(5) //??[1-100]
                //                .setDbExtField(...) //??
                .setDbVersion(1)//??
                .setDbUpgradeListener(new DbUpgradeListener() {
                    @Override
                    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

                    }
                }) //??
                .setDownloadStorePath(root); //?
        //???

        DownloaderManager.getInstance().init(dmBulder.build());//??

        DownloaderManager.getInstance().addServiceConnectListener(new FileDownloadConnectListener() {
            @Override
            public void connected() {

                final ArrayList<BaseFile> unFinishedFiles = DuoMApplication.app().mDbService.fetchUnDownloadFiles();
                if (null == unFinishedFiles || unFinishedFiles.size() == 0)
                    return;
                unFinishCount = unFinishedFiles.size();
                for (BaseFile file : unFinishedFiles) {
                    String fileName = Uri.parse(file.getNetAddress()).getLastPathSegment();
                    fileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".data";
                    FileDownloaderModel downloadModel = DownloaderManager.getInstance()
                            .addTask(file.getNetAddress(), file.getDirAddress() + File.separator + fileName);
                    DownloaderManager.getInstance().startTask(downloadModel.getId(), downloadCallback);
                }
            }

            @Override
            public void disconnected() {
                DownloaderManager.getInstance().onDestroy();
            }
        });
    }

    private FileDownloaderCallback downloadCallback = new FileDownloaderCallback() {
        @Override
        public void onFinish(int downloadId, String path) {
            super.onFinish(downloadId, path);
            DuoMApplication.app().mDbService.updateFileByDownloadId(downloadId, path);
            subUnFinishCount();
            sendBroadcast(new Intent(Configure.UPDATE_DOWNLOAD_TASK));
        }

        @Override
        public void onStart(int downloadId, long soFarBytes, long totalBytes, int preProgress) {

            super.onStart(downloadId, soFarBytes, totalBytes, preProgress);
        }

        @Override
        public void onStop(int downloadId, long soFarBytes, long totalBytes, int progress) {
            super.onStop(downloadId, soFarBytes, totalBytes, progress);
        }

        @Override
        public void onProgress(int downloadId, long soFarBytes, long totalBytes, long speed, int progress) {
            super.onProgress(downloadId, soFarBytes, totalBytes, speed, progress);
        }
    };

    public void downLoadFiles(String dirPath, ArrayList<BaseFile> objs) {
        if (null != objs && objs.size() == 0)
            return;
        for (BaseFile obj : objs) {
            String fileName = Uri.parse(obj.getNetAddress()).getLastPathSegment();
            fileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".data";
            obj.setDirAddress(dirPath);
            FileDownloaderModel downloadModel = DownloaderManager.getInstance().addTask(obj.getNetAddress(),
                    dirPath + File.separator + fileName);
            obj.setDownloadId(downloadModel.getId());
            DuoMApplication.app().mDbService.insertFile(obj);
        }
        addUnFinishCount(objs.size());
        sendBroadcast(new Intent(Configure.UPDATE_DOWNLOAD_TASK));
        for (BaseFile obj : objs) {
            DownloaderManager.getInstance().startTask((int) obj.getDownloadId(), downloadCallback);
        }
    }

    public int getUnFinishCount() {
        return unFinishCount;
    }

    public void subUnFinishCount() {
        synchronized (this) {
            unFinishCount -= 1;
        }
    }

    public void addUnFinishCount(int count) {
        synchronized (this) {
            unFinishCount += count;
        }

    }

    public void setUnFinishCount(int unFinishCount) {
        this.unFinishCount = unFinishCount;
    }
}