LocalDataUtils.java 6.28 KB
/*
 * Copyright (c) 2016 wugian.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.gimi.common.cinema.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
import com.gimi.common.cinema.model.Constant;
import com.gimi.common.cinema.model.SambaMsg;
import com.xgimi.gimicinema.BuildConfig;
import com.xgimi.gimicinema.activity.CinemaConfig;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.Random;


/**
 * Created by wugian on 2016/8/25
 */
public class LocalDataUtils {
    public static long SPACE_TIME = 24 * 60 * 60 * 1000;

    private Context context;

    private DbUpdateManger dbUpdateManger;
    private SharedPreferences sharedPreferences;
    private SambaMsg sambaMsg;
    private Handler handler = new Handler();

    public LocalDataUtils(Context context) {
        this.context = context;
        this.sharedPreferences = context.getSharedPreferences(Constant.XML_NAME, Context.MODE_PRIVATE);
        Handler dbHandler = new DbHandler(this);
        this.dbUpdateManger = new DbUpdateManger(context, dbHandler);
        this.sambaMsg = Utils.getSambaMsg(sharedPreferences);

    }

    public void updateDb() {
        long l = System.currentTimeMillis();
        long lastUpdateTime = sharedPreferences.getLong("db-last-update-time-db", 0);
        if (lastUpdateTime == 0 || l - lastUpdateTime > SPACE_TIME) {
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    if (NetStatusUtils.isNetworkConnected(context)) {
                        dbUpdateManger.insertLocalData();
                    }
                }
            }.start();
        }
    }

    private static class DbHandler extends Handler {

        private final WeakReference<LocalDataUtils> activity;

        public DbHandler(LocalDataUtils activity) {
            this.activity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            final LocalDataUtils utils = activity.get();
            if (utils != null) {
                switch (msg.what) {
                    case Constant.DB_INIT_START:
                        utils.toast("开始本地数据初始化");
                        long l = System.currentTimeMillis() + 15 * 60 * 1000;
                        SharedPreferences.Editor editor = utils.sharedPreferences.edit();
                        editor.putLong("db-last-update-time-db", l);
                        editor.apply();
                        break;
                    case Constant.DB_INIT_SUCCESS:
                        utils.toast("本地数据初始化成功" + msg.obj);
                        utils.dbUpdateManger.deleteMovieNotExits();
                        int delayMillis = ((new Random().nextInt(5) + 2) * 60 + new Random().nextInt(40)) * 1000;
                        LogUtils.d("server-db", "copy out in " + delayMillis);
                        utils.handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                LogUtils.d("server-db", "do copy");
                                utils.copyFile();
                            }
                        }, delayMillis);
                        break;
                    case Constant.DB_INIT_FAILURE:
                        utils.toast("本地数据初始化失败");//应该不可能
                        break;
                    case Constant.DB_INIT_DONE:
                        utils.toast("本地数据初始化完成");
                        break;
                    case Constant.DB_INIT_ZERO:
                        utils.toast("本地数据为空 ");
                        break;
                }
            }
        }
    }

    private void toast(String str) {
        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
    }

    /**
     * 复制单个文件,如果需要的话将db文件复制到特定目录下面,以便其他机器共用
     */
    public void copyFile() {
        String oldPath = "/data/data/com.xgimi.gimicinema/databases/xgimi_cinema_movie.db";
        String newPath = sambaMsg.getLocalPath() + "xgimi_cinema_movie.db";

        if (BuildConfig.MACHINE_TYPE.equals("himedia")) {
            newPath = CinemaConfig.BASIC_ROOT + "/xgimi_cinema_movie.db";
        }
        if (new File(oldPath).length() < 50 * 1024) {
            return;
        }
        File file = new File(newPath);
        if (file.exists()) {
            file.delete();
        }
        try {
            Thread.sleep(2 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            int byteRead;
            int byteSum = 0;
            File newFile = new File(newPath);
            if (!newFile.exists()) {
                newFile.createNewFile();
            }
            File oldFile = new File(oldPath);
            if (oldFile.exists()) { //文件存在时
                byte[] buffer = new byte[1024];
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                while ((byteRead = inStream.read(buffer)) != -1) {
                    byteSum += byteRead; //字节数 文件大小
                    System.out.println(byteSum);
                    fs.write(buffer, 0, byteRead);
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }
    }
}