Skip to content

Commit

Permalink
新增:一键克隆增加离线模式(导出备份json文件到Download目录,其他机器读取文件导入)
Browse files Browse the repository at this point in the history
优化:一键克隆机制优化(替换db文件→操作现有db)
  • Loading branch information
pppscn committed Apr 2, 2022
1 parent 60dde07 commit 3101760
Show file tree
Hide file tree
Showing 21 changed files with 749 additions and 505 deletions.
234 changes: 108 additions & 126 deletions app/src/main/java/com/idormy/sms/forwarder/CloneActivity.java
Original file line number Diff line number Diff line change
@@ -1,28 +1,32 @@
package com.idormy.sms.forwarder;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

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

import com.alibaba.fastjson.JSON;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.idormy.sms.forwarder.model.vo.CloneInfoVo;
import com.idormy.sms.forwarder.receiver.BaseServlet;
import com.idormy.sms.forwarder.receiver.RebootBroadcastReceiver;
import com.idormy.sms.forwarder.sender.HttpServer;
import com.idormy.sms.forwarder.utils.BackupDbTask;
import com.idormy.sms.forwarder.utils.CloneUtils;
import com.idormy.sms.forwarder.utils.Define;
import com.idormy.sms.forwarder.utils.DownloadUtil;
import com.idormy.sms.forwarder.utils.FileUtils;
import com.idormy.sms.forwarder.utils.HttpUtil;
import com.idormy.sms.forwarder.utils.NetUtil;
import com.idormy.sms.forwarder.utils.SettingUtil;
Expand All @@ -31,6 +35,7 @@
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
Expand All @@ -47,37 +52,19 @@ public class CloneActivity extends AppCompatActivity {
private final String TAG = "CloneActivity";
private Context context;
private String serverIp;
public static final String DATABASE_NAME = "sms_forwarder.db";
private String backupPath;
private final String backupFile = "SmsForwarder.json";
private IPEditText textServerIp;
private TextView sendTxt;
private TextView receiveTxt;
private TextView backupPathTxt;
private Button sendBtn;
public static final int TOAST = 0x9731994;
public static final int DOWNLOAD = 0x9731995;

//消息处理者,创建一个Handler的子类对象,目的是重写Handler的处理消息的方法(handleMessage())
@SuppressWarnings("deprecation")
@SuppressLint("HandlerLeak")
private final Handler handError = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == TOAST) {
ToastUtils.delayedShow(msg.getData().getString("DATA"), 3000);
} else if (msg.what == DOWNLOAD) {
String savePath = context.getCacheDir().getPath() + File.separator + BackupDbTask.BACKUP_FILE;
Log.d(TAG, savePath);
downloadFile(msg.getData().getString("URL"), context.getCacheDir().getPath(), BackupDbTask.BACKUP_FILE, msg.getData().getString("INFO"));
}
}
};

@Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);

context = CloneActivity.this;

setContentView(R.layout.activity_clone);
Log.d(TAG, "onCreate: " + RebootBroadcastReceiver.class.getName());

Expand All @@ -92,6 +79,41 @@ protected void onStart() {
super.onStart();
Log.d(TAG, "onStart");

backupPathTxt = findViewById(R.id.backupPathTxt);
// 申请储存权限
XXPermissions.with(this).permission(Permission.Group.STORAGE).request(new OnPermissionCallback() {
@Override
public void onGranted(List<String> permissions, boolean all) {
backupPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
backupPathTxt.setText(backupPath + File.separator + backupFile);
}

@Override
public void onDenied(List<String> permissions, boolean never) {
if (never) {
ToastUtils.show(R.string.toast_denied_never);
// 如果是被永久拒绝就跳转到应用权限系统设置页面
XXPermissions.startPermissionActivity(CloneActivity.this, permissions);
} else {
ToastUtils.show(R.string.toast_denied);
}
backupPathTxt.setText("未授权储存权限,该功能无法使用!");
}
});

LinearLayout layoutNetwork = findViewById(R.id.layoutNetwork);
LinearLayout layoutOffline = findViewById(R.id.layoutOffline);
final RadioGroup radioGroupTypeCheck = findViewById(R.id.radioGroupTypeCheck);
radioGroupTypeCheck.setOnCheckedChangeListener((group, checkedId) -> {
if (checkedId == R.id.btnTypeOffline) {
layoutNetwork.setVisibility(View.GONE);
layoutOffline.setVisibility(View.VISIBLE);
} else {
layoutNetwork.setVisibility(View.VISIBLE);
layoutOffline.setVisibility(View.GONE);
}
});

sendBtn = findViewById(R.id.sendBtn);
sendTxt = findViewById(R.id.sendTxt);
TextView ipText = findViewById(R.id.ipText);
Expand All @@ -110,18 +132,14 @@ protected void onStart() {
sendBtn.setText(R.string.send);
sendTxt.setText(R.string.server_has_stopped);
}
//noinspection CommentedOutCode

//发送
sendBtn.setOnClickListener(v -> {
if (!HttpServer.asRunning() && NetUtil.NETWORK_WIFI != NetUtil.getNetWorkStatus()) {
Toast(handError, TAG, getString(R.string.no_wifi_network));
ToastUtils.show(getString(R.string.no_wifi_network));
return;
}

//备份文件
//BackupDbTask task = new BackupDbTask(this);
//String backup_version = task.doInBackground(BackupDbTask.COMMAND_BACKUP);
//Log.d(TAG, "backup_version = " + backup_version);

SettingUtil.switchEnableHttpServer(!SettingUtil.getSwitchEnableHttpServer());
if (!HttpServer.update()) {
SettingUtil.switchEnableHttpServer(!SettingUtil.getSwitchEnableHttpServer());
Expand All @@ -138,23 +156,24 @@ protected void onStart() {
}
});

//接收
receiveBtn.setOnClickListener(v -> {
if (HttpServer.asRunning()) {
receiveTxt.setText(R.string.sender_cannot_receive);
Toast(handError, TAG, getString(R.string.sender_cannot_receive));
ToastUtils.show(getString(R.string.sender_cannot_receive));
return;
}

if (NetUtil.NETWORK_WIFI != NetUtil.getNetWorkStatus()) {
receiveTxt.setText(R.string.no_wifi_network);
Toast(handError, TAG, getString(R.string.no_wifi_network));
ToastUtils.show(getString(R.string.no_wifi_network));
return;
}

serverIp = textServerIp.getIP();
if (serverIp == null || serverIp.isEmpty()) {
receiveTxt.setText(R.string.invalid_server_ip);
Toast(handError, TAG, getString(R.string.invalid_server_ip));
ToastUtils.show(getString(R.string.invalid_server_ip));
return;
}

Expand Down Expand Up @@ -187,7 +206,7 @@ protected void onStart() {
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull final IOException e) {
Toast(handError, TAG, getString(R.string.tips_get_info_failed));
ToastUtils.show(getString(R.string.tips_get_info_failed));
}

@Override
Expand All @@ -196,7 +215,7 @@ public void onResponse(@NonNull Call call, @NonNull Response response) throws IO
Log.d(TAG, "Response:" + response.code() + "," + responseStr);

if (TextUtils.isEmpty(responseStr)) {
Toast(handError, TAG, getString(R.string.tips_get_info_failed));
ToastUtils.show(getString(R.string.tips_get_info_failed));
return;
}

Expand All @@ -205,27 +224,68 @@ public void onResponse(@NonNull Call call, @NonNull Response response) throws IO
Log.d(TAG, cloneInfoVo.toString());

if (!SettingUtil.getVersionName().equals(cloneInfoVo.getVersionName())) {
Toast(handError, TAG, getString(R.string.tips_versions_inconsistent));
ToastUtils.show(getString(R.string.tips_versions_inconsistent));
return;
}

//下载备份文件
Message msg = new Message();
msg.what = DOWNLOAD;
Bundle bundle = new Bundle();
bundle.putString("URL", requestUrl);
bundle.putString("INFO", responseStr);
msg.setData(bundle);
handError.sendMessage(msg);
if (CloneUtils.restoreSettings(cloneInfoVo)) {
ToastUtils.show(getString(R.string.tips_clone_done));
} else {
ToastUtils.show(getString(R.string.tips_clone_failed));
}

} catch (Exception e) {
Toast(handError, TAG, getString(R.string.tips_clone_failed) + e.getMessage());
ToastUtils.show(getString(R.string.tips_clone_failed) + e.getMessage());
}
}
});

});

Button exportBtn = findViewById(R.id.exportBtn);
TextView exportTxt = findViewById(R.id.exportTxt);
Button importBtn = findViewById(R.id.importBtn);
TextView importTxt = findViewById(R.id.importTxt);

//导出
exportBtn.setOnClickListener(v -> {
if (FileUtils.writeFileR(CloneUtils.exportSettings(), backupPath, backupFile, true)) {
ToastUtils.show("导出配置成功!");
} else {
exportTxt.setText("导出失败,请检查写入权限!");
ToastUtils.show("导出失败,请检查写入权限!");
}
});

//导入
importBtn.setOnClickListener(v -> {
try {
String responseStr = FileUtils.readFileI(backupPath, backupFile);
if (TextUtils.isEmpty(responseStr)) {
ToastUtils.show(getString(R.string.tips_get_info_failed));
return;
}

CloneInfoVo cloneInfoVo = JSON.parseObject(responseStr, CloneInfoVo.class);
Log.d(TAG, Objects.requireNonNull(cloneInfoVo).toString());

if (!SettingUtil.getVersionName().equals(cloneInfoVo.getVersionName())) {
ToastUtils.show(getString(R.string.tips_versions_inconsistent));
return;
}

if (CloneUtils.restoreSettings(cloneInfoVo)) {
ToastUtils.show(getString(R.string.tips_clone_done));
} else {
ToastUtils.show(getString(R.string.tips_clone_failed));
}

} catch (Exception e) {
e.printStackTrace();
importTxt.setText("还原失败:" + e.getMessage());
}
});

}

@SuppressLint("SetTextI18n")
Expand All @@ -238,82 +298,4 @@ protected void onResume() {
ipText.setText(getString(R.string.local_ip) + serverIp);
}

/**
* 文件下载
*
* @param url 下载链接
*/
public void downloadFile(String url, final String destFileDir, final String destFileName, final String cloneInfo) {
ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setTitle(getString(R.string.tips_downloading));
progressDialog.setMessage(getString(R.string.tips_please_wait));
progressDialog.setProgress(0);
progressDialog.setMax(100);
progressDialog.show();
progressDialog.setCancelable(false);
DownloadUtil.get().download(url, destFileDir, destFileName, new DownloadUtil.OnDownloadListener() {
@Override
public void onDownloadSuccess(File file) {
if (progressDialog.isShowing()) {
Toast(handError, TAG, getString(R.string.tips_download_done));
progressDialog.dismiss();
}
//下载完成进行相关逻辑操作
Log.d(TAG, file.getPath());

//还原数据库
BackupDbTask task = new BackupDbTask(context);
String backup_version = task.doInBackground(BackupDbTask.COMMAND_RESTORE);
Log.d(TAG, "backup_version = " + backup_version);

//应用配置
CloneInfoVo cloneInfoVo = JSON.parseObject(cloneInfo, CloneInfoVo.class);
System.out.println(cloneInfoVo.toString());
SettingUtil.init(context);
SettingUtil.switchEnableSms(cloneInfoVo.isEnableSms());
SettingUtil.switchEnablePhone(cloneInfoVo.isEnablePhone());
SettingUtil.switchCallType1(cloneInfoVo.isCallType1());
SettingUtil.switchCallType2(cloneInfoVo.isCallType2());
SettingUtil.switchCallType3(cloneInfoVo.isCallType3());
SettingUtil.switchEnableAppNotify(cloneInfoVo.isEnableAppNotify());
SettingUtil.switchCancelAppNotify(cloneInfoVo.isCancelAppNotify());
SettingUtil.smsHubApiUrl(cloneInfoVo.getSmsHubApiUrl());
SettingUtil.setBatteryLevelAlarmMin(cloneInfoVo.getBatteryLevelAlarmMin());
SettingUtil.setBatteryLevelAlarmMax(cloneInfoVo.getBatteryLevelAlarmMax());
SettingUtil.switchBatteryLevelAlarmOnce(cloneInfoVo.isBatteryLevelAlarmOnce());
SettingUtil.setRetryTimes(cloneInfoVo.getRetryTimes());
SettingUtil.setDelayTime(cloneInfoVo.getDelayTime());
SettingUtil.switchSmsTemplate(cloneInfoVo.isEnableSmsTemplate());
SettingUtil.setSmsTemplate(cloneInfoVo.getSmsTemplate());

Toast(handError, TAG, getString(R.string.tips_clone_done));
}

@Override
public void onDownloading(int progress) {
progressDialog.setProgress(progress);
}

@SuppressLint("SetTextI18n")
@Override
public void onDownloadFailed(Exception e) {
//下载异常进行相关提示操作
Log.e(TAG, getString(R.string.tips_download_failed) + e.getMessage());
Toast(handError, TAG, getString(R.string.tips_download_failed) + e.getMessage());
}
});
}

public static void Toast(Handler handError, String Tag, String data) {
Log.i(Tag, data);
if (handError != null) {
Message msg = new Message();
msg.what = TOAST;
Bundle bundle = new Bundle();
bundle.putString("DATA", data);
msg.setData(bundle);
handError.sendMessage(msg);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@

import androidx.annotation.NonNull;

import com.idormy.sms.forwarder.model.RuleModel;
import com.idormy.sms.forwarder.model.SenderModel;

import java.io.Serializable;
import java.util.List;

import lombok.Getter;
import lombok.Setter;
Expand All @@ -28,7 +32,8 @@ public class CloneInfoVo implements Serializable {
private int delayTime;
private boolean enableSmsTemplate;
private String smsTemplate;
private String backupVersion;
private List<SenderModel> senderList;
private List<RuleModel> ruleList;

@NonNull
@Override
Expand All @@ -51,7 +56,8 @@ public String toString() {
", delayTime=" + delayTime +
", enableSmsTemplate=" + enableSmsTemplate +
", smsTemplate=" + smsTemplate +
", backupVersion=" + backupVersion +
", senderList=" + senderList.toString() +
", ruleList=" + ruleList.toString() +
'}';
}
}
Loading

0 comments on commit 3101760

Please sign in to comment.