修复 Room 迁移并支持通话记录与反向拨号
This commit is contained in:
1 parent
7124137730
commit
38e1bcc288
7 files changed
+262
-15
No files matched your search
@@ -37,6 +37,7 @@
|
||||
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />
|
||||
<!-- 短信记录:仅声明,需 ROM 预授权 -->
|
||||
<uses-permission android:name="android.permission.READ_SMS" />
|
||||
<uses-permission android:name="android.permission.READ_CALL_LOG" />
|
||||
<uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<uses-permission android:name="android.permission.SET_ALARM" />
|
||||
|
||||
@@ -15,7 +15,7 @@ import com.ttstd.dialer.db.sms.SmsRecordDao;
|
||||
import com.ttstd.dialer.db.sms.SmsRecordEntity;
|
||||
|
||||
@Database(entities = {AppInfo.class, AppIconUpload.class, SmsRecordEntity.class},
|
||||
version = 4, exportSchema = false)
|
||||
version = 5, exportSchema = false)
|
||||
public abstract class AppDatabase extends RoomDatabase {
|
||||
public abstract AppDao appDao();
|
||||
|
||||
@@ -60,6 +60,30 @@ public abstract class AppDatabase extends RoomDatabase {
|
||||
}
|
||||
};
|
||||
|
||||
// 兼容从旧版迁移的非空列,以及全新安装 v4 时生成的可空列。
|
||||
static final Migration MIGRATION_4_5 = new Migration(4, 5) {
|
||||
@Override
|
||||
public void migrate(@NonNull SupportSQLiteDatabase database) {
|
||||
database.execSQL("CREATE TABLE `sms_record_new` ("
|
||||
+ "`source_id` INTEGER NOT NULL, "
|
||||
+ "`direction` TEXT, "
|
||||
+ "`address` TEXT, "
|
||||
+ "`contact_name` TEXT, "
|
||||
+ "`sent_time` INTEGER NOT NULL, "
|
||||
+ "`sim_slot` INTEGER, "
|
||||
+ "`uploaded` INTEGER NOT NULL, "
|
||||
+ "`present` INTEGER NOT NULL, "
|
||||
+ "`updated_at` INTEGER NOT NULL, "
|
||||
+ "PRIMARY KEY(`source_id`))");
|
||||
String columns = "`source_id`, `direction`, `address`, `contact_name`, "
|
||||
+ "`sent_time`, `sim_slot`, `uploaded`, `present`, `updated_at`";
|
||||
database.execSQL("INSERT INTO `sms_record_new` (" + columns + ") "
|
||||
+ "SELECT " + columns + " FROM `sms_record`");
|
||||
database.execSQL("DROP TABLE `sms_record`");
|
||||
database.execSQL("ALTER TABLE `sms_record_new` RENAME TO `sms_record`");
|
||||
}
|
||||
};
|
||||
|
||||
// 单例模式获取数据库实例
|
||||
public static AppDatabase getDatabase(final Context context) {
|
||||
if (INSTANCE == null) {
|
||||
@@ -67,7 +91,7 @@ public abstract class AppDatabase extends RoomDatabase {
|
||||
if (INSTANCE == null) {
|
||||
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
|
||||
AppDatabase.class, context.getExternalFilesDir("db") + File.separator + "app" + File.separator + "app_db")
|
||||
.addMigrations(MIGRATION_2_3, MIGRATION_3_4)
|
||||
.addMigrations(MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5)
|
||||
.fallbackToDestructiveMigration()
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import android.database.Cursor;
|
||||
import android.net.Uri;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.provider.CallLog;
|
||||
import android.provider.Telephony;
|
||||
import android.text.TextUtils;
|
||||
|
||||
@@ -58,6 +59,7 @@ public class SmsRecordManager {
|
||||
|
||||
private static final String KEY_SMS_ENABLED = "record_sms_enabled";
|
||||
private static final String KEY_CALL_ENABLED = "record_call_enabled";
|
||||
private static final String KEY_CALL_VERSION = "record_call_snapshot_version";
|
||||
private static final String KEY_LAST_FALLBACK = "sms_last_fallback_at";
|
||||
|
||||
private static final String FALLBACK_WORK_NAME = "sms_fallback_daily";
|
||||
@@ -65,6 +67,7 @@ public class SmsRecordManager {
|
||||
private static final long DEBOUNCE_MILLIS = 3000L;
|
||||
|
||||
private static final int UPLOAD_CHUNK = 200;
|
||||
private static final int CALL_LIMIT = 500;
|
||||
private static final int SNAPSHOT_CHUNK = 5000;
|
||||
|
||||
private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
|
||||
@@ -80,8 +83,11 @@ public class SmsRecordManager {
|
||||
private final AtomicBoolean busy = new AtomicBoolean(false);
|
||||
|
||||
private ContentObserver observer;
|
||||
private ContentObserver callObserver;
|
||||
private final Object callUploadLock = new Object();
|
||||
|
||||
private final Runnable collectTask = () -> executor.execute(this::collectAndUpload);
|
||||
private final Runnable callCollectTask = () -> executor.execute(this::uploadCallSnapshot);
|
||||
|
||||
private SmsRecordManager(@NonNull Context context) {
|
||||
appContext = context.getApplicationContext();
|
||||
@@ -112,6 +118,8 @@ public class SmsRecordManager {
|
||||
if (isSmsEnabled()) {
|
||||
registerObserver();
|
||||
}
|
||||
refreshCallObserver();
|
||||
uploadCallSnapshot();
|
||||
collectAndUpload();
|
||||
});
|
||||
}
|
||||
@@ -125,6 +133,11 @@ public class SmsRecordManager {
|
||||
public void handleRecordSettingPush(Boolean callLogEnabled, Boolean smsLogEnabled) {
|
||||
if (callLogEnabled != null) {
|
||||
kv.encode(KEY_CALL_ENABLED, callLogEnabled);
|
||||
refreshCallObserver();
|
||||
if (callLogEnabled) {
|
||||
debounceHandler.removeCallbacks(callCollectTask);
|
||||
debounceHandler.post(callCollectTask);
|
||||
}
|
||||
}
|
||||
if (smsLogEnabled != null) {
|
||||
kv.encode(KEY_SMS_ENABLED, smsLogEnabled);
|
||||
@@ -162,6 +175,134 @@ public class SmsRecordManager {
|
||||
|
||||
// ==================== 采集 ====================
|
||||
|
||||
private boolean canReadCalls() {
|
||||
return kv.decodeBool(KEY_CALL_ENABLED, true)
|
||||
&& appContext.checkSelfPermission(Manifest.permission.READ_CALL_LOG)
|
||||
== PackageManager.PERMISSION_GRANTED;
|
||||
}
|
||||
|
||||
private synchronized void refreshCallObserver() {
|
||||
if (!canReadCalls()) {
|
||||
debounceHandler.removeCallbacks(callCollectTask);
|
||||
if (callObserver != null) {
|
||||
appContext.getContentResolver().unregisterContentObserver(callObserver);
|
||||
callObserver = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (callObserver != null) {
|
||||
return;
|
||||
}
|
||||
ContentObserver observer = new ContentObserver(debounceHandler) {
|
||||
@Override
|
||||
public void onChange(boolean selfChange) {
|
||||
debounceHandler.removeCallbacks(callCollectTask);
|
||||
debounceHandler.postDelayed(callCollectTask, DEBOUNCE_MILLIS);
|
||||
}
|
||||
};
|
||||
try {
|
||||
appContext.getContentResolver().registerContentObserver(
|
||||
CallLog.Calls.CONTENT_URI, true, observer);
|
||||
callObserver = observer;
|
||||
} catch (SecurityException e) {
|
||||
Logger.e(TAG, "Call log observer permission denied");
|
||||
}
|
||||
}
|
||||
|
||||
private void uploadCallSnapshot() {
|
||||
uploadCallSnapshot(null);
|
||||
}
|
||||
|
||||
public void handleCallSyncRequest(String requestId) {
|
||||
if (requestId == null || !requestId.matches("[0-9a-f]{32}")) {
|
||||
return;
|
||||
}
|
||||
executor.execute(() -> {
|
||||
if (!uploadCallSnapshot(requestId)) {
|
||||
try {
|
||||
api.reportCallSyncFailure(requestId).blockingFirst();
|
||||
} catch (Exception e) {
|
||||
Logger.e(TAG, "Call sync failure report failed: " + e.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private boolean uploadCallSnapshot(String requestId) {
|
||||
synchronized (callUploadLock) {
|
||||
if (!canReadCalls()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Uri uri = CallLog.Calls.CONTENT_URI.buildUpon()
|
||||
.appendQueryParameter(CallLog.Calls.LIMIT_PARAM_KEY, String.valueOf(CALL_LIMIT))
|
||||
.build();
|
||||
String[] columns = {
|
||||
CallLog.Calls._ID, CallLog.Calls.NUMBER, CallLog.Calls.CACHED_NAME,
|
||||
CallLog.Calls.TYPE, CallLog.Calls.DATE, CallLog.Calls.DURATION
|
||||
};
|
||||
List<Map<String, Object>> calls = new ArrayList<>();
|
||||
try (Cursor cursor = appContext.getContentResolver().query(uri, columns, null, null,
|
||||
CallLog.Calls.DATE + " DESC, " + CallLog.Calls._ID + " DESC")) {
|
||||
if (cursor == null) {
|
||||
return false;
|
||||
}
|
||||
while (calls.size() < CALL_LIMIT && cursor.moveToNext()) {
|
||||
long id = cursor.getLong(0);
|
||||
long calledAt = cursor.getLong(4);
|
||||
if (id <= 0 || calledAt <= 0) {
|
||||
continue;
|
||||
}
|
||||
Map<String, Object> call = new HashMap<>();
|
||||
call.put("sourceId", id);
|
||||
call.put("number", limitCallText(cursor.getString(1)));
|
||||
call.put("contactName", limitCallText(cursor.getString(2)));
|
||||
call.put("direction", callDirection(cursor.getInt(3)));
|
||||
call.put("calledAt", calledAt);
|
||||
call.put("durationSeconds", Math.max(0, cursor.getLong(5)));
|
||||
calls.add(call);
|
||||
}
|
||||
}
|
||||
if (!canReadCalls()) {
|
||||
return false;
|
||||
}
|
||||
long version = Math.max(System.currentTimeMillis(), kv.decodeLong(KEY_CALL_VERSION, 0) + 1);
|
||||
kv.encode(KEY_CALL_VERSION, version);
|
||||
Map<String, Object> request = new HashMap<>();
|
||||
request.put("snapshotVersion", version);
|
||||
request.put("calls", calls);
|
||||
if (requestId != null) {
|
||||
request.put("requestId", requestId);
|
||||
}
|
||||
BaseResponse<Void> response = api.uploadCallSnapshot(jsonBody(request)).blockingFirst();
|
||||
if (!response.isSuccess()) {
|
||||
Logger.e(TAG, "Call log snapshot rejected: " + response.getCode());
|
||||
}
|
||||
return response.isSuccess();
|
||||
} catch (Exception e) {
|
||||
Logger.e(TAG, "Call log snapshot failed: " + e.getClass().getSimpleName());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String limitCallText(String value) {
|
||||
return value == null || value.length() <= 256 ? value : value.substring(0, 256);
|
||||
}
|
||||
|
||||
private String callDirection(int type) {
|
||||
switch (type) {
|
||||
case CallLog.Calls.INCOMING_TYPE:
|
||||
return "INCOMING";
|
||||
case CallLog.Calls.OUTGOING_TYPE:
|
||||
return "OUTGOING";
|
||||
case CallLog.Calls.MISSED_TYPE:
|
||||
return "MISSED";
|
||||
default:
|
||||
return "OTHER";
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void registerObserver() {
|
||||
if (observer != null) {
|
||||
return;
|
||||
@@ -360,6 +501,8 @@ public class SmsRecordManager {
|
||||
executor.execute(() -> reconcile(syncId));
|
||||
} /** WorkManager 兜底,调用线程需为后台线程 */
|
||||
public void runFallbackIfDue() {
|
||||
refreshCallObserver();
|
||||
uploadCallSnapshot();
|
||||
if (!isSmsEnabled() || !hasReadSmsPermission()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -39,6 +39,8 @@ public class UrlConstants {
|
||||
public static final String GET_RECORD_SETTINGS = "get_record_settings";
|
||||
/*上传短信元数据*/
|
||||
public static final String SMS_META = "sms_meta";
|
||||
public static final String CALL_SNAPSHOT = "call_snapshot";
|
||||
public static final String CALL_SYNC_FAILED = "call_sync_failed";
|
||||
/*设备自主发起短信对账*/
|
||||
public static final String SMS_SYNC_START = "sms_sync_start";
|
||||
/*上传本地短信 ID 快照*/
|
||||
|
||||
@@ -153,6 +153,12 @@ public interface SnApi {
|
||||
@POST(UrlConstants.SMS_META)
|
||||
Observable<BaseResponse<Integer>> uploadSmsMeta(@Body RequestBody body);
|
||||
|
||||
@POST(UrlConstants.CALL_SNAPSHOT)
|
||||
Observable<BaseResponse<Void>> uploadCallSnapshot(@Body RequestBody body);
|
||||
|
||||
@POST(UrlConstants.CALL_SYNC_FAILED)
|
||||
Observable<BaseResponse<Void>> reportCallSyncFailure(@Query("requestId") String requestId);
|
||||
|
||||
/** 上传本地短信 ID 快照 */
|
||||
@POST(UrlConstants.SMS_SNAPSHOT)
|
||||
Observable<BaseResponse<SmsSyncModels.SnapshotResult>> uploadSmsSnapshot(@Body RequestBody body);
|
||||
|
||||
@@ -16,6 +16,7 @@ import android.os.Build;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.UserManager;
|
||||
import android.provider.Settings;
|
||||
import android.text.TextUtils;
|
||||
import android.util.Log;
|
||||
import android.view.ContextThemeWrapper;
|
||||
@@ -26,6 +27,7 @@ import android.widget.Toast;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.kongzue.dialogx.dialogs.MessageDialog;
|
||||
import com.tencent.mmkv.MMKV;
|
||||
import com.ttstd.dialer.BuildConfig;
|
||||
import com.ttstd.dialer.R;
|
||||
@@ -129,6 +131,8 @@ public class PushExecutor {
|
||||
private static final String DEVICE_RECORD_SETTING = "26";
|
||||
/** 家属端请求读取单条短信正文 */
|
||||
private static final String DEVICE_SMS_CONTENT = "27";
|
||||
private static final String DEVICE_CALL_SYNC = "28";
|
||||
private static final String DEVICE_REVERSE_DIAL_CONFIRM = "29";
|
||||
|
||||
/** 绑定请求弹窗倒计时时长(秒) */
|
||||
private static final long BIND_REQUEST_COUNTDOWN_SECONDS = 60L;
|
||||
@@ -261,7 +265,10 @@ public class PushExecutor {
|
||||
bindSuccess(extra);
|
||||
break;
|
||||
case DEVICE_REVERSE_DIAL:
|
||||
reverseDial(extra);
|
||||
reverseDial(extra, false);
|
||||
break;
|
||||
case DEVICE_REVERSE_DIAL_CONFIRM:
|
||||
reverseDial(extra, true);
|
||||
break;
|
||||
case DEVICE_WALLPAPER:
|
||||
applyWallpaper();
|
||||
@@ -278,6 +285,9 @@ public class PushExecutor {
|
||||
case DEVICE_SMS_CONTENT:
|
||||
replySmsContent(extra);
|
||||
break;
|
||||
case DEVICE_CALL_SYNC:
|
||||
syncCallRecords(extra);
|
||||
break;
|
||||
default:
|
||||
Logger.e(TAG, "setPushMessage: default");
|
||||
}
|
||||
@@ -784,6 +794,19 @@ public class PushExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
private void syncCallRecords(String extra) {
|
||||
try {
|
||||
JsonObject json = JsonParser.parseString(extra).getAsJsonObject();
|
||||
String requestId = json.get("requestId").getAsString();
|
||||
SmsRecordManager manager = SmsRecordManager.getInstance();
|
||||
if (manager != null) {
|
||||
manager.handleCallSyncRequest(requestId);
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
Logger.e(TAG, "syncCallRecords: invalid extra");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理(contentType = 15, clean)。
|
||||
* <p>
|
||||
@@ -815,11 +838,9 @@ public class PushExecutor {
|
||||
* 反向拨号(contentType = 22, reverseDial)。
|
||||
* <p>
|
||||
* 由后端 {@code ClientController.reverseDial} 下发,extra 携带 {@code phone} 字段。
|
||||
* 收到后设备主动外呼该号码:有 CALL_PHONE 权限时用 {@code ACTION_CALL} 直接拨打,
|
||||
* 否则退回 {@code ACTION_DIAL} 打开拨号盘,实现「家属端发起、设备端呼叫」的反向拨号。
|
||||
* 已由家属端确认的专用推送直接拨号,其余请求由设备端确认。
|
||||
*/
|
||||
private void reverseDial(String extra) {
|
||||
Logger.e(TAG, "reverseDial: 收到反向拨号推送, extra=" + extra);
|
||||
private void reverseDial(String extra, boolean canBeConfirmedByFamily) {
|
||||
if (TextUtils.isEmpty(extra)) {
|
||||
Logger.e(TAG, "reverseDial: extra 为空");
|
||||
return;
|
||||
@@ -830,21 +851,67 @@ public class PushExecutor {
|
||||
Logger.e(TAG, "reverseDial: 缺少 phone 字段");
|
||||
return;
|
||||
}
|
||||
String phone = json.get("phone").getAsString().trim();
|
||||
if (TextUtils.isEmpty(phone)) {
|
||||
Logger.e(TAG, "reverseDial: phone 为空");
|
||||
String rawPhone = json.get("phone").getAsString().trim();
|
||||
String phone = rawPhone.replaceAll("[()\\s.\\-]", "");
|
||||
if (rawPhone.startsWith("-") || !phone.matches("[+]?[0-9]{1,32}")) {
|
||||
Logger.e(TAG, "reverseDial: invalid phone");
|
||||
return;
|
||||
}
|
||||
boolean confirmedByFamily = canBeConfirmedByFamily
|
||||
&& json.has("confirmedByFamily")
|
||||
&& json.get("confirmedByFamily").getAsBoolean();
|
||||
new Handler(Looper.getMainLooper()).post(() -> {
|
||||
if (confirmedByFamily) {
|
||||
dialConfirmedNumber(phone);
|
||||
} else {
|
||||
showReverseDialConfirmation(phone);
|
||||
}
|
||||
});
|
||||
} catch (RuntimeException e) {
|
||||
Logger.e(TAG, "reverseDial: invalid push payload");
|
||||
}
|
||||
}
|
||||
|
||||
private void showReverseDialConfirmation(String phone) {
|
||||
try {
|
||||
String title = mContext.getString(R.string.reverse_dial_confirmation_title);
|
||||
String message = mContext.getString(R.string.reverse_dial_confirmation_message, phone);
|
||||
String confirm = mContext.getString(R.string.reverse_dial_confirm);
|
||||
if (!Settings.canDrawOverlays(mContext)) {
|
||||
MessageDialog.show(title, message, confirm, mContext.getString(android.R.string.cancel))
|
||||
.setOkButton((dialog, view) -> {
|
||||
dialConfirmedNumber(phone);
|
||||
return false;
|
||||
});
|
||||
return;
|
||||
}
|
||||
ContextThemeWrapper wrapper = new ContextThemeWrapper(
|
||||
mContext, android.R.style.Theme_DeviceDefault_Light_Dialog_Alert);
|
||||
AlertDialog dialog = new AlertDialog.Builder(wrapper)
|
||||
.setTitle(title)
|
||||
.setMessage(message)
|
||||
.setPositiveButton(confirm, (d, which) -> dialConfirmedNumber(phone))
|
||||
.setNegativeButton(android.R.string.cancel, null)
|
||||
.create();
|
||||
dialog.getWindow().setType(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
|
||||
? WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
|
||||
: WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
|
||||
dialog.show();
|
||||
} catch (RuntimeException e) {
|
||||
Logger.e(TAG, "reverseDial: confirmation unavailable");
|
||||
}
|
||||
}
|
||||
|
||||
private void dialConfirmedNumber(String phone) {
|
||||
try {
|
||||
boolean hasCallPermission = mContext.checkSelfPermission(Manifest.permission.CALL_PHONE)
|
||||
== PackageManager.PERMISSION_GRANTED;
|
||||
Intent intent = new Intent(hasCallPermission ? Intent.ACTION_CALL : Intent.ACTION_DIAL);
|
||||
intent.setData(Uri.parse("tel:" + phone));
|
||||
intent.setData(Uri.fromParts("tel", phone, null));
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||||
mContext.startActivity(intent);
|
||||
Logger.e(TAG, "reverseDial: 已发起呼叫 " + phone + ", action="
|
||||
+ (hasCallPermission ? "ACTION_CALL" : "ACTION_DIAL"));
|
||||
} catch (Exception e) {
|
||||
Logger.e(TAG, "reverseDial: 拨号失败 " + e.getMessage());
|
||||
} catch (RuntimeException e) {
|
||||
Toast.makeText(mContext, R.string.reverse_dial_failed, Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,4 +10,8 @@
|
||||
<string name="accessibility_service_label">❤拨号助手无障碍服务👈🏻</string>
|
||||
<string name="accessibility_service_description">使用拨号助手一键拨号</string>
|
||||
|
||||
<string name="reverse_dial_confirmation_title">反向拨号</string>
|
||||
<string name="reverse_dial_confirmation_message">家属请求拨打 %1$s,是否拨号?</string>
|
||||
<string name="reverse_dial_confirm">确认拨号</string>
|
||||
<string name="reverse_dial_failed">无法拨打此号码</string>
|
||||
</resources>
|
||||
Reference in new issue
Block a user