核心功能增强 - 现有 Activity 修改

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
This commit is contained in:
wchino
2026-04-05 22:28:21 +08:00
parent db8d37ec36
commit a61f468fcf
4 changed files with 353 additions and 343 deletions

View File

@@ -1,16 +1,14 @@
package com.miraclegarden.smsmessage.Activity; package com.miraclegarden.smsmessage.Activity;
import android.content.SharedPreferences; import android.content.Intent;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.text.TextUtils; import android.text.TextUtils;
import android.view.View; import android.view.View;
import android.widget.ImageView; import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.miraclegarden.library.app.MiracleGardenActivity; import com.miraclegarden.library.app.MiracleGardenActivity;
import com.miraclegarden.smsmessage.ActionConfirmDialog; import com.miraclegarden.smsmessage.ActionConfirmDialog;
@@ -21,21 +19,38 @@ import com.miraclegarden.smsmessage.R;
import com.miraclegarden.smsmessage.comm.CommonAdapter; import com.miraclegarden.smsmessage.comm.CommonAdapter;
import com.miraclegarden.smsmessage.comm.ViewHolder; import com.miraclegarden.smsmessage.comm.ViewHolder;
import com.miraclegarden.smsmessage.databinding.AppListSettingBinding; import com.miraclegarden.smsmessage.databinding.AppListSettingBinding;
import com.miraclegarden.smsmessage.network.TokenManager;
import java.util.ArrayList; import java.util.ArrayList;
public class AppListActivity extends MiracleGardenActivity<AppListSettingBinding> { public class AppListActivity extends MiracleGardenActivity<AppListSettingBinding> {
public static SharedPreferences sp; private TokenManager tokenManager;
private ArrayList<AppInfo> appList = new ArrayList<>(); private ArrayList<AppInfo> appList = new ArrayList<>();
CommonAdapter userAdapter; CommonAdapter userAdapter;
@Override @Override
protected void onCreate(@Nullable Bundle savedInstanceState) { protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
sp = getSharedPreferences("server", MODE_PRIVATE);
initData(); tokenManager = TokenManager.getInstance(this);
if (!tokenManager.isLoggedIn()) {
startActivity(new Intent(this, LoginActivity.class));
finish();
return;
}
initView();
}
private void initView() {
String username = tokenManager.getUsername();
if (username != null) {
binding.tvUsername.setText(username);
}
binding.backIv.setOnClickListener(view -> finish());
binding.recyclerview.setLayoutManager(new LinearLayoutManager(this));
initAdapter();
} }
@Override @Override
@@ -71,9 +86,7 @@ public class AppListActivity extends MiracleGardenActivity<AppListSettingBinding
private void initData() { private void initAdapter() {
binding.backIv.setOnClickListener(view -> finish());
binding.recyclerview.setLayoutManager(new LinearLayoutManager(this));
userAdapter = new CommonAdapter<>(AppListActivity.this, R.layout.item_user, appList) { userAdapter = new CommonAdapter<>(AppListActivity.this, R.layout.item_user, appList) {
@Override @Override
public void convert(ViewHolder holder, AppInfo info, int index) { public void convert(ViewHolder holder, AppInfo info, int index) {

View File

@@ -4,70 +4,160 @@ import android.Manifest;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.content.pm.PermissionInfo; import android.net.Uri;
import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.PowerManager;
import android.util.Log; import android.provider.Settings;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat; import androidx.core.content.ContextCompat;
import com.miraclegarden.library.app.MiracleGardenActivity; import com.miraclegarden.library.app.MiracleGardenActivity;
import com.miraclegarden.smsmessage.databinding.ActivityMainBinding; import com.miraclegarden.smsmessage.databinding.ActivityMainBinding;
import com.miraclegarden.smsmessage.network.TokenManager;
import java.io.IOException; import com.miraclegarden.smsmessage.util.OEMBackgroundHelper;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends MiracleGardenActivity<ActivityMainBinding> { public class MainActivity extends MiracleGardenActivity<ActivityMainBinding> {
public static SharedPreferences sp;
private static final String TAG = "MainActivity"; private TokenManager tokenManager;
@Override @Override
protected void onCreate(@Nullable Bundle savedInstanceState) { protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
sp = getSharedPreferences("server", MODE_PRIVATE);
initData(); tokenManager = TokenManager.getInstance(this);
if (!tokenManager.isLoggedIn()) {
startActivity(new Intent(this, LoginActivity.class));
finish();
return;
}
initView(); initView();
} }
private void initData() { @Override
if (sp == null) { protected void onResume() {
super.onResume();
if (!tokenManager.isLoggedIn()) {
startActivity(new Intent(this, LoginActivity.class));
finish();
return; return;
} }
binding.host.setText(sp.getString("host", "")); updatePermissionStatus();
} }
private void initView() { private void initView() {
binding.yes.setOnClickListener(v -> { String username = tokenManager.getUsername();
if (sp == null) { if (username != null) {
return; binding.tvUsername.setText(username);
} }
binding.host.setText(sp.getString("host", "https://www.judy88.xin/api/bills/app-upload")); binding.tvDeviceBrand.setText("检测到设备: " + OEMBackgroundHelper.getManufacturer());
if (binding.host.getText().toString().length() == 0) { binding.btnLogout.setOnClickListener(v -> logout());
Toast.makeText(this, "服务器和添加参数不能为空", Toast.LENGTH_SHORT).show();
return;
}
if (!binding.host.getText().toString().startsWith("http")) { binding.btnStartMonitoring.setOnClickListener(v -> {
Toast.makeText(this, "服务器地址错误", Toast.LENGTH_SHORT).show(); startActivity(new Intent(this, NotificationActivity.class));
return; });
}
SharedPreferences.Editor edit = sp.edit(); binding.btnBankManage.setOnClickListener(v -> {
edit.putString("host", binding.host.getText().toString()); startActivity(new Intent(this, BankListActivity.class));
edit.apply(); });
startActivity(new Intent(MainActivity.this, NotificationActivity.class));
finish(); binding.permissionNotificationAccess.setOnClickListener(v -> {
startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS));
});
binding.permissionPostNotifications.setOnClickListener(v -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.POST_NOTIFICATIONS}, 100);
}
}
});
binding.permissionBattery.setOnClickListener(v -> {
requestBatteryOptimization();
});
binding.btnAutostart.setOnClickListener(v -> {
OEMBackgroundHelper.openAutoStartSettings(this);
});
binding.btnBatteryOptimization.setOnClickListener(v -> {
OEMBackgroundHelper.requestBatteryOptimizationExemption(this);
}); });
new Handler().postDelayed(() -> binding.yes.performClick(),2000);
} }
private void logout() {
tokenManager.clear();
Toast.makeText(this, "已退出登录", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
private void updatePermissionStatus() {
boolean notificationAccessEnabled = isNotificationListenerEnabled();
updatePermissionItem(binding.iconNotificationAccess, binding.statusNotificationAccess,
notificationAccessEnabled, notificationAccessEnabled ? "已授权" : "未授权");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
boolean postNotificationsGranted = ContextCompat.checkSelfPermission(this,
Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED;
updatePermissionItem(binding.iconPostNotifications, binding.statusPostNotifications,
postNotificationsGranted, postNotificationsGranted ? "已授权" : "未授权");
binding.permissionPostNotifications.setVisibility(View.VISIBLE);
} else {
binding.permissionPostNotifications.setVisibility(View.GONE);
}
boolean batteryOptimized = isBatteryOptimizationEnabled();
updatePermissionItem(binding.iconBattery, binding.statusBattery,
!batteryOptimized, batteryOptimized ? "未授权" : "已授权");
}
private void updatePermissionItem(ImageView icon, TextView status, boolean granted, String statusText) {
if (granted) {
icon.setImageResource(android.R.drawable.checkbox_on_background);
icon.setColorFilter(ContextCompat.getColor(this, android.R.color.holo_green_dark));
} else {
icon.setImageResource(android.R.drawable.ic_dialog_info);
icon.setColorFilter(ContextCompat.getColor(this, android.R.color.holo_red_dark));
}
status.setText(statusText);
}
private boolean isNotificationListenerEnabled() {
String flat = Settings.Secure.getString(getContentResolver(), "enabled_notification_listeners");
return flat != null && flat.contains(getPackageName());
}
private boolean isBatteryOptimizationEnabled() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
return pm != null && !pm.isIgnoringBatteryOptimizations(getPackageName());
}
return false;
}
private void requestBatteryOptimization() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);
} catch (Exception e) {
startActivity(new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS));
}
}
}
} }

View File

@@ -1,166 +1,214 @@
package com.miraclegarden.smsmessage.Activity; package com.miraclegarden.smsmessage.Activity;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.os.Looper; import android.os.Looper;
import android.os.Message; import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings; import android.provider.Settings;
import android.text.TextUtils; import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager; import android.view.WindowManager;
import android.widget.ScrollView; import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import com.miraclegarden.library.app.MiracleGardenActivity; import com.miraclegarden.library.app.MiracleGardenActivity;
import com.miraclegarden.smsmessage.AppInfo; import com.miraclegarden.smsmessage.App;
import com.miraclegarden.smsmessage.AppListUtil;
import com.miraclegarden.smsmessage.MessageInfo;
import com.miraclegarden.smsmessage.databinding.ActivityNotificationBinding; import com.miraclegarden.smsmessage.databinding.ActivityNotificationBinding;
import com.miraclegarden.smsmessage.network.TokenManager;
import com.miraclegarden.smsmessage.service.NotificationService; import com.miraclegarden.smsmessage.service.NotificationService;
import com.miraclegarden.smsmessage.service.RetryManager;
import org.json.JSONException; import java.lang.ref.WeakReference;
import org.json.JSONObject;
import java.io.IOException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class NotificationActivity extends MiracleGardenActivity<ActivityNotificationBinding> { public class NotificationActivity extends MiracleGardenActivity<ActivityNotificationBinding> {
private static final Handler handler = new Handler(Looper.myLooper()) { private static final int MAX_LOG_LINES = 200;
private static WeakReference<NotificationActivity> instanceRef;
private TokenManager tokenManager;
private final Handler handler = new Handler(Looper.getMainLooper()) {
@Override @Override
public void handleMessage(@NonNull Message msg) { public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg); super.handleMessage(msg);
String str = (String) msg.obj; String str = (String) msg.obj;
if (str != null) { if (str != null && binding != null && binding.tvLog != null) {
@SuppressLint("SimpleDateFormat") SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss"); SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
String t = format.format(new Date()); String t = format.format(new Date());
if (textView != null) { binding.tvLog.append(t + " " + str + "\n");
textView.append(t + "" + str + "\n\r"); trimLogIfNeeded();
scrollView.post(() -> scrollView.fullScroll(ScrollView.FOCUS_DOWN)); binding.scrollView.post(() ->
} binding.scrollView.fullScroll(ScrollView.FOCUS_DOWN));
} }
} }
}; };
public static SharedPreferences sharedPreferences;
public static void sendMessage(String str) { public static void sendMessage(String str) {
Message message = new Message(); NotificationActivity activity = instanceRef != null ? instanceRef.get() : null;
message.obj = str; if (activity != null && activity.handler != null) {
NotificationActivity.handler.sendMessage(message); Message message = Message.obtain();
message.obj = str;
activity.handler.sendMessage(message);
}
} }
@SuppressLint("StaticFieldLeak")
private static TextView textView;
@SuppressLint("StaticFieldLeak")
private static NestedScrollView scrollView;
private final String[] permissions = new String[]{
Manifest.permission.RECEIVE_BOOT_COMPLETED
};
@Override @Override
protected void onCreate(@Nullable Bundle savedInstanceState) { protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
sharedPreferences = getSharedPreferences("server", MODE_PRIVATE);
tokenManager = TokenManager.getInstance(this);
if (!tokenManager.isLoggedIn()) {
Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, LoginActivity.class));
finish();
return;
}
instanceRef = new WeakReference<>(this);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
NotificationActivity.textView = binding.text;
NotificationActivity.scrollView = binding.scrollable;
initPermission();
initView(); initView();
} }
@Override
protected void onResume() {
super.onResume();
updateUI();
handler.post(statsUpdateRunnable);
}
@Override
protected void onPause() {
super.onPause();
handler.removeCallbacks(statsUpdateRunnable);
}
@Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacksAndMessages(null);
if (instanceRef != null && instanceRef.get() == this) {
instanceRef = null;
}
}
private void initView() { private void initView() {
binding.button2.setOnClickListener(v -> { String username = tokenManager.getUsername();
//打开监听引用消息Notification access if (username != null) {
Intent intent_s = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS); binding.tvUsername.setText(username);
startActivity(intent_s); }
});
binding.button.setOnClickListener(v -> {
binding.ivBack.setOnClickListener(v -> finish());
binding.btnSettings.setOnClickListener(v -> {
startActivity(new Intent(this, SettingActivity.class));
}); });
binding.button1.setOnClickListener(view -> { binding.btnClearLog.setOnClickListener(v -> {
if (textView != null) { binding.tvLog.setText("");
textView.setText("");
}
}); });
binding.toolbar.setOnLongClickListener(view -> { binding.btnToggleMonitor.setOnClickListener(v -> toggleMonitoring());
// Toast.makeText(NotificationActivity.this,"点我干嘛",Toast.LENGTH_SHORT).show();
startActivity(new Intent(NotificationActivity.this,SettingActivity.class));
return false;
});
binding.jiantingList.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(NotificationActivity.this,SettingActivity.class);
intent.putExtra("is_list",true);
startActivity(intent);
}
});
} }
private void initPermission() { private void toggleMonitoring() {
checkPermission(); if (!isNotificationListenerEnabled()) {
for (String permission : permissions) { Toast.makeText(this, "请先开启通知访问权限", Toast.LENGTH_LONG).show();
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) { startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS));
sendMessage("没有" + permission + "权限"); return;
}
if (NotificationService.isMonitoring()) {
NotificationService.stopMonitoring(this);
sendMessage("正在停止监听...");
} else {
if (App.getNotiList(this).isEmpty()) {
Toast.makeText(this, "请先在\"监听设置\"中添加要监听的APP", Toast.LENGTH_LONG).show();
return;
} }
NotificationService.requestStartMonitoring(this);
sendMessage("正在开启监听服务...");
updateUI();
} }
} }
public static void updateUI() {
NotificationActivity activity = instanceRef != null ? instanceRef.get() : null;
if (activity == null || activity.binding == null) {
return;
}
//打开设置界面 if (NotificationService.isMonitoring()) {
private void checkPermission() { activity.binding.btnToggleMonitor.setText("停止监听");
if (!isEnabled()) { activity.binding.btnToggleMonitor.setEnabled(true);
startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS")); activity.binding.btnToggleMonitor.setBackgroundTintList(
android.content.res.ColorStateList.valueOf(0xFFFF5252));
activity.binding.tvStatus.setText("状态: 监听中");
activity.binding.tvStatus.setTextColor(0xFF4CAF50);
} else {
activity.binding.btnToggleMonitor.setText("开始监听");
activity.binding.btnToggleMonitor.setEnabled(true);
activity.binding.btnToggleMonitor.setBackgroundTintList(
android.content.res.ColorStateList.valueOf(activity.getResources().getColor(com.miraclegarden.smsmessage.R.color.purple_500)));
activity.binding.tvStatus.setText("状态: 未启动");
activity.binding.tvStatus.setTextColor(0xFF888888);
}
activity.updateStatistics();
}
private void updateStatistics() {
if (binding == null) {
return;
}
android.content.SharedPreferences sp = getSharedPreferences("server", MODE_PRIVATE);
int totalCount = sp.getInt("total_count", 0);
int uploadedCount = sp.getInt("uploaded_count", 0);
int configuredCount = App.getNotiList(this).size();
binding.tvConfiguredApps.setText("已配置: " + configuredCount + "");
binding.tvMonitoredCount.setText("监听: " + totalCount);
binding.tvUploadedCount.setText("上传: " + uploadedCount);
if (totalCount > 0) {
int successRate = (uploadedCount * 100) / totalCount;
binding.tvSuccessRate.setText("成功率: " + successRate + "%");
} else {
binding.tvSuccessRate.setText("成功率: --");
} }
} }
private final Runnable statsUpdateRunnable = new Runnable() {
@Override
public void run() {
updateStatistics();
handler.postDelayed(this, 2000);
}
};
// 判断是否打开了通知监听权限 private void trimLogIfNeeded() {
private boolean isEnabled() { if (binding == null || binding.tvLog == null) return;
String pkgName = getPackageName(); String fullText = binding.tvLog.getText().toString();
final String flat = Settings.Secure.getString(getContentResolver(), "enabled_notification_listeners"); String[] lines = fullText.split("\n");
if (!TextUtils.isEmpty(flat)) { if (lines.length > MAX_LOG_LINES) {
final String[] names = flat.split(":"); StringBuilder sb = new StringBuilder();
for (String name : names) { for (int i = lines.length - MAX_LOG_LINES; i < lines.length; i++) {
final ComponentName cn = ComponentName.unflattenFromString(name); sb.append(lines[i]);
if (cn != null) { if (i < lines.length - 1) {
if (TextUtils.equals(pkgName, cn.getPackageName())) { sb.append("\n");
return true;
}
} }
} }
binding.tvLog.setText(sb.toString());
} }
return false;
} }
private boolean isNotificationListenerEnabled() {
String flat = Settings.Secure.getString(getContentResolver(), "enabled_notification_listeners");
return flat != null && flat.contains(getPackageName());
}
} }

View File

@@ -1,31 +1,15 @@
package com.miraclegarden.smsmessage.Activity; package com.miraclegarden.smsmessage.Activity;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.PermissionInfo;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log;
import android.view.View; import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager;
import com.miraclegarden.library.app.MiracleGardenActivity; import com.miraclegarden.library.app.MiracleGardenActivity;
import com.miraclegarden.smsmessage.ActionConfirmDialog;
import com.miraclegarden.smsmessage.App; import com.miraclegarden.smsmessage.App;
import com.miraclegarden.smsmessage.AppInfo; import com.miraclegarden.smsmessage.AppInfo;
import com.miraclegarden.smsmessage.AppListUtil; import com.miraclegarden.smsmessage.AppListUtil;
@@ -34,236 +18,111 @@ import com.miraclegarden.smsmessage.MessageInfo;
import com.miraclegarden.smsmessage.R; import com.miraclegarden.smsmessage.R;
import com.miraclegarden.smsmessage.comm.CommonAdapter; import com.miraclegarden.smsmessage.comm.CommonAdapter;
import com.miraclegarden.smsmessage.comm.ViewHolder; import com.miraclegarden.smsmessage.comm.ViewHolder;
import com.miraclegarden.smsmessage.databinding.ActivityMainBinding;
import com.miraclegarden.smsmessage.databinding.ActivitySettingBinding; import com.miraclegarden.smsmessage.databinding.ActivitySettingBinding;
import com.miraclegarden.smsmessage.network.TokenManager;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class SettingActivity extends MiracleGardenActivity<ActivitySettingBinding> { public class SettingActivity extends MiracleGardenActivity<ActivitySettingBinding> {
public static SharedPreferences sp;
private static final String TAG = "SettingActivity";
private ArrayList<MessageInfo> appList = new ArrayList<>(); private ArrayList<MessageInfo> appList = new ArrayList<>();
CommonAdapter userAdapter; private CommonAdapter userAdapter;
boolean is_list = false; private TokenManager tokenManager;
@Override @Override
protected void onCreate(@Nullable Bundle savedInstanceState) { protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
sp = getSharedPreferences("server", MODE_PRIVATE);
initData();
initList();
is_list = getIntent().getBooleanExtra("is_list",false); tokenManager = TokenManager.getInstance(this);
if(!is_list){ if (!tokenManager.isLoggedIn()) {
binding.setPostLy.setVisibility(View.VISIBLE); startActivity(new Intent(this, LoginActivity.class));
binding.titleTv.setText("设置"); finish();
}else{ return;
binding.titleTv.setText("监听App列表");
} }
initView();
initList();
}
private void initView() {
String username = tokenManager.getUsername();
if (username != null) {
binding.tvUsername.setText(username);
}
binding.ivBack.setOnClickListener(v -> finish());
binding.btnAddApp.setOnClickListener(v -> {
startActivity(new Intent(this, AppListActivity.class));
});
} }
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
initChangeList(); refreshList();
} }
private void initChangeList() { private void refreshList() {
List<MessageInfo> appList1 = App.getNotiList(SettingActivity.this); List<MessageInfo> list = App.getNotiList(this);
if(appList1 == null){ appList = new ArrayList<>(list);
appList = new ArrayList<>();
}else{
appList = (ArrayList<MessageInfo>) appList1;
}
userAdapter.setDates(appList); userAdapter.setDates(appList);
if(appList.size()>0){
if (appList.size() > 0) {
binding.recyclerview.setVisibility(View.VISIBLE); binding.recyclerview.setVisibility(View.VISIBLE);
binding.nodataIv.setVisibility(View.GONE); binding.tvEmpty.setVisibility(View.GONE);
}else{ } else {
binding.recyclerview.setVisibility(View.GONE); binding.recyclerview.setVisibility(View.GONE);
binding.nodataIv.setVisibility(View.VISIBLE); binding.tvEmpty.setVisibility(View.VISIBLE);
} }
} }
private void initData() {
binding.host.setText(sp.getString("host", "https://www.judy88.xin/api/bills/app-upload"));
binding.addBt.setOnClickListener(view -> startActivity(new Intent(SettingActivity.this,AppListActivity.class)));
binding.backIv.setOnClickListener(view -> finish());
binding.yes.setOnClickListener(v -> {
if (sp == null) {
return;
}
if (binding.host.getText().toString().length() == 0) {
Toast.makeText(this, "服务器和添加参数不能为空", Toast.LENGTH_SHORT).show();
return;
}
if (!binding.host.getText().toString().startsWith("http")) {
Toast.makeText(this, "服务器地址错误", Toast.LENGTH_SHORT).show();
return;
}
hideKeyboard();
AppInfo appInfo = AppListUtil.getAppByPackageName(SettingActivity.this,"com.miraclegarden.smsmessage");
appInfo.setCode("111");
appInfo.setName("测试");
appInfo.setRemark("测试更换接口");
MessageInfo messageInfo = MessageInfo.AppInfoToMessageInfo(appInfo);
Submit(messageInfo,"测试更换接口","测试更换接口");
});
}
public MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public void Submit(MessageInfo messageInfo, String title, String context) {
OkHttpClient client = new OkHttpClient();
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", messageInfo.getName());
jsonObject.put("code", messageInfo.getCode());
jsonObject.put("remark", messageInfo.getRemark());
jsonObject.put("appName", messageInfo.getAppName());
jsonObject.put("packageName", messageInfo.getPackageName());
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("title", title);
jsonObject1.put("context", context);
jsonObject.put("data", jsonObject1);
String json = jsonObject.toString();
RequestBody body = RequestBody.create(json, JSON);
// 构建请求
Request request = new Request.Builder()
.url(binding.host.getText().toString())
.post(body)
.build();
Log.i("地址是啥","地址是啥1111"+binding.host.getText().toString());
Log.i("地址是啥","地址是啥2222"+json);
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
// NotificationActivity.sendMessage("提交失败:" + e);
// Toast.makeText(SettingActivity.this,"接口地址访问异常",Toast.LENGTH_SHORT).show();
sendMessage("接口地址访问异常");
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
String str = response.body().string();
if (response.isSuccessful()) {
Log.i("地址是啥","地址是啥:"+str);
// {"ok":true,"received":true}
toSaveAddress();
return;
}
Log.i("地址是啥","地址是啥11"+str);
sendMessage("接口地址访问异常");
}
});
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
private void hideKeyboard() {
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
if (imm != null && binding.host.getWindowToken() != null) {
imm.hideSoftInputFromWindow(binding.host.getWindowToken(), 0);
}
}
private Handler handler = new Handler(Looper.myLooper()) {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
String str = (String) msg.obj;
if (str != null) {
Toast.makeText(SettingActivity.this,str,Toast.LENGTH_SHORT).show();
}
}
};
public void sendMessage(String str) {
Message message = new Message();
message.obj = str;
handler.sendMessage(message);
}
private void toSaveAddress() {
SharedPreferences.Editor edit = sp.edit();
edit.putString("host", binding.host.getText().toString());
edit.apply();
sendMessage( "服务器地址修改成功:" );
}
private void initList() { private void initList() {
binding.recyclerview.setLayoutManager(new LinearLayoutManager(this)); binding.recyclerview.setLayoutManager(new LinearLayoutManager(this));
userAdapter = new CommonAdapter<>(SettingActivity.this, R.layout.item_user, appList) { userAdapter = new CommonAdapter<>(this, R.layout.item_user, appList) {
@Override @Override
public void convert(ViewHolder holder, MessageInfo info, int index) { public void convert(ViewHolder holder, MessageInfo info, int index) {
AppInfo appInfo = AppListUtil.getAppByPackageName(SettingActivity.this,info.getPackageName()); AppInfo appInfo = AppListUtil.getAppByPackageName(SettingActivity.this, info.getPackageName());
ImageView delete_img = holder.getView(R.id.delete_img);
delete_img.setVisibility(View.VISIBLE);
delete_img.setOnClickListener(view -> {
DeleteConfirmDialog deleteConfirmDialog = new DeleteConfirmDialog(SettingActivity.this,info);
deleteConfirmDialog.setOnToActionListener(() -> {
App.deleteNotiBean(SettingActivity.this,info);
initChangeList();
});
deleteConfirmDialog.show();
ImageView deleteBtn = holder.getView(R.id.delete_img);
deleteBtn.setVisibility(View.VISIBLE);
deleteBtn.setOnClickListener(v -> {
DeleteConfirmDialog dialog = new DeleteConfirmDialog(SettingActivity.this, info);
dialog.setOnConfirmListener(() -> {
App.deleteNotiBean(SettingActivity.this, info);
refreshList();
});
dialog.show();
}); });
if(appInfo!=null){
if (appInfo != null) {
((ImageView) holder.getView(R.id.iv_icon)).setImageDrawable(appInfo.getIcon()); ((ImageView) holder.getView(R.id.iv_icon)).setImageDrawable(appInfo.getIcon());
}else{ } else {
((ImageView) holder.getView(R.id.iv_icon)).setImageResource(R.mipmap.app_logo); ((ImageView) holder.getView(R.id.iv_icon)).setImageResource(R.mipmap.app_logo);
} }
holder.setText(R.id.tv_appname, info.getAppName()); holder.setText(R.id.tv_appname, info.getAppName());
holder.setText(R.id.tv_package, info.getPackageName()); holder.setText(R.id.tv_package, info.getPackageName());
if (!TextUtils.isEmpty(info.getName())) { if (!TextUtils.isEmpty(info.getName())) {
holder.setText(R.id.tv_name, info.getName()+"/"); holder.setText(R.id.tv_name, info.getName());
}else{ } else {
holder.setText(R.id.tv_name, "--/"); holder.setText(R.id.tv_name, "未设置");
} }
if (!TextUtils.isEmpty(info.getCode())) { if (!TextUtils.isEmpty(info.getCode())) {
holder.setText(R.id.tv_code, info.getCode()+"/"); holder.setText(R.id.tv_code, info.getCode());
}else{ } else {
holder.setText(R.id.tv_code, "--/"); holder.setText(R.id.tv_code, "--");
} }
if (!TextUtils.isEmpty(info.getRemark())) { if (!TextUtils.isEmpty(info.getRemark())) {
holder.setText(R.id.tv_remark, info.getRemark()); holder.setText(R.id.tv_remark, "(" + info.getRemark() + ")");
}else{ holder.getView(R.id.tv_remark).setVisibility(View.VISIBLE);
holder.setText(R.id.tv_remark, "--"); } else {
holder.getView(R.id.tv_remark).setVisibility(View.GONE);
} }
} }
}; };
binding.recyclerview.setAdapter(userAdapter); binding.recyclerview.setAdapter(userAdapter);
} }
} }