Android上传本地数据,下载服务器数据,检测版本更新

添加权限:

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

一:数据库工具类DBOpenHelper,导入SQL文件的方法

package com.example.upload.tools;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class DBOpenHelper extends SQLiteOpenHelper {
    private SQLiteDatabase db;

    public DBOpenHelper(Context context) {
        super(context, "quinto", null, 1);
        db = getReadableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS user(" +
                "_id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "name TEXT," +
                "password TEXT)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS user");
        onCreate(db);
    }

    /**
     * 导入sql文件
     * @param sqlName sql文件名称
     * @param context 上下文对象
     * @param sqlPlan 接口回调
     */
    public void importSql(String sqlName, Context context, SqlIntentPlan sqlPlan) {
        DBOpenHelper helper = new DBOpenHelper(context);
        SQLiteDatabase db = helper.getWritableDatabase();
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(context.openFileInput(sqlName)));
            String str;
            int allLine = 0;
            BufferedReader reader = new BufferedReader(new InputStreamReader(context.openFileInput(sqlName)));
            while ((str = reader.readLine()) != null) {
                allLine++;
            }
            int readLineNum = 0;
            StringBuffer buffer = new StringBuffer("");
            while ((str = bufferedReader.readLine()) != null) {
                readLineNum++;
                if (str.indexOf("<html>") > -1) {
                    sqlPlan.onSqlFailed("服务器连接失败,请选择正确的服务器!");
                    return;
                } else {
                    buffer.append(str);
                    if (str.indexOf("; --") > -1) {
                        db.execSQL(buffer.toString());
                        buffer = new StringBuffer("");
                        sqlPlan.SqlPlan(readLineNum * 100 / allLine);
                    }
                }
            }
            db.close();
            sqlPlan.onSqlSuccess(1);
        } catch (IOException e) {
            sqlPlan.onSqlFailed("文件导入错误!");
            Log.e("db-error", e.toString());
            return;
        } catch (SQLException e) {
            sqlPlan.onSqlFailed("导入数据错误!" + e.toString());
            Log.e("db-error", e.toString());
            return;
        }
    }

    public interface SqlIntentPlan {
        // 导入进度
        void  SqlPlan(int a);

        // 导入成功
        void onSqlSuccess(int b);

        // 导入异常
        void onSqlFailed(String e);
    }

}

二:网络请求接口类YLHttpClient ,get请求、post请求

package com.example.upload.tools;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.widget.Toast;

import com.example.upload.BaseActivity;
import com.example.upload.MainActivity;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 网络接口请求
 */
public class YLHttpClient {
    static YLHttpClient ylHttpClient = null;
    static OkHttpClient okHttpClient = null;

    private static String tokenStr = "";

    public static String getTokenStr() {
        return tokenStr;
    }

    public void setTokenStr(String tokenStr) {
        this.tokenStr = tokenStr;
    }

    public static YLHttpClient getDefaultYLHttpCline() {
        if (ylHttpClient == null) {
            ylHttpClient = new YLHttpClient();
        }
        return ylHttpClient;
    }

    public OkHttpClient okHttpClient() {
        return okHttpClient;
    }

    public YLHttpClient() {
        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).build();
        }
    }

    /**
     * post请求
     * @param currentActivity 上下文对象
     * @param url 接口请求地址
     * @param requestBody 传递的参数
     * @param typeData
     * @param httpCallBack 保存返回的结果
     */
    public void sendPostRequest(BaseActivity currentActivity, String url, RequestBody requestBody, Type typeData, HttpCallBack httpCallBack) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 是否连接USB
                boolean isUSBConnected = false;
                if (isUSBConnected) {
                    try {
                        Request request = new Request.Builder()
                                .url(url)
                                .addHeader("Authorization", tokenStr)
                                .build();
                        Response response = okHttpClient.newCall(request).execute();
                        responseHandel(currentActivity, response, typeData, httpCallBack);
                    } catch (IOException e) {
                        e.printStackTrace();
                        currentActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showMessage(currentActivity, "无法连接到服务器");
                            }
                        });
                    }
                } else {
                    // post请求的时候截取requestBody中的参数添加到url进行本地路由
                    String appendUri = "";
                    for (int i = 0; i < ((FormBody)requestBody).size(); i++) {
                        String key = ((FormBody) requestBody).encodedName(i);
                        String value = ((FormBody)requestBody).encodedValue(i);
                        if (i == 0) {
                            appendUri = "?" + key + "=" + value;
                        } else if (i > 0){
                            appendUri += "&" + key + "=" + value;
                        }
                    }
                }
            }
        }).start();
    }

    /**
     * get请求
     * @param currentActivity 上下文对象
     * @param url 接口请求地址
     * @param typeData
     * @param httpCallBack
     */
    public void sendGetRequest(BaseActivity currentActivity, String url, Type typeData, HttpCallBack httpCallBack) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 是否连接USB
                boolean isUSBConnected = false;
                if (!isUSBConnected) {
                    try {
                        Request request = new Request.Builder()
                                .url(url)
                                .addHeader("Authorization", tokenStr)
                                .build();
                        Response response = okHttpClient.newCall(request).execute();
                        responseHandel(currentActivity, response, typeData, httpCallBack);
                    } catch (IOException e) {
                        e.printStackTrace();
                        currentActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showMessage(currentActivity, "无法连接到服务器");
                            }
                        });
                    } catch (RuntimeException e) {
                        e.printStackTrace();
                        currentActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showMessage(currentActivity, "无法连接到服务器");
                            }
                        });
                    }
                }
            }
        }).start();
    }

    /**
     * 提示对话框
     * @param currentActivity 上下文对象
     * @param message 提示的内容
     */
    private void showMessage(BaseActivity currentActivity, String message) {
        View decorView = currentActivity.getWindow().getDecorView();
        // SYSTEM_UI_FLAG_FULLSCREEN表示全屏
        // 设置系统UI元素的可见性
        int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                View.SYSTEM_UI_FLAG_FULLSCREEN;
        uiFlags |= 0x00001000;
        decorView.setSystemUiVisibility(uiFlags);
        AlertDialog.Builder builder = new AlertDialog.Builder(currentActivity);
        builder.setTitle("提示");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                currentActivity.finish();
                dialog.dismiss();
            }
        });
        builder.setMessage(message);
        builder.show();
    }

    /**
     * 处理服务器返回结果
     * @param currentActivity 上下文对象
     * @param response 返回值
     * @param typeData
     * @param httpCallBack 保存返回的结果
     * @throws IOException
     */
    private void responseHandel(BaseActivity currentActivity, Response response, Type typeData, HttpCallBack httpCallBack) throws IOException {
        if (response.code() != 200) {
            currentActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // 更新UI
                    if (response.code() == 500) {
                        Toast.makeText(currentActivity, "服务器错误" + response.code(), Toast.LENGTH_LONG).show();
                    } else if (response.code() == 400) {
                        Toast.makeText(currentActivity, "网络请求错误" + response.code(), Toast.LENGTH_LONG).show();
                    } else if (response.code() == 403) {
                        Toast.makeText(currentActivity, "登录超时,请重新登录", Toast.LENGTH_LONG).show();
                        setTokenStr("");
                        currentActivity.startLoginActivity();

                    } else {
                        Toast.makeText(currentActivity, "错误" + response.code(), Toast.LENGTH_LONG).show();
                    }
                }
            });
        } else {
            String result = null;
            ResponseBody body = response.body();
            result = body.string();
            String sss = result;
            if (!YLHttpClient.validate(result)) {
                currentActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 更新UI
                        Toast.makeText(currentActivity, sss, Toast.LENGTH_LONG).show();
                        if (typeData.equals(String.class)) {
                            httpCallBack.callBack(response.code(), sss);
                        }
                    }
                });
                return;
            }
            JsonObject jsonObject = (JsonObject) new JsonParser().parse(result);
            if (jsonObject.get("success").getAsBoolean()) {
                Gson gson = new Gson();
                Object httpData = gson.fromJson(result, typeData);
                String str = result;
                currentActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        httpCallBack.callBack(response.code(), httpData);
                    }
                });
            } else {
                String msg = jsonObject.get("msg").getAsString();
                currentActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (currentActivity != null && (!currentActivity.getClass().equals(MainActivity.class))) {
                            currentActivity.finish();
                        }
                        Toast.makeText(currentActivity, msg, Toast.LENGTH_LONG).show();
                    }
                });
            }
        }
    }

    private static boolean validate(String jsonStr) {
        JsonElement jsonElement;
        try {
            jsonElement = new JsonParser().parse(jsonStr);
        } catch (Exception e) {
            return false;
        }
        if (jsonElement == null) {
            return false;
        }
        if (!jsonElement.isJsonObject()) {
            return false;
        }
        return true;
    }
}

三:文件下载工具类YLDownload 

package com.example.upload.tools;

import androidx.annotation.NonNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 文件下载工具类
 */
public class YLDownload {
    private static YLDownload download;
    private OkHttpClient okHttpClient;

    public YLDownload() {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
    }

    public static YLDownload getInstance() {
        if (download == null) {
            download = new YLDownload();
        }
        return download;
    }

    /**
     * 下载文件
     * @param url 下载地址
     * @param destFileDir 下载文件的目录
     * @param destFileName 文件名称
     * @param listener 下载接口
     */
    public void download(String url, String destFileDir, String destFileName, OnDownloadListener listener) {
        // 设置请求头,添加token
        Request request = new Request.Builder()
                .url(url)
                .build();
        // 异步请求
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                // 下载失败监听回调
                listener.onDownloadFailed(e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;

                // 储存下载文件的目录
                File dir = new File(destFileDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File file = new File(dir, destFileName);

                is = response.body().byteStream();
                long total = response.body().contentLength();
                fos = new FileOutputStream(file);
                long sum = 0;
                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                    sum += len;
                    int progress = (int) (sum * 1.0f / total * 100);
                    // 下载中更新进度条
                    listener.onDownloading(progress);
                }
                fos.flush();
                // 下载完成
                listener.onDownloadSuccess(file);

                if (is != null) {
                    is.close();
                }
                if (fos != null) {
                    fos.close();
                }
            }
        });
    }

    public interface OnDownloadListener {
        // 下载成功之后的文件
        void onDownloadSuccess(File file);

        // 下载进度
        void onDownloading(int progress);

        // 下载异常信息
        void onDownloadFailed(Exception e);
    }
}

四:数据上传工具类SqlUpload 

package com.example.upload.tools;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 上传本地数据文件
 */
public class SqlUpload {
    private static SqlUpload sqlUpload;

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    public static SqlUpload getInstance() {
        if (sqlUpload == null) {
            sqlUpload = new SqlUpload();
        }
        return sqlUpload;
    }

    /**
     * 上传数据库文件
     * @param url 服务器上传地址
     * @param context 上下文对象
     * @param upload 接口
     * @throws IOException
     */
    public void upLoad(String url, Context context, OnSqlUploadListener upload) throws IOException {
        // 判断是否是第一次拉取数据
        boolean isOne = getTable("表名", context);
        if (isOne) {
            upload.onUploadSuccess(1);
        } else {
            // 查询数据库中所有有增、删、改操作的记录,并将其保存
            DBOpenHelper helper = new DBOpenHelper(context);
            SQLiteDatabase db = helper.getReadableDatabase();
            List<Map> list = new ArrayList<>();

            // operation为记录数据增、删、改的字段,默认为0,新增1,修改2,删除3
            Cursor cursor1 = db.rawQuery("SELECT '保存图片的表名' tableType, * FROM '保存图片的表名' WHERE operation > 0", null);
            while (cursor1.moveToNext()) {
                Map<String, Object> map = new HashMap<>();
                String[] strings = cursor1.getColumnNames();
                for (int i = 0; i < strings.length; i++) {
                    String key = strings[i];
                    String value = cursor1.getString(cursor1.getColumnIndex(key));
                    map.put(key, value);
                }
                list.add(map);
            }
            cursor1.close();

            // 图片上传
            OkHttpClient client = new OkHttpClient();
            MediaType contentType = MediaType.parse("multipart/from-data");   // 上传文件的Content-Type
            for (Map map : list) {
                RequestBody fileBody = RequestBody.create(contentType, new File(map.get("file_path").toString()));  // 上传文件的请求体
                RequestBody requestBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("upload", new File(map.get("file_path").toString()).getName(), fileBody)
                        .addFormDataPart("busId", "")
                        .addFormDataPart("busType", "10000001")
                        .build();
                Request request = new Request.Builder()
                        .url(Consts.URL + Consts.upload)
                        .post(requestBody)
                        .build();
                String result = "";
                Response response = client.newCall(request).execute();
                ResponseBody responseBody = response.body();
                if (response.isSuccessful() && responseBody != null) {
                    result = responseBody.string();
                } else {
                    if (responseBody != null) {
                        result = responseBody.string();
                    }
                }
                Map maps = MapUtils.getStringToMap(result);
                map.put("file_url", maps.get("file_url").toString());
            }

            Cursor cursor2 = db.rawQuery("SELECT '表名1' tableType, * FROM '表名1' WHERE operation > 0", null);
            while (cursor2.moveToNext()) {
                Map<String, Object> map = new HashMap<>();
                String[] strings = cursor2.getColumnNames();
                for (int i = 0; i < strings.length; i++) {
                    String key = strings[i];
                    String value = cursor2.getString(cursor2.getColumnIndex(key));
                    map.put(key, value);
                }
                list.add(map);
            }
            cursor2.close();

            Cursor cursor3 = db.rawQuery("SELECT '表名2' tableType, * FROM '表名2' WHERE operation > 0", null);
            while (cursor3.moveToNext()) {
                Map<String, Object> map = new HashMap<>();
                String[] strings = cursor3.getColumnNames();
                for (int i = 0; i < strings.length; i++) {
                    String key = strings[i];
                    String value = cursor3.getString(cursor3.getColumnIndex(key));
                    map.put(key, value);
                }
                list.add(map);
            }
            cursor3.close();

            // 以此类推

            // 上传保存的数据
            YLHttpClient ylHttpClient = YLHttpClient.getDefaultYLHttpCline();
            Gson gson = new Gson();
            String json = gson.toJson(list);
            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("Authorization", YLHttpClient.getTokenStr())
                    .build();
            Response response = null;
            try {
                response = ylHttpClient.okHttpClient().newCall(request).execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (response.code() == 200) {
                upload.onUploading(100);
                upload.onUploadSuccess(1);
                Log.i("上传完成:", "upLoad: OK");
            } else {
                try {
                    upload.onUploadFailed("Unexpected code" + response);
                    throw new IOException("Unexpected code" + response);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 判断表是否存在
     * @param tableName
     * @param context
     * @return
     */
    public static boolean getTable(String tableName, Context context) {
        boolean table;
        DBOpenHelper helper = new DBOpenHelper(context);
        SQLiteDatabase db = helper.getReadableDatabase();
        // 查询表是否存在
        Cursor cursor = db.rawQuery("SELECT COUNT(1) FROM sqlite_master WHERE type = 'table' AND name = '" + tableName + "'", null);
        int num = 0;
        if (cursor != null && cursor.getCount() >= 1) {
            String[] cols = cursor.getColumnNames();
            while (cursor.moveToNext()) {
                for (String ColumnName : cols) {
                    num = cursor.getInt(cursor.getColumnIndex(ColumnName));
                }
            }
        }
        // num为0的时候表不存在
        if (num == 0) {
            table = false;
        } else {
            table = true;
        }
        return table;
    }

    public interface OnSqlUploadListener {
        // 上传成功
        void onUploadSuccess(int p);

        // 上传进度
        void onUploading(int plan);

        // 上传异常
        void onUploadFailed(String s);
    }
}

五:公共方法类BaseActivity

package com.example.upload;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

/**
 * 公共方法
 */
public class BaseActivity extends AppCompatActivity{
    // 本地时间和服务器时间差
    private long currentTime = 0;
    private long dTime = 0;
    // USB连接状态
    private static boolean isUSBConnected = false;
    private static BroadcastReceiver receiver = null;
    private static IntentFilter filter = null;
    // 是否是本地模式
    private static boolean localHost = false;

    public static boolean isLocalHost() {
        return localHost;
    }

    public static void setLocalHost(boolean localHost) {
        BaseActivity.localHost = localHost;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (receiver == null) {
            receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    if (action.equals("android.hardware.usb.action.USB_STATE")) {
                        boolean connected = intent.getExtras().getBoolean("connected");
                        if (connected) {
                            if (!isUSBConnected) {
                                isUSBConnected = true;
                                Toast.makeText(BaseActivity.this, "USB已连接", Toast.LENGTH_LONG).show();
                            }
                        } else {
                            if (isUSBConnected) {
                                isUSBConnected = false;
                                Toast.makeText(BaseActivity.this, "USB已断开", Toast.LENGTH_LONG).show();
                            }
                        }
                    }
                    context.unregisterReceiver(this);
                }
            };
        }
        if (filter == null) {
            filter = new IntentFilter();
            filter.addAction("android.hardware.usb.action.USB_STATE");
            registerReceiver(receiver, filter);
        }
    }

    public void startLoginActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
    }

    /**
     * 获取本地版本号名称
     * @param context 上下文对象
     * @return 本地版本号名称
     */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

    public long getCurrentTime() {
        long time = System.currentTimeMillis();
        currentTime = time + dTime;
        return currentTime;
    }

    public void setDateTime(String format) {
        SharedPreferences.Editor editor = getSharedPreferences("format", MODE_PRIVATE).edit();
        editor.putString("dTime", format);
        editor.commit();
    }

    public void setTime(long time) {
        dTime = time;
        SharedPreferences.Editor editor = getSharedPreferences("lock", MODE_PRIVATE).edit();
        editor.putLong("dTime", time);
        editor.commit();
    }

    /**
     * 获取当前USB连接状态
     * @return
     */
    public static boolean getUSBConnected() {
        return isUSBConnected;
    }
}

六:保存从服务器获取的数据类

AppFile:

package com.example.upload.entity;

import java.io.Serializable;

public class AppFile implements Serializable {
    private static final long serialVersionUID = 7975433571399514905L;

    public Long fileId = 0L;    // 文件ID
    public Long verId = 0L;     // 版本ID
    public Long appId = 0L;     // 程序ID
    public String fileName = "";      // 原文件ID
    public String filePath = "";      // 客户端相对exe文件夹的路径,不包含文件名
    public String fileVar = "";       // 文件版本
    public Long fileType = 0L;        // 文件类型:1整体压缩包,2解压后的文件,3升级文件
    public Long fileSize = 0L;        // 文件大小:字节byte
    public String fileUrl = "";       // 客户端相对exe文件夹的路径,不包含文件名
    public String fileMds = "";       // MDS
    public Long timeCreate = 0L;      // 新增时间
}

HttpData:

package com.example.upload.entity;

public class HttpData<T> {
    public boolean success = false;
    public String msg = "";
    public T data = null;
}

LoginResultData:

package com.example.upload.entity;

public class LoginResultData<T> {
    public T sysAccount = null;
    public String href = "";
    public String token = "";

    @Override
    public String toString() {
        return "sysAccount=" + sysAccount + ", href=" + href + ", token=" + token;
    }
}

ServerTime:

package com.example.upload.entity;

public class ServerTime {
    public long t1;
    public long t2;
    public long t3;
}

SysAccount:

package com.example.upload.entity;

public class SysAccount {
    public Long accId;
    public String account;
    public Long accType;
    public Long userId;
    public Long deptId;
    public Long status;
    public Long userCreate;
    public String timeCreate;
    public Long userUpdate;
    public String accTypeCN;
    public String statusCN;
    public String userName;
    public String orgName;
}

七:工具类

Consts :

package com.example.upload.tools;

public class Consts {
    public static String URL = "";

    // 登录
    public static String loginPath = "";

    // 获取最新版本
    public static String getVersion = "";

    public static String appCode = "";

    public static String mePath = "";

    // 获取服务器的时间
    public static String getTime = "";

    // 上传本地数据到服务器的地址
    public static String takeNewData = "";

    // 获取服务器数据库sql文件
    public static String getNewData = "";

    // 图片上传地址
    public static String upload = "";
}

HttpCallBack:

package com.example.upload.tools;

public interface HttpCallBack<T> {
    void callBack(int statueCode, T httpData);
}

 MapUtils :

package com.example.upload.tools;

import java.util.HashMap;
import java.util.Map;

/**
 * 解析信息
 */
public class MapUtils {
    public static Map<String, String> getStringToMap(String str) {
        // 判断str是否有值
        if (str == null || str.equals("")) {
            return null;
        }
        // 去掉大括号
        str = str.replace("{", "");
        str = str.replace("}", "");
        // 根据“,”截取
        String[] strings = str.split(",");
        // 设置HashMap长度
        int mapLength = strings.length;
        // 判断HashMap的长度是否是2的幂
        if ((strings.length % 2) != 0) {
            mapLength = mapLength + 1;
        }
        Map<String, String> map = new HashMap<>();
        // 循环加入map集合
        for (int i = 0; i < strings.length; i++) {
            // 截取一组字符串
            String[] strArray = strings[i].split(":");
            // strArray[0]为key strArray[1]为value
            map.put(strArray[0].substring(1, strArray[0].length() - 1), strArray[1].substring(1, strArray[1].length() - 1));
        }
        return map;
    }
}

八:登录界面

package com.example.upload;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import com.example.upload.entity.HttpData;
import com.example.upload.entity.LoginResultData;
import com.example.upload.entity.SysAccount;
import com.example.upload.tools.Consts;
import com.example.upload.tools.HttpCallBack;
import com.example.upload.tools.YLHttpClient;
import com.google.gson.reflect.TypeToken;

import okhttp3.FormBody;
import okhttp3.RequestBody;

public class LoginActivity extends BaseActivity {
    private EditText text_name;
    private EditText text_pwd;

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

        text_name = findViewById(R.id.text_name);
        text_pwd = findViewById(R.id.text_pwd);
    }

    public void Login(View view) {
        BaseActivity.setLocalHost(false);
        YLHttpClient client = YLHttpClient.getDefaultYLHttpCline();
        RequestBody requestBody = new FormBody.Builder()
                .add("loginName",text_name.getText().toString().trim())
                .add("loginPwd", text_pwd.getText().toString().trim())
                .build();
        client.sendPostRequest(LoginActivity.this, Consts.URL + Consts.loginPath, requestBody, new TypeToken<HttpData<LoginResultData<SysAccount>>>() {
        }.getType(), new HttpCallBack<HttpData<LoginResultData<SysAccount>>>() {
            @Override
            public void callBack(int statueCode, HttpData<LoginResultData<SysAccount>> httpData) {
                if (statueCode == 200) {
                    startActivity(new Intent(LoginActivity.this, ModelActivity.class));
                }
            }
        });
    }
}

九:选择登录模式、同步数据界面

package com.example.upload;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.example.upload.entity.AppFile;
import com.example.upload.entity.HttpData;
import com.example.upload.entity.ServerTime;
import com.example.upload.tools.Consts;
import com.example.upload.tools.DBOpenHelper;
import com.example.upload.tools.HttpCallBack;
import com.example.upload.tools.SqlUpload;
import com.example.upload.tools.YLDownload;
import com.example.upload.tools.YLHttpClient;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;

import okhttp3.FormBody;
import okhttp3.RequestBody;

public class ModelActivity extends BaseActivity implements YLDownload.OnDownloadListener, DBOpenHelper.SqlIntentPlan, SqlUpload.OnSqlUploadListener{
    private static final int INSTALL_PERMISSION_CODE = 1;
    private ProgressBar progress;
    private TextView plan_title;
    private TextView plan_text1;
    private TextView plan_text2;
    private TextView bar;
    private AlertDialog alertDialog;
    private String format = "";
    private File file_apk;

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

        getVersions();
    }

    /**
     * 进入界面时自动检测是否有最新版本
     */
    private void getVersions() {
        YLHttpClient client = YLHttpClient.getDefaultYLHttpCline();
        RequestBody requestBody = new FormBody.Builder()
                .add("appCode", Consts.appCode)
                .add("verCode", getVerName(ModelActivity.this))
                .build();
        client.sendPostRequest(ModelActivity.this, Consts.URL + Consts.getVersion, requestBody, new TypeToken<HttpData<AppFile>>() {
        }.getType(), new HttpCallBack<HttpData<AppFile>>() {
            @Override
            public void callBack(int statueCode, HttpData<AppFile> httpData) {
                if (statueCode == 200) {
                    if (httpData.success = true) {
                        Long fileId = httpData.data.fileId;
                        String fileName = httpData.data.fileName;
                        String fileUrl = httpData.data.fileUrl;
                        if (fileId != null) {  // fileId为null时是最新版本
                            AlertDialog.Builder builder = new AlertDialog.Builder(ModelActivity.this);
                            builder.setTitle("提示");
                            builder.setMessage("发现有最新版本,请确定更新!!!");
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            // 下载最新版本
                                            YLDownload download = new YLDownload();
                                            Looper.prepare();
                                            download.download(Consts.URL + fileUrl, getFilesDir().getPath(), fileName, ModelActivity.this);
                                            Looper.loop();
                                        }
                                    }).start();
                                    View view = View.inflate(ModelActivity.this, R.layout.sync_file, null);
                                    plan_title = view.findViewById(R.id.plan_title);
                                    plan_text1 = view.findViewById(R.id.plan_text1);
                                    plan_text2 = view.findViewById(R.id.plan_text2);
                                    progress = view.findViewById(R.id.progress);
                                    bar = view.findViewById(R.id.bar);
                                    plan_title.setText("文件下载:");
                                    plan_text1.setText("更新文件下载中,请耐心等候...");
                                    plan_text2.setText("下载过程中请保持开机状态!");
                                    progress.setProgress(0);
                                    progress.setSecondaryProgress(1);
                                    alertDialog = new AlertDialog.Builder(ModelActivity.this).setView(view).create();
                                    alertDialog.show();
                                    alertDialog.setCanceledOnTouchOutside(false);
                                }
                            });
                            builder.setCancelable(false);
                            builder.show();
                        }
                    }
                }
            }
        });
    }

    /**
     * 离线模式
     */
    public void Login(View view) {
        startActivity(new Intent(ModelActivity.this, MainActivity.class));
    }

    /**
     * 同步数据
     * @param view
     */
    public void Sync(View view) {
        // 上传本地数据,在上传外套一次请求,避免因为网络异常而导致页面泄露
        YLHttpClient client = YLHttpClient.getDefaultYLHttpCline();
        client.sendGetRequest(ModelActivity.this, Consts.URL + Consts.mePath, new TypeToken<HttpData>() {
        }.getType(), new HttpCallBack<HttpData>() {
            @Override
            public void callBack(int statueCode, HttpData httpData) {
                if (statueCode == 200) {
                    if (getUSBConnected()) {
                        // 同步时间
                        YLHttpClient client = YLHttpClient.getDefaultYLHttpCline();
                        client.sendGetRequest(ModelActivity.this, Consts.URL + Consts.getTime + "?t1=" + System.currentTimeMillis(), new TypeToken<HttpData<ServerTime>>() {
                        }.getType(), new HttpCallBack<HttpData<ServerTime>>() {
                            @Override
                            public void callBack(int statueCode, HttpData<ServerTime> httpData) {
                                if (statueCode == 200) {
                                    long a = System.currentTimeMillis() - httpData.data.t1;
                                    long currentTime = a / 2 + httpData.data.t3;
                                    long Time = currentTime - System.currentTimeMillis();
                                    setTime(Time);
                                    // 同步数据
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            SqlUpload upload = new SqlUpload();
                                            new Thread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Looper.prepare();
                                                    try {
                                                        upload.upLoad(Consts.URL + Consts.takeNewData, ModelActivity.this, ModelActivity.this);
                                                    } catch (IOException e) {
                                                        e.printStackTrace();
                                                    }
                                                    Looper.loop();
                                                }
                                            }).start();
                                        }
                                    }).start();
                                    View view = View.inflate(ModelActivity.this, R.layout.sync_file, null);
                                    plan_title = view.findViewById(R.id.plan_title);
                                    plan_text1 = view.findViewById(R.id.plan_text1);
                                    plan_text2 = view.findViewById(R.id.plan_text2);
                                    progress = view.findViewById(R.id.progress);
                                    bar = view.findViewById(R.id.bar);
                                    plan_title.setText("数据同步:");
                                    plan_text1.setText("数据上传中中,请耐心等候...");
                                    plan_text2.setText("上传过程中请保持开机状态!");
                                    progress.setProgress(0);
                                    progress.setSecondaryProgress(1);
                                    alertDialog = new AlertDialog.Builder(ModelActivity.this).setView(view).create();
                                    alertDialog.show();
                                    alertDialog.setCanceledOnTouchOutside(false);
                                }
                            }
                        });
                    }
                }
            }
        });
    }

    /**
     * 退出登录
     * @param view
     */
    public void Back(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(ModelActivity.this);
        builder.setTitle("提示");
        builder.setMessage("确定退出登录?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                finish();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    /**
     * 申请安装未知应用权限
     */
    private void setInstallPermission() {
        boolean haveInstallPermission;
        // Android8.0以上需要打开允许安装位置应用权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 先判断是否有安装未知应用权限
            haveInstallPermission = getPackageManager().canRequestPackageInstalls();
            if (!haveInstallPermission) {
                // 弹框提示用户手动打开
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Looper.prepare();
                        AlertDialog.Builder builder = new AlertDialog.Builder(ModelActivity.this);
                        builder.setTitle("安装权限");
                        builder.setMessage("需要打开此应用允许安装未知应用权限!");
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                    // 此方法需要API>=26才能使用
                                    toInstallPermissionSettingIntent();
                                }
                            }
                        });
                        builder.setCancelable(false);
                        alertDialog = builder.create();
                        alertDialog.show();
                        Looper.loop();
                    }
                }).start();
            } else {
                installApk(file_apk);
            }
        } else {
            installApk(file_apk);
        }
    }

    /**
     * 跳转到系统设置未知应用权限界面
     */
    private void toInstallPermissionSettingIntent() {
        Uri packageURI = Uri.parse("package:" + getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        startActivityForResult(intent, INSTALL_PERMISSION_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == INSTALL_PERMISSION_CODE) {
            // 安装下载完成的最新版本
            installApk(file_apk);
        }
    }

    /**
     * 安装apk
     */
    private void installApk(File file) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            // 如果是Android7.0以上,因为权限原因需要建一个fileprovider,设置成共享目录
            Uri apkUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", file);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            // 如果是Android7.0以下
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            chmod("777", file.getAbsolutePath());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
    }

    /**
     * Android7.0以下版本安装需要的权限
     * @param permission
     * @param path
     */
    private void chmod(String permission, String path) {
        try {
            String command = "chmod" + permission + " " + path;
            Runtime runtime = Runtime.getRuntime();
            runtime.exec(command);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载完成
     * @param file
     */
    @Override
    public void onDownloadSuccess(File file) {
        if (file.getName().indexOf("ass_pda.sql") > -1) {
            // 下载数据同步的sql语句
            this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    DBOpenHelper dbOpenHelper = new DBOpenHelper(ModelActivity.this);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            dbOpenHelper.importSql("ass_pda.sql", ModelActivity.this, ModelActivity.this);
                        }
                    }).start();
                }
            });
        } else if (file.getName().indexOf(".apk") > -1) {
            this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    long dateTime = getCurrentTime();
                    SimpleDateFormat dare = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    format = dare.format(dateTime);
                    setDateTime(format);
                    Toast.makeText(ModelActivity.this, "文件下载成功", Toast.LENGTH_LONG).show();
                    alertDialog.hide();
                }
            });
            file_apk = file;
            // 申请安装未知应用权限
            setInstallPermission();
        }
    }

    /**
     * 下载中
     * @param p
     */
    @Override
    public void onDownloading(int p) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                plan_title.setText("文件下载:");
                plan_text1.setText("更新文件下载中,请耐心等候...");
                plan_text2.setText("下载过程中请保持开机状态!");
                progress.setProgress(p);
                progress.setSecondaryProgress(1);
                bar.setText(p + "%");
                Log.i("下载中更新进度条", String.valueOf(p));
            }
        });
    }

    /**
     * 下载异常
     * @param e
     */
    @Override
    public void onDownloadFailed(Exception e) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(ModelActivity.this, "下载异常", Toast.LENGTH_LONG).show();
                if (alertDialog != null) {
                    alertDialog.hide();
                }
            }
        });
    }

    /**
     * 上传成功
     * @param p
     */
    @Override
    public void onUploadSuccess(int p) {
        // 上传成功后下载
        YLHttpClient client = YLHttpClient.getDefaultYLHttpCline();
        client.sendGetRequest(ModelActivity.this, Consts.URL + Consts.getNewData, new TypeToken<HttpData<String>>() {
        }.getType(), new HttpCallBack<HttpData<String>>() {
            @Override
            public void callBack(int statueCode, HttpData<String> httpData) {
                if (statueCode == 200) {
                    String urlMsg = Consts.URL + "/download" + httpData.data;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            YLDownload download = new YLDownload();
                            download.download(urlMsg, getFilesDir().getPath(), "ass_pda.sql", ModelActivity.this);
                        }
                    }).start();
                }
            }
        });
    }

    /**
     * 上传进度
     * @param plan
     */
    @Override
    public void onUploading(int plan) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                plan_title.setText("数据同步:");
                plan_text1.setText("数据上传中,请耐心等候...");
                plan_text2.setText("上传过程中请保持开机状态!");
                progress.setProgress(plan);
                progress.setSecondaryProgress(1);
                bar.setText(plan + "%");
                Log.i("上传中更新进度条", String.valueOf(plan));
            }
        });
    }

    /**
     * 上传异常
     * @param s
     */
    @Override
    public void onUploadFailed(String s) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(ModelActivity.this, "上传异常", Toast.LENGTH_LONG).show();
                if (alertDialog != null) {
                    alertDialog.hide();
                }
            }
        });
    }

    /**
     * 导入进度
     * @param a
     */
    @Override
    public void SqlPlan(int a) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                plan_title.setText("数据同步:");
                plan_text1.setText("数据文件导入中,请耐心等候...");
                plan_text2.setText("导入过程中请保持开机状态!");
                progress.setProgress(a);
                progress.setSecondaryProgress(1);
                bar.setText(a + "%");
                Log.i("导入中更新进度条", String.valueOf(a));
            }
        });
    }

    /**
     * 导入成功
     * @param b
     */
    @Override
    public void onSqlSuccess(int b) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                long dataTime = getCurrentTime();
                SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                format = date.format(dataTime);
                setDateTime(format);
                Toast.makeText(ModelActivity.this, "数据同步完成", Toast.LENGTH_LONG).show();
                if (alertDialog != null) {
                    alertDialog.hide();
                }
            }
        });
    }

    /**
     * 导入异常
     * @param e
     */
    @Override
    public void onSqlFailed(String e) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(ModelActivity.this, "导入异常", Toast.LENGTH_LONG).show();
                if (alertDialog != null) {
                    alertDialog.hide();
                }
            }
        });
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Qxnedy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值