美文网首页
增加通信进程保活

增加通信进程保活

作者: Openwit | 来源:发表于2022-09-23 15:10 被阅读0次

    1.登录成功时增加调用下面代码

    IctHelper.getInstance().setConflicted(false);
    CoreModule.getInstance().startBgService();
    
    1663917029(1).png

    2.在自己的首页增加保活申请代码

            if (CoreModule.getInstance().isFirstLaunch()) {
                if (!BatteryHelper.isOptimizingBattery()) {
                    IntentWrapper.whiteListMatters(this, null);
                }
                CoreModule.getInstance().setFirstLaunch(false);
            }
    
    1663922489(1).png

    3.更新CoreModule.java文件(appcore/src/main/java/com/fec/phone/core/CoreModule.java),复制下面代码替换现有代码即可:

    package com.fec.phone.core;
    
    import android.app.Activity;
    import android.app.Application;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.os.Build;
    import android.text.TextUtils;
    import android.util.Log;
    
    import com.baidu.mapapi.CoordType;
    import com.baidu.mapapi.SDKInitializer;
    import com.fec.lib.ict.IctKit;
    import com.fec.lib.ict.ResultCode;
    import com.fec.lib.ict.data.LoginInfo;
    import com.fec.lib.im.FecImKit;
    import com.fec.phone.core.conference.repository.ConferenceRepository;
    import com.fec.phone.core.connect.ConnectManager;
    import com.fec.phone.core.contact.repository.ContactRepository;
    import com.fec.phone.core.contact.repository.GroupRepository;
    import com.fec.phone.core.downdb.ContactDatabase;
    import com.fec.phone.core.system.DataCache;
    import com.fec.phone.core.utils.LogUtil;
    import com.fec.phone.lib.ActivityList;
    import com.fec.phone.lib.event.CoreSubject;
    import com.fec.phone.core.message.repository.EmojiRepository;
    import com.fec.phone.core.message.repository.EventMsgRepository;
    import com.fec.phone.core.message.repository.MessageRepository;
    import com.fec.phone.core.receiver.PhoneReceiver;
    import com.fec.phone.core.system.model.db.entity.PocCustomEntity;
    import com.fec.phone.core.system.model.db.entity.UserEntity;
    import com.fec.phone.core.system.repository.SettingRepository;
    import com.fec.phone.core.system.repository.SystemRepository;
    import com.fec.phone.core.template.TemplateConst;
    import com.fec.phone.core.utils.BeanCloneUtil;
    import com.fec.phone.core.utils.PublicUtil;
    import com.fec.phone.lib.configuration.AppSharedPreferences;
    import com.fec.phone.lib.rx.RxBus;
    import com.fec.phone.lib.utils.ThreadPoolUtils;
    import com.fec.phone.lib.utils.ToastUtil;
    import com.fec.rxretrofit.RxRetrofitKit;
    
    import java.util.concurrent.TimeUnit;
    import java.util.logging.Logger;
    
    import io.reactivex.Observable;
    import io.reactivex.ObservableEmitter;
    import io.reactivex.ObservableOnSubscribe;
    import io.reactivex.android.schedulers.AndroidSchedulers;
    import io.reactivex.functions.BiFunction;
    import io.reactivex.functions.Consumer;
    import io.reactivex.functions.Predicate;
    import io.reactivex.schedulers.Schedulers;
    
    /**
     * Created by xuy on 2017/12/25 0025.
     * Core组件的初始化和一些缓存
     */
    
    public class CoreModule {
        private String KEY_CONTACT_SUCCEFFUL;
        private String KEY_FIRST_LAUNCH = "first_launch";
    
        public static final String CHANNEL_XJ = "xj";
        public static final String CHANNEL_CQJZ = "cqjz";
        public static final String CHANNEL_CQJZAQ = "cqjzaq";
        public static final String CHANNEL_NBDT = "nbdt";
        private static CoreModule sInstance = new CoreModule();
        //保存Application
        private Application mApplication;
        //
        private AppSharedPreferences mConfiguration;
    
        private AppSharedPreferences mTest;
    
        private boolean isLogined = false;
        private LoginInfo.Session mCurrentUser;
        private UserEntity mUserEntity;
        private Logger mLogger = Logger.getLogger(getClass().getName());
        private String channel;
    
        public boolean isFirstCreate() {
            return isFirstCreate;
        }
    
        public void setFirstCreate(boolean firstCreate) {
            isFirstCreate = firstCreate;
        }
    
        private boolean isFirstCreate = true;
        private Observable observable;
        private boolean mStop = false;
    
        public boolean isFirstLaunch() {
            boolean isFirstLauch = getConfiguration().getBoolean(KEY_FIRST_LAUNCH, true);
            return isFirstLauch;
        }
    
        public void setFirstLaunch(boolean firstLaunch) {
            getConfiguration().putBoolean(KEY_FIRST_LAUNCH, firstLaunch);
            getConfiguration().commit();
        }
    
        public static CoreModule getInstance() {
            return sInstance;
        }
    
        public void onCreate(Application application) {
            mApplication = application;
            CoreDatabase.init(application);
            RxRetrofitKit.init(application);
            //IctKit.getInstance().init(application.getApplicationContext());
            //Todo IctHelper
    //        IctHelper.init();
            TemplateConst.init();
            mConfiguration = new AppSharedPreferences(application, "");
            mTest = new AppSharedPreferences(application, "");
            ThreadPoolUtils.init();
            channel = PublicUtil.getChannelName(getApplication());
            PhoneReceiver receiver = new PhoneReceiver();
            mApplication.registerReceiver(receiver, new IntentFilter("PhoneReceiver"));
        }
    
        public void initServices() {
            IctKit.getInstance().init(mApplication.getApplicationContext());
            IctHelper.init();
            //百度地图初始化
            SDKInitializer.initialize(mApplication.getApplicationContext());
            SDKInitializer.setCoordType(CoordType.BD09LL);
            LogUtil.getInstance().configLog();
        }
    
        public void startBgService() {
            mStop = false;
            observable.timer(40, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .takeWhile(new Predicate<Long>() {
                        @Override
                        public boolean test(Long aLong) throws Exception {
                            return !mStop;
                        }
                    })
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) throws Exception {
                            if (!FecImKit.getInstance().getConnectionState().isConnected()) {
                                ToastUtil.showShort(mApplication.getApplicationContext(), "即时消息未连接,请重新登录!");
                            } else {
                                Intent intent = new Intent(mApplication, BackGroundService.class);
                                mApplication.startService(intent);
                            }
                        }
                    });
        }
    
        public void stopBgService() {
            mStop = true;
            if (observable != null) {
                observable.unsubscribeOn(Schedulers.io());
            }
            try {
                mApplication.stopService(new Intent(mApplication, BackGroundService.class));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    
        public Application getApplication() {
            return mApplication;
        }
    
        public String getString(int resId) {
            return mApplication.getString(resId);
        }
    
        public AppSharedPreferences getConfiguration() {
            return mConfiguration;
        }
    
        public AppSharedPreferences getTest() {
            return mTest;
        }
    
        public void setCurrentUser(LoginInfo.Session session) {
            if (session != null) {
                isLogined = true;
            }
            mCurrentUser = session;
            KEY_CONTACT_SUCCEFFUL = "key_contact_successful" + CoreModule.getInstance().getCurrentIdentity();
        }
    
        public boolean isLogined() {
            return isLogined;
        }
    
        public UserEntity getUserEntity() {
            if (mUserEntity == null) {
                mUserEntity = new UserEntity();
            }
            return mUserEntity;
        }
    
        public void setUserEntity(UserEntity userEntity) {
            if (userEntity != null) {
                mUserEntity = BeanCloneUtil.copy(userEntity);
            } else {
                mUserEntity = new UserEntity();
            }
        }
    
        public String getKEY_CONTACT_SUCCEFFUL() {
            return KEY_CONTACT_SUCCEFFUL;
        }
    
    
        public String getChannel() {
            if (channel.equals(CHANNEL_CQJZ) || channel.equals(CHANNEL_CQJZAQ)) {
                channel = CHANNEL_CQJZ;
            }
            return channel;
        }
    
        public LoginInfo.Session getCurrentUser() {
            return mCurrentUser;
        }
    
        public String getCurrentIdentity() {
            if (mCurrentUser != null) {
                return mCurrentUser.getUserId();
            } else {
                return "";
            }
        }
    
        public String getCurrentUserName() {
            if (mCurrentUser != null) {
                return mCurrentUser.getUsername();
            } else {
                return "";
            }
        }
    
        public Observable<Boolean> doWorksAfterLoginRx() {
            return Observable.create(new ObservableOnSubscribe<Boolean>() {
                @Override
                public void subscribe(final ObservableEmitter<Boolean> observableEmitter) throws Exception {
                    Log.i("CoreModule", "doWorksAfterLoginRx");
                    MessageRepository.getInstance().doAfterLogin();
                    Observable<Boolean> contactRepositoryObservable = Observable.create(new ObservableOnSubscribe<Boolean>() {
                        @Override
                        public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
                            ContactRepository.getInstance().doAfterLogin(e);
                        }
                    });
    
                    Observable<Boolean> groupRepositroyObservable = Observable.create(new ObservableOnSubscribe<Boolean>() {
                        @Override
                        public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
                            GroupRepository.getInstance().doAfterLogin(e);
                        }
                    });
    
                    Observable.zip(contactRepositoryObservable, groupRepositroyObservable, new BiFunction<Boolean, Boolean, Boolean>() {
                        @Override
                        public Boolean apply(Boolean s, Boolean s2) throws Exception {
                            mLogger.info("doWorksAfterLoginRx" + s + s2);
                            Log.i("CoreModule", "doWorksAfterLoginRx" + s + s2);
                            if (s && !TextUtils.isEmpty(KEY_CONTACT_SUCCEFFUL)) {
                                getConfiguration().putBoolean(KEY_CONTACT_SUCCEFFUL, true);
                                getConfiguration().commit();
                                mLogger.info("即将开始计算人数!");
                                //ContactRepository.getInstance().loadUnitPeopleSizeSync();
                            } else if (!s) {
                                getConfiguration().putBoolean(KEY_CONTACT_SUCCEFFUL, false);
                                getConfiguration().commit();
                            }
                            observableEmitter.onNext(s2);
                            observableEmitter.onComplete();
                            return s && s2;
                        }
                    }).subscribeOn(Schedulers.io())
                            .subscribe(new Consumer<Boolean>() {
                                @Override
                                public void accept(Boolean s) throws Exception {
                                    if (s) {
                                        //更新联系人界面显示
                                        RxBus.publish(CoreSubject.CONTACT_LOAD_FINISH, ResultCode.CODE_SUCCESS);
                                        EventMsgRepository.getInstance().doAfterLogin();
                                    } else {
                                        RxBus.publish(CoreSubject.CONTACT_LOAD_FINISH, -1);
                                    }
                                }
                            });
    
                    SystemRepository.getInstance().doAfterLogin();
    
                    ConferenceRepository.getInstance().doAfterLogin();
    
                    EmojiRepository.getInstance().doAfterLogin();
    
                }
            }).subscribeOn(Schedulers.io());
        }
    
        public void doWorksAfterLogin() {
            MessageRepository.getInstance().doAfterLogin();
            Observable<Boolean> contactRepositoryObservable = Observable.create(new ObservableOnSubscribe<Boolean>() {
                @Override
                public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
                    ContactRepository.getInstance().doAfterLogin(e);
                }
            });
    
            Observable<Boolean> groupRepositroyObservable = Observable.create(new ObservableOnSubscribe<Boolean>() {
                @Override
                public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
                    GroupRepository.getInstance().doAfterLogin(e);
                }
            });
    
            Observable.zip(contactRepositoryObservable, groupRepositroyObservable, new BiFunction<Boolean, Boolean, Boolean>() {
                @Override
                public Boolean apply(Boolean s, Boolean s2) throws Exception {
                    if (s && !TextUtils.isEmpty(KEY_CONTACT_SUCCEFFUL)) {
                        getConfiguration().putBoolean(KEY_CONTACT_SUCCEFFUL, true);
                        getConfiguration().commit();
                        //ContactRepository.getInstance().loadUnitPeopleSizeSync();
                    } else if (!s) {
                        getConfiguration().putBoolean(KEY_CONTACT_SUCCEFFUL, false);
                        getConfiguration().commit();
                    }
                    return s && s2;
                }
            }).subscribeOn(Schedulers.io())
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean s) throws Exception {
                            if (s) {
                                //更新联系人界面显示
                                RxBus.publish(CoreSubject.CONTACT_LOAD_FINISH, ResultCode.CODE_SUCCESS);
                                EventMsgRepository.getInstance().doAfterLogin();
                            } else {
                                RxBus.publish(CoreSubject.CONTACT_LOAD_FINISH, -1);
                            }
                        }
                    });
    
            SystemRepository.getInstance().doAfterLogin();
            //ConnectManager.getInstance().connectDetection(getApplication());
            ConferenceRepository.getInstance().doAfterLogin();
            EmojiRepository.getInstance().doAfterLogin();
        }
    
        public String getImId() {
            return IctKit.getInstance().getImId();
        }
    
        public String getPocId() {
            if (IctKit.getInstance().getPocId() != null) {
                return IctKit.getInstance().getPocId();
            }
            return "";
        }
    
        //注销
        public void logout() {
            isLogined = false;
            stopBgService();
            CoreModule.getInstance().setCurrentUser(null);
            SystemRepository.getInstance().logOutIct();
            //ContactRepository.getInstance().clearState();
            ContactDatabase.clearState();
    
            IctKit.getInstance().unRegister();
            IctKit.getInstance().clear(mApplication.getApplicationContext());
            PublicUtil.setBadge(0);
            ContactRepository.clear();
            GroupRepository.clear();
            DataCache.clear();
        }
    
        //退出
        public void exit() {
            logout();
            IctKit.getInstance().unRegister();
            IctKit.getInstance().clear(mApplication.getApplicationContext());
            ThreadPoolUtils.executeTask(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ThreadPoolUtils.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            for (Activity activity : ActivityList.getInstance().getActivityList()) {
                                activity.finish();
                            }
                        }
                    });
                }
            });
    /*
            ThreadPoolUtils.executeTask(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    android.os.Process.killProcess(android.os.Process.myPid());
                    System.exit(1);
                }
            });
    */
    
        }
    }
    
    

    相关文章

      网友评论

          本文标题:增加通信进程保活

          本文链接:https://www.haomeiwen.com/subject/itjnortx.html