zhibo/android-app/app/src/main/java/com/example/livestreaming/FishPondWebViewActivity.java
2026-01-06 14:24:42 +08:00

509 lines
19 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.example.livestreaming;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.livestreaming.net.ApiClient;
import com.example.livestreaming.net.ApiResponse;
import com.example.livestreaming.net.ApiService;
import com.example.livestreaming.net.CommunityResponse;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* 缘池页面 - WebView版本
* 使用H5页面展示通过JavaScript Bridge与原生交互
*/
public class FishPondWebViewActivity extends AppCompatActivity {
private static final String TAG = "FishPondWebView";
private WebView webView;
private ProgressBar loadingProgress;
private ApiService apiService;
// 缓存数据
private String cachedUserName = "";
private String cachedUserInfo = "";
private int cachedMatchableCount = 0;
private List<CommunityResponse.NearbyUser> cachedNearbyUsers = new ArrayList<>();
private List<CommunityResponse.Category> cachedCategories = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fish_pond_webview);
apiService = ApiClient.getService(this);
initViews();
setupWebView();
setupBottomNav();
// 预加载数据
loadCurrentUserInfo();
loadMatchableUserCount();
loadNearbyUsers();
loadCategories();
// 加载H5页面
webView.loadUrl("file:///android_asset/web/yuanchi.html");
}
private void initViews() {
webView = findViewById(R.id.webView);
loadingProgress = findViewById(R.id.loadingProgress);
}
@SuppressLint("SetJavaScriptEnabled")
private void setupWebView() {
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
settings.setAllowFileAccess(true);
settings.setAllowContentAccess(true);
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
// 添加JavaScript接口
webView.addJavascriptInterface(new FishPondJSInterface(), "Android");
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
loadingProgress.setVisibility(View.GONE);
// 页面加载完成后推送缓存的数据到H5
pushDataToH5();
}
});
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress < 100) {
loadingProgress.setVisibility(View.VISIBLE);
} else {
loadingProgress.setVisibility(View.GONE);
}
}
});
}
private void setupBottomNav() {
BottomNavigationView bottomNav = findViewById(R.id.bottomNavigation);
if (bottomNav != null) {
bottomNav.setSelectedItemId(R.id.nav_friends);
UnreadMessageManager.updateBadge(bottomNav);
bottomNav.setOnItemSelectedListener(item -> {
int id = item.getItemId();
if (id == R.id.nav_home) {
startActivity(new Intent(this, MainActivity.class));
finish();
return true;
}
if (id == R.id.nav_friends) {
return true;
}
if (id == R.id.nav_wish_tree) {
WishTreeWebViewActivity.start(this);
finish();
return true;
}
if (id == R.id.nav_messages) {
MessagesActivity.start(this);
finish();
return true;
}
if (id == R.id.nav_profile) {
ProfileActivity.start(this);
finish();
return true;
}
return true;
});
}
}
/**
* 加载当前用户信息
*/
private void loadCurrentUserInfo() {
SharedPreferences prefs = getSharedPreferences("profile_prefs", MODE_PRIVATE);
cachedUserName = prefs.getString("profile_name", "爱你");
String location = prefs.getString("profile_location", "广西");
String gender = prefs.getString("profile_gender", "");
String genderText = "真诚";
String locationText = location;
if (!TextUtils.isEmpty(location) && location.contains("-")) {
locationText = location.replace("-", "·");
} else if (TextUtils.isEmpty(location)) {
locationText = "南宁";
}
cachedUserInfo = genderText + " | " + locationText + " | 在线";
}
/**
* 加载可匹配用户数量
*/
private void loadMatchableUserCount() {
apiService.getMatchableUserCount().enqueue(new Callback<ApiResponse<Integer>>() {
@Override
public void onResponse(Call<ApiResponse<Integer>> call, Response<ApiResponse<Integer>> response) {
if (response.isSuccessful() && response.body() != null
&& response.body().isOk() && response.body().getData() != null) {
cachedMatchableCount = response.body().getData();
pushMatchableCountToH5();
}
}
@Override
public void onFailure(Call<ApiResponse<Integer>> call, Throwable t) {
Log.e(TAG, "获取用户总数失败: " + t.getMessage());
}
});
}
/**
* 加载附近用户
*/
private void loadNearbyUsers() {
SharedPreferences prefs = getSharedPreferences("profile_prefs", MODE_PRIVATE);
double latitude = prefs.getFloat("latitude", 22.82f);
double longitude = prefs.getFloat("longitude", 108.32f);
apiService.getNearbyUsers(latitude, longitude, 5000, 6)
.enqueue(new Callback<ApiResponse<CommunityResponse.NearbyUserList>>() {
@Override
public void onResponse(Call<ApiResponse<CommunityResponse.NearbyUserList>> call,
Response<ApiResponse<CommunityResponse.NearbyUserList>> response) {
if (response.isSuccessful() && response.body() != null
&& response.body().isOk() && response.body().getData() != null) {
List<CommunityResponse.NearbyUser> users = response.body().getData().getUsers();
if (users != null && !users.isEmpty()) {
cachedNearbyUsers = users;
pushNearbyUsersToH5();
}
}
}
@Override
public void onFailure(Call<ApiResponse<CommunityResponse.NearbyUserList>> call, Throwable t) {
Log.e(TAG, "获取附近用户失败: " + t.getMessage());
}
});
}
/**
* 加载板块列表
*/
private void loadCategories() {
apiService.getCommunityCategories().enqueue(new Callback<ApiResponse<List<CommunityResponse.Category>>>() {
@Override
public void onResponse(Call<ApiResponse<List<CommunityResponse.Category>>> call,
Response<ApiResponse<List<CommunityResponse.Category>>> response) {
if (response.isSuccessful() && response.body() != null
&& response.body().isOk() && response.body().getData() != null) {
cachedCategories = response.body().getData();
pushCategoriesToH5();
}
}
@Override
public void onFailure(Call<ApiResponse<List<CommunityResponse.Category>>> call, Throwable t) {
Log.e(TAG, "加载板块失败: " + t.getMessage());
}
});
}
/**
* 推送所有数据到H5
*/
private void pushDataToH5() {
pushUserInfoToH5();
pushMatchableCountToH5();
pushNearbyUsersToH5();
pushCategoriesToH5();
}
private void pushUserInfoToH5() {
runOnUiThread(() -> {
String js = String.format("updateUserInfo('%s', '%s')",
escapeJs(cachedUserName), escapeJs(cachedUserInfo));
webView.evaluateJavascript(js, null);
});
}
private void pushMatchableCountToH5() {
runOnUiThread(() -> {
String js = String.format("updateMatchableCount('%d')", cachedMatchableCount);
webView.evaluateJavascript(js, null);
});
}
private void pushNearbyUsersToH5() {
runOnUiThread(() -> {
try {
JSONArray usersArray = new JSONArray();
String baseUrl = ApiClient.getCurrentBaseUrl(this);
for (CommunityResponse.NearbyUser user : cachedNearbyUsers) {
JSONObject userObj = new JSONObject();
userObj.put("id", String.valueOf(user.getUserId()));
userObj.put("name", user.getNickname() != null ? user.getNickname() : "用户");
userObj.put("location", user.getLocation() != null ? user.getLocation() : "附近");
String avatarUrl = user.getAvatar();
if (avatarUrl != null && !avatarUrl.isEmpty()) {
if (!avatarUrl.startsWith("http://") && !avatarUrl.startsWith("https://")) {
avatarUrl = baseUrl + avatarUrl;
}
}
userObj.put("avatar", avatarUrl != null ? avatarUrl : "");
usersArray.put(userObj);
}
String js = String.format("updateNearbyUsers('%s')", escapeJs(usersArray.toString()));
webView.evaluateJavascript(js, null);
} catch (JSONException e) {
Log.e(TAG, "构建用户JSON失败: " + e.getMessage());
}
});
}
private void pushCategoriesToH5() {
runOnUiThread(() -> {
try {
JSONArray categoriesArray = new JSONArray();
for (CommunityResponse.Category cat : cachedCategories) {
if (cat.status == 1 || cat.status == 0) {
JSONObject catObj = new JSONObject();
catObj.put("id", cat.getId());
catObj.put("name", cat.getName() != null ? cat.getName() : "");
catObj.put("icon", cat.getIcon() != null ? cat.getIcon() : "");
catObj.put("jumpPage", cat.getJumpPage() != null ? cat.getJumpPage() : "");
categoriesArray.put(catObj);
}
}
String js = String.format("updateCategories('%s')", escapeJs(categoriesArray.toString()));
webView.evaluateJavascript(js, null);
} catch (JSONException e) {
Log.e(TAG, "构建板块JSON失败: " + e.getMessage());
}
});
}
private String escapeJs(String str) {
if (str == null) return "";
return str.replace("\\", "\\\\")
.replace("'", "\\'")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r");
}
/**
* JavaScript接口类 - 供H5调用
*/
private class FishPondJSInterface {
@JavascriptInterface
public String getUserInfo() {
try {
JSONObject obj = new JSONObject();
obj.put("name", cachedUserName);
obj.put("info", cachedUserInfo);
return obj.toString();
} catch (JSONException e) {
return "{}";
}
}
@JavascriptInterface
public String getMatchableCount() {
return String.valueOf(cachedMatchableCount);
}
@JavascriptInterface
public String getNearbyUsers() {
try {
JSONArray usersArray = new JSONArray();
String baseUrl = ApiClient.getCurrentBaseUrl(FishPondWebViewActivity.this);
for (CommunityResponse.NearbyUser user : cachedNearbyUsers) {
JSONObject userObj = new JSONObject();
userObj.put("id", String.valueOf(user.getUserId()));
userObj.put("name", user.getNickname() != null ? user.getNickname() : "用户");
userObj.put("location", user.getLocation() != null ? user.getLocation() : "附近");
String avatarUrl = user.getAvatar();
if (avatarUrl != null && !avatarUrl.isEmpty()) {
if (!avatarUrl.startsWith("http://") && !avatarUrl.startsWith("https://")) {
avatarUrl = baseUrl + avatarUrl;
}
}
userObj.put("avatar", avatarUrl != null ? avatarUrl : "");
usersArray.put(userObj);
}
return usersArray.toString();
} catch (JSONException e) {
return "[]";
}
}
@JavascriptInterface
public String getCategories() {
try {
JSONArray categoriesArray = new JSONArray();
for (CommunityResponse.Category cat : cachedCategories) {
if (cat.status == 1 || cat.status == 0) {
JSONObject catObj = new JSONObject();
catObj.put("id", cat.getId());
catObj.put("name", cat.getName() != null ? cat.getName() : "");
catObj.put("icon", cat.getIcon() != null ? cat.getIcon() : "");
catObj.put("jumpPage", cat.getJumpPage() != null ? cat.getJumpPage() : "");
categoriesArray.put(catObj);
}
}
return categoriesArray.toString();
} catch (JSONException e) {
return "[]";
}
}
@JavascriptInterface
public void onUserClick(String oderId, String userName) {
Log.d(TAG, "点击用户: " + oderId + ", " + userName);
runOnUiThread(() -> {
// 跳转到用户详情页
try {
int userId = 0;
try {
userId = Integer.parseInt(oderId);
} catch (NumberFormatException e) {
Log.e(TAG, "用户ID解析失败: " + oderId);
}
if (userId > 0) {
UserProfileActivity.start(FishPondWebViewActivity.this, userId);
} else {
Toast.makeText(FishPondWebViewActivity.this, "用户ID无效", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(FishPondWebViewActivity.this, "查看用户: " + userName, Toast.LENGTH_SHORT).show();
}
});
}
@JavascriptInterface
public void onCategoryClick(int categoryId, String categoryName, String jumpPage) {
Log.d(TAG, "点击板块: " + categoryId + ", " + categoryName + ", " + jumpPage);
runOnUiThread(() -> {
// 跳转到板块详情页
try {
Intent intent = new Intent(FishPondWebViewActivity.this, DynamicCommunityActivity.class);
intent.putExtra("category_id", categoryId);
intent.putExtra("category_name", categoryName);
startActivity(intent);
} catch (Exception e) {
Toast.makeText(FishPondWebViewActivity.this, "板块 \"" + categoryName + "\" 暂未开放", Toast.LENGTH_SHORT).show();
}
});
}
@JavascriptInterface
public void onRefresh() {
Log.d(TAG, "刷新");
runOnUiThread(() -> {
loadMatchableUserCount();
loadNearbyUsers();
});
}
@JavascriptInterface
public void onVoiceMatch() {
runOnUiThread(() -> {
Toast.makeText(FishPondWebViewActivity.this, "语音匹配功能待接入~", Toast.LENGTH_SHORT).show();
});
}
@JavascriptInterface
public void onHeartSignal() {
runOnUiThread(() -> {
Toast.makeText(FishPondWebViewActivity.this, "心动信号功能待接入~", Toast.LENGTH_SHORT).show();
});
}
@JavascriptInterface
public void showToast(String message) {
runOnUiThread(() -> {
Toast.makeText(FishPondWebViewActivity.this, message, Toast.LENGTH_SHORT).show();
});
}
}
@Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
@Override
protected void onResume() {
super.onResume();
// 刷新底部导航状态
BottomNavigationView bottomNav = findViewById(R.id.bottomNavigation);
if (bottomNav != null) {
bottomNav.setSelectedItemId(R.id.nav_friends);
UnreadMessageManager.updateBadge(bottomNav);
}
}
@Override
protected void onDestroy() {
if (webView != null) {
webView.destroy();
}
super.onDestroy();
}
}