387 lines
13 KiB
Dart
387 lines
13 KiB
Dart
import 'dart:io';
|
||
import 'dart:convert';
|
||
|
||
import 'package:circle_app/app/home/logic.dart';
|
||
import 'package:circle_app/app/splash/binding.dart';
|
||
import 'package:circle_app/util/paymentUtil.dart';
|
||
import 'package:circle_app/common/values/pushconfig.dart';
|
||
import 'package:circle_app/network/api.dart';
|
||
import 'package:circle_app/network/dio_manager.dart';
|
||
import 'package:circle_app/router/app_pages.dart';
|
||
import 'package:circle_app/router/app_routers.dart';
|
||
import 'package:circle_app/util/PaymentUtils.dart';
|
||
import 'package:circle_app/util/SharedPreferencesHelper.dart';
|
||
import 'package:circle_app/util/device.dart';
|
||
import 'package:circle_app/util/util.dart';
|
||
import 'package:flutter/material.dart';
|
||
import 'package:flutter/services.dart';
|
||
import 'package:flutter_bugly/flutter_bugly.dart';
|
||
import 'package:flutter_localizations/flutter_localizations.dart';
|
||
import 'package:flutter_native_splash/flutter_native_splash.dart';
|
||
import 'package:flutter_screenutil/flutter_screenutil.dart';
|
||
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
|
||
import 'package:get/get.dart';
|
||
import 'package:image_picker/image_picker.dart';
|
||
import 'package:oktoast/oktoast.dart';
|
||
import 'package:pull_to_refresh/pull_to_refresh.dart';
|
||
import 'package:tencent_cloud_chat_uikit/business_logic/separate_models/tui_chat_separate_view_model.dart';
|
||
import 'package:tencent_cloud_chat_uikit/data_services/core/core_services.dart';
|
||
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';
|
||
|
||
import 'package:tencent_chat_push_for_china/model/appInfo.dart';
|
||
|
||
import 'package:tencent_chat_push_for_china/tencent_chat_push_for_china.dart';
|
||
import 'app/login/login/logic.dart';
|
||
import 'app/splash/view.dart';
|
||
|
||
///定义全局的 routeObserver 对象
|
||
final RouteObserver<PageRoute> routeObserver = RouteObserver();
|
||
|
||
final CoreServicesImpl coreInstance = TIMUIKitCore.getInstance();
|
||
final TUIChatSeparateViewModel chatSeparateViewModel =
|
||
TUIChatSeparateViewModel();
|
||
|
||
OverlayEntry? mainOverlayEntry;
|
||
|
||
void main() {
|
||
FlutterBugly.postCatchedException(() async {
|
||
// 如果需要 ensureInitialized,请在这里运行。
|
||
WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
|
||
FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
|
||
runApp(MyApp());
|
||
if (Platform.isAndroid) {
|
||
bool isAgreemement = await getAgreemement();
|
||
if (isAgreemement) {
|
||
FlutterBugly.init(
|
||
androidAppId: "8509314e11",
|
||
iOSAppId: "51e7b4e472",
|
||
);
|
||
}
|
||
}
|
||
|
||
|
||
});
|
||
if (Platform.isAndroid) {
|
||
getLostData();
|
||
}
|
||
}
|
||
|
||
Future<void> getLostData() async {
|
||
final ImagePicker picker = ImagePicker();
|
||
final LostDataResponse response = await picker.retrieveLostData();
|
||
if (response.isEmpty) {
|
||
return;
|
||
}
|
||
final List<XFile>? files = response.files;
|
||
if (files != null) {
|
||
_handleLostFiles(files);
|
||
} else {
|
||
_handleError(response.exception);
|
||
}
|
||
}
|
||
|
||
void _handleLostFiles(List<XFile> file) {}
|
||
Future<void> _handleError(dynamic error) async {
|
||
// 处理错误,例如记录错误或显示错误消息
|
||
print('Error occurred: $error');
|
||
// 在界面上显示错误消息
|
||
showToast('内存异常,请重新上传');
|
||
}
|
||
|
||
int IM_SDK_APP_ID = 1400799631;
|
||
|
||
String IOS_APP_ID = "";
|
||
|
||
//登录IM
|
||
loginIM(String userId, String sig) async {
|
||
var info = await coreInstance.login(
|
||
userID: userId,
|
||
userSig: sig,
|
||
);
|
||
if (info.code == 0) {
|
||
uploadBuzIDAndToken();
|
||
V2TimCallback setC2CReceiveMessageOptRes = await TencentImSDKPlugin
|
||
.v2TIMManager
|
||
.getMessageManager()
|
||
.setC2CReceiveMessageOpt(
|
||
userIDList: [
|
||
'qpqz_dev_10_10000000000',
|
||
'qpqz_prod_10_10000000000'
|
||
], // 需要设置的用户id列表
|
||
opt: ReceiveMsgOptEnum
|
||
.V2TIM_RECEIVE_NOT_NOTIFY_MESSAGE); // 用户消息接收选项属性
|
||
if (setC2CReceiveMessageOptRes.code == 0) {
|
||
//设置成功
|
||
}
|
||
var logic = Get.find<HomeLogic>();
|
||
logic.getUnreadSize();
|
||
}
|
||
}
|
||
|
||
//退出IM
|
||
logoutIM() async {
|
||
try {
|
||
final result = await coreInstance.logout();
|
||
print(result.desc + '退出IM');
|
||
} catch (e) {
|
||
|
||
}
|
||
}
|
||
|
||
//获取设备Token,获取成功后开启离线推送
|
||
void uploadBuzIDAndToken() async {
|
||
bool isAgreemement = await getAgreemement();
|
||
if (!isAgreemement) {
|
||
return;
|
||
}
|
||
|
||
|
||
await ChannelPush.init((msg) {});
|
||
|
||
int? businessID = await TimUiKitPushPlugin.getBuzId(PushConfig.appInfo);
|
||
|
||
String token = await ChannelPush.getDeviceToken();
|
||
ChannelPush.uploadToken();
|
||
|
||
print("token=" + token);
|
||
if (token != "") {
|
||
V2TimCallback res = await coreInstance.setOfflinePushConfig(
|
||
token: token, businessID: businessID);
|
||
|
||
print("token=" + res.code.toString());
|
||
}
|
||
}
|
||
|
||
|
||
class MyApp extends StatefulWidget {
|
||
const MyApp({super.key});
|
||
|
||
@override
|
||
State<MyApp> createState() => _MyAppState();
|
||
}
|
||
|
||
class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
|
||
AppLifecycleState? _lastLifecycleState;
|
||
|
||
// This widget is the root of your application.
|
||
|
||
final List<String> _guideList = ['bg', 'home_back'];
|
||
|
||
@override
|
||
void dispose() {
|
||
WidgetsBinding.instance.removeObserver(this);
|
||
super.dispose();
|
||
}
|
||
|
||
@override
|
||
void initState() {
|
||
initIM();
|
||
WidgetsBinding.instance.addObserver(this);
|
||
|
||
// uploadBuzIDAndToken();
|
||
loadBgImage();
|
||
super.initState();
|
||
addPayNotifi();
|
||
}
|
||
|
||
@override
|
||
void didChangeAppLifecycleState(AppLifecycleState state) async {
|
||
print("--" + state.toString());
|
||
_lastLifecycleState = state;
|
||
int? unreadCount = 0;
|
||
//获取会话未读总数
|
||
V2TimValueCallback<int> getTotalUnreadMessageCountRes =
|
||
await TencentImSDKPlugin.v2TIMManager
|
||
.getConversationManager()
|
||
.getTotalUnreadMessageCount();
|
||
if (getTotalUnreadMessageCountRes.code == 0) {
|
||
//拉取成功
|
||
unreadCount = getTotalUnreadMessageCountRes.data; //会话未读总数
|
||
}
|
||
print("state=" + state.toString());
|
||
if (Platform.isIOS) {
|
||
return;
|
||
}
|
||
switch (state) {
|
||
case AppLifecycleState.inactive:
|
||
setOfflinePushStatus(
|
||
status: AppStatus.background, totalCount: unreadCount);
|
||
if (unreadCount != null) {
|
||
ChannelPush.setBadgeNum(unreadCount);
|
||
}
|
||
break;
|
||
case AppLifecycleState.resumed:
|
||
setOfflinePushStatus(status: AppStatus.foreground);
|
||
break;
|
||
case AppLifecycleState.paused:
|
||
setOfflinePushStatus(
|
||
status: AppStatus.background, totalCount: unreadCount);
|
||
if (unreadCount != null) {
|
||
ChannelPush.setBadgeNum(unreadCount);
|
||
}
|
||
break;
|
||
}
|
||
}
|
||
|
||
@override
|
||
Future<V2TimCallback> setOfflinePushStatus(
|
||
{required AppStatus status, int? totalCount}) {
|
||
if (status == AppStatus.foreground) {
|
||
// 当应用status为前台时,上报doForeground()
|
||
return TencentImSDKPlugin.v2TIMManager
|
||
.getOfflinePushManager()
|
||
.doForeground();
|
||
} else {
|
||
// 当应用status为后台时,上报doBackground(),并带上未读数
|
||
return TencentImSDKPlugin.v2TIMManager
|
||
.getOfflinePushManager()
|
||
.doBackground(unreadCount: totalCount ?? 0);
|
||
}
|
||
}
|
||
|
||
getLoginStyle() async {
|
||
if ((await getAuthorization()).isEmpty) {
|
||
pushLoginPage();
|
||
FlutterNativeSplash.remove();
|
||
} else {
|
||
var data =
|
||
await DioManager.instance.put(url: Api.refreshToken, params: {});
|
||
var bean = BaseResponse<LoginData>.fromJson(
|
||
data, (data) => LoginData.fromJson(data));
|
||
if (bean.code == 200) {
|
||
SharedPreferencesHelper.getInstance().then((sharedPreferences) {
|
||
sharedPreferences.setString(SharedPreferencesHelper.AUTHORIZATION,
|
||
bean.data!.Authorization.toString());
|
||
});
|
||
FlutterNativeSplash.remove();
|
||
Get.offNamed(AppRoutes.Home);
|
||
|
||
return;
|
||
} else if (bean.code == 30002) {
|
||
SharedPreferencesHelper.getInstance().then((sharedPreferences) {
|
||
sharedPreferences.setString(SharedPreferencesHelper.AUTHORIZATION,
|
||
bean.data!.Authorization.toString());
|
||
});
|
||
Get.offNamed(AppRoutes.Complete_materialPage);
|
||
FlutterNativeSplash.remove();
|
||
return;
|
||
}
|
||
showOKToast(bean.msg.toString());
|
||
if (bean.code == 500) {
|
||
await Future.delayed(const Duration(seconds: 5));
|
||
getLoginStyle();
|
||
return;
|
||
}
|
||
}
|
||
}
|
||
|
||
initIM() {
|
||
coreInstance.init(
|
||
sdkAppID: IM_SDK_APP_ID,
|
||
// Replace 0 with the SDKAppID of your IM application when integrating
|
||
// language: LanguageEnum.zhHans, // 界面语言配置,若不配置,则跟随系统语言
|
||
loglevel: LogLevelEnum.V2TIM_LOG_DEBUG,
|
||
onTUIKitCallbackListener: (TIMCallback callbackValue) {
|
||
switch (callbackValue.type) {
|
||
case TIMCallbackType.INFO:
|
||
// Shows the recommend text for info callback directly
|
||
showOKToast(callbackValue.infoRecommendText!);
|
||
break;
|
||
case TIMCallbackType.API_ERROR:
|
||
//Prints the API error to console, and shows the error message.
|
||
if (callbackValue.errorCode == 20007) {
|
||
showOKToast("您已被对方拉黑,换个人聊聊天吧~");
|
||
return;
|
||
}
|
||
if (callbackValue.errorCode == 6015) {
|
||
return;
|
||
}
|
||
print(
|
||
"Error from TUIKit: ${callbackValue.errorMsg}, Code: ${callbackValue.errorCode}");
|
||
if (callbackValue.errorCode == 10004 &&
|
||
callbackValue.errorMsg!.contains("not support @all")) {
|
||
showOKToast("当前群组不支持@全体成员");
|
||
} else {
|
||
// showToast(callbackValue.errorMsg ??
|
||
// callbackValue.errorCode.toString());
|
||
}
|
||
break;
|
||
case TIMCallbackType.FLUTTER_ERROR:
|
||
default:
|
||
// prints the stack trace to console or shows the catch error
|
||
if (callbackValue.catchError != null) {
|
||
// showToast(callbackValue.catchError.toString());
|
||
} else {
|
||
print(callbackValue.stackTrace);
|
||
// loginIM();
|
||
}
|
||
}
|
||
},
|
||
// [建议配置,详见此部分](https://cloud.tencent.com/document/product/269/70746#callback)
|
||
listener: V2TimSDKListener(onConnectSuccess: () {
|
||
print('IM登录成功');
|
||
|
||
// loginIM();
|
||
}));
|
||
}
|
||
|
||
loadBgImage() async {
|
||
await precacheImage(precacheImages(_guideList.first), context);
|
||
await precacheImage(precacheImages(_guideList.last), context);
|
||
await precacheImage(AssetImage(getCircleImage('circle_bg')), context,
|
||
size: Size(Get.width, Get.height));
|
||
}
|
||
|
||
precacheImages(String image) {
|
||
return AssetImage(getBaseImage(image));
|
||
}
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
//填入设计稿中设备的屏幕尺寸,单位dp
|
||
// configureDio();
|
||
return ScreenUtilInit(
|
||
designSize: const Size(375, 812),
|
||
minTextAdapt: true,
|
||
splitScreenMode: true,
|
||
builder: (context, child) {
|
||
return RefreshConfiguration(
|
||
footerBuilder: () => CustomLoadFooter(),
|
||
child: OKToast(
|
||
// 2-A: wrap your app with OKToast
|
||
textStyle:
|
||
const TextStyle(fontSize: 19.0, color: Colors.white),
|
||
backgroundColor: Colors.grey,
|
||
animationCurve: Curves.easeIn,
|
||
|
||
// animationBuilder: const Miui10AnimBuilder(),
|
||
animationDuration: const Duration(milliseconds: 200),
|
||
duration: const Duration(seconds: 2),
|
||
child: GetMaterialApp(
|
||
title: '微乐园',
|
||
initialBinding: SplashBinding(),
|
||
getPages: AppPages.routes,
|
||
/// 国际化处理
|
||
localizationsDelegates: const [
|
||
GlobalMaterialLocalizations.delegate,
|
||
GlobalWidgetsLocalizations.delegate,
|
||
GlobalCupertinoLocalizations.delegate, /// iOS一定要设置,不然报错
|
||
],
|
||
locale: const Locale('zh', 'CN'),
|
||
supportedLocales : const [
|
||
Locale('zh', 'CN'),
|
||
Locale('en', 'US'),
|
||
],
|
||
home: SplashPage(),
|
||
navigatorObservers: [routeObserver],
|
||
builder: FlutterSmartDialog.init(),
|
||
debugShowCheckedModeBanner: false,
|
||
)));
|
||
});
|
||
}
|
||
|
||
void addPayNotifi() {
|
||
IOSPayment.instance.startSubscription();
|
||
}
|
||
}
|