/dateLoveInternational/src/main/java/com/datelove/online/International/activity/MainActivity.java
Java | 1470 lines | 1065 code | 155 blank | 250 comment | 186 complexity | 3c53a39898477ba2d50b624da276de22 MD5 | raw file
- package com.datelove.online.International.activity;
- import android.Manifest;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.content.pm.PackageManager;
- import android.location.Location;
- import android.location.LocationListener;
- import android.location.LocationManager;
- import android.os.Build;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.os.PersistableBundle;
- import android.os.Vibrator;
- import android.support.annotation.NonNull;
- import android.support.annotation.Nullable;
- import android.support.v4.app.ActivityCompat;
- import android.support.v4.app.Fragment;
- import android.support.v4.app.FragmentManager;
- import android.support.v4.app.FragmentPagerAdapter;
- import android.support.v4.content.ContextCompat;
- import android.support.v4.view.ViewPager;
- import android.text.TextUtils;
- import android.util.Log;
- import android.view.KeyEvent;
- import android.view.View;
- import android.view.WindowManager;
- import android.view.animation.Animation;
- import android.view.animation.AnimationSet;
- import android.view.animation.AnimationUtils;
- import android.view.animation.TranslateAnimation;
- import android.widget.FrameLayout;
- import android.widget.ImageView;
- import android.widget.LinearLayout;
- import android.widget.RelativeLayout;
- import android.widget.TextView;
- import android.widget.Toast;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONArray;
- import com.alibaba.fastjson.JSONObject;
- import com.datelove.online.International.R;
- import com.datelove.online.International.base.BaseFragmentActivity;
- import com.datelove.online.International.bean.BaseModel;
- import com.datelove.online.International.bean.FateUser;
- import com.datelove.online.International.bean.HeadMsgNotice;
- import com.datelove.online.International.bean.Image;
- import com.datelove.online.International.bean.LocationInfo;
- import com.datelove.online.International.bean.MsgBox;
- import com.datelove.online.International.bean.NewHeadMsgNotice;
- import com.datelove.online.International.bean.RecommendUser;
- import com.datelove.online.International.bean.User;
- import com.datelove.online.International.bean.UserBase;
- import com.datelove.online.International.constant.IUrlConstant;
- import com.datelove.online.International.event.BaseOpenMailFragmentEvent;
- import com.datelove.online.International.event.CloseMainActivityEvent;
- import com.datelove.online.International.event.HeadMsgEvent;
- import com.datelove.online.International.event.MatchInfoChangeEvent;
- import com.datelove.online.International.event.MessageChangedEvent;
- import com.datelove.online.International.event.NoSeeMeEvent;
- import com.datelove.online.International.event.OpenMailFragmentEvent;
- import com.datelove.online.International.event.RegistEvent;
- import com.datelove.online.International.event.UpdateMessageCountEvent;
- import com.datelove.online.International.event.UpdateUserProvince;
- import com.datelove.online.International.fragment.FateCardFragment;
- import com.datelove.online.International.fragment.MeFragment;
- import com.datelove.online.International.fragment.MessageFragment;
- import com.datelove.online.International.fragment.SearchFragment;
- import com.datelove.online.International.utils.CommonRequestUtil;
- import com.datelove.online.International.utils.Utils;
- import com.datelove.online.International.xml.PlatformInfoXml;
- import com.datelove.online.International.xml.UserInfoXml;
- import com.library.imageloader.ImageLoader;
- import com.library.imageloader.ImageLoaderUtil;
- import com.library.utils.HeightUtils;
- import com.library.utils.LogUtil;
- import com.library.utils.SharedPreferenceUtil;
- import com.library.utils.Util;
- import com.library.widgets.CircleImageView;
- import com.library.widgets.ScrollControlViewPager;
- import com.zhy.http.okhttp.OkHttpUtils;
- import com.zhy.http.okhttp.callback.Callback;
- import com.zhy.http.okhttp.callback.StringCallback;
- import org.greenrobot.eventbus.EventBus;
- import org.greenrobot.eventbus.Subscribe;
- import java.lang.ref.WeakReference;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import butterknife.BindView;
- import butterknife.OnClick;
- import okhttp3.Call;
- import okhttp3.Response;
- import static com.datelove.online.International.utils.GoogleUtil.getGoogleProviceL1Key;
- //import com.datelove.online.International.fragment.NearbyFragment;
- /**
- * modified by zhangdroid on 2017-02-28
- */
- public class MainActivity extends BaseFragmentActivity {
- @BindView(R.id.viewPager)
- ScrollControlViewPager mViewPager;
- // 页眉
- @BindView(R.id.head_msg_container)
- RelativeLayout mRlHeadMsgContainer;
- @BindView(R.id.head_msg_content)
- TextView mTvHeadMsgContent;
- @BindView(R.id.head_msg_clear)
- ImageView mIvHeadMsgClear;
- // 新页眉
- @BindView(R.id.headMsg_container)
- FrameLayout mFlHeadMsgNew;
- @BindView(R.id.headMsg_unread)
- RelativeLayout mRlHeadMsgUnread;
- @BindView(R.id.headMsg_avatar)
- CircleImageView mIvHeadMsgAvatar;
- @BindView(R.id.headMsg_nickname)
- TextView mTvNickname;
- @BindView(R.id.headMsg_age)
- TextView mTvAge;
- @BindView(R.id.headMsg_height)
- TextView mTvHeight;
- @BindView(R.id.headMsg_content)
- TextView mTvMsgContent;
- @BindView(R.id.headMsg_check)
- TextView mTvMsgCheck;
- // 访客
- @BindView(R.id.headMsg_visitor)
- RelativeLayout mRlHeadMsgVisitor;
- @BindView(R.id.visitor_avatar)
- CircleImageView mIvVisitorAvatar;
- @BindView(R.id.visitor_content)
- TextView mTvVisitorContent;
- @BindView(R.id.visitor_ignore)
- TextView mTvVisitorIgnore;
- @BindView(R.id.visitor_look)
- TextView mTvVisitorLook;
- // 推荐用户
- @BindView(R.id.recommend_user_container)
- LinearLayout mLlRecommendUser;
- @BindView(R.id.recommend_user_avatar)
- CircleImageView mIvRecommendAvatar;
- @BindView(R.id.recommend_user_content)
- TextView mTvRecommendContent;
- @BindView(R.id.recommend_user_ignore)
- TextView mTvRecommendIgnore;
- @BindView(R.id.recommend_user_look)
- TextView mTvRecommendLook;
- // tab页
- @BindView(R.id.main_tab_fate)
- TextView mTvTabFate;
- @BindView(R.id.main_tab_search)
- TextView mTvTabSearch;
- @BindView(R.id.main_tab_mail)
- TextView mTvTabMail;
- @BindView(R.id.unread_msg_count)
- TextView mTvUnreadMsgCount;// 未读消息数
- @BindView(R.id.main_tab_nearby)
- TextView mTvTabNearby;
- @BindView(R.id.main_tab_me)
- TextView mTvTabMe;
- private static final int TAB_INDEX_FATE = 0;
- private static final int TAB_INDEX_SEARCH = 1;
- private static final int TAB_INDEX_MAIL = 2;
- private static final int TAB_INDEX_NEARBY = 4;
- private static final int TAB_INDEX_ME = 3;
- private static final int HEAD_MSG_REFRESH_PERIOD = 20 * 1000;
- private static final int MSG_TYPE_LOAD_DATA = 1;
- private static final int MSG_TYPE_HEAD_MSG = 2;
- private static final int MSG_TYPE_HEAD_MSG_NEW = 3;
- private static final int MSG_TYPE_RECOMMEND_USER = 4;
- private static final int MSG_TYPE_SHOW_UNREAD_MSG = 5;
- private static final int MSG_TYPE_DISMISS_UNREAD_MSG = 6;
- private static final int MSG_TYPE_DISMISS_VISITOR = 7;
- private static final int MSG_TYPE_HIDE_RECOMMEND_USER = 8;
- private static final int PERMISSION_CODE_ACCESS_FINE_LOCATION = 0;
- private boolean mReceiverTag = false; //广播接受者标识
- @BindView(R.id.iv_loading_heart)
- ImageView ivLoadingHeart;
- @BindView(R.id.fl_loading)
- FrameLayout flLoading;
- @BindView(R.id.tv_loading)
- TextView tvLoading;
- private LocationManager mLocationManager;
- /**
- * 页眉对象缓存
- */
- private HeadMsgNotice mHeadMsgNotice;
- /**
- * 新页眉对象缓存
- */
- private NewHeadMsgNotice mNewHeadMsgNotice;
- /**
- * 推荐用户对象缓存
- */
- private RecommendUser mRecommendUser;
- /**
- * 新页眉最后一条未读消息毫秒数
- */
- private long mLastMsgTime;
- /**
- * 推荐用户轮询周期(秒)
- */
- private int cycle;
- /**
- * 新页眉中当前正在显示的未读消息索引
- */
- private int mCurrDisplayItem;
- private TimerHandler mTimerHandler;
- private Context mContext;
- private Vibrator vibrator;
- private boolean isShake = true;
- private MainAdapter mainAdapter;
- private int currentUnreadMsgCount;
- private boolean isNewHeadMsg;
- private boolean getProvince = false;
- private int firstIntoSearch=0;
- private String getLatitude;
- private String getLongitude;
- private boolean againGetLocation=false;
- private String getProvinceFromSplash;
- private boolean isPause=false;
- private boolean isStartAnim;
- private AnimationSet animationSet;
- // private boolean stopRecommend=false;
- // private boolean stopMsg=false;
- @Override
- protected int getLayoutResId() {
- return R.layout.activity_main;
- }
- @Override
- protected void initViewsAndVariables() {
- // 设置状态栏
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 5.0及以上
- View decorView = getWindow().getDecorView();
- decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
- // 设置状态栏背景
- getWindow().setStatusBarColor(getResources().getColor(R.color.main_color));
- } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {// 4.4
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
- }
- mainAdapter = new MainAdapter(getSupportFragmentManager());
- mViewPager.setAdapter(mainAdapter);
- mViewPager.setCanScroll(false);
- mViewPager.setOffscreenPageLimit(4);
- /**显示加载动画**/
- flLoading.setVisibility(View.VISIBLE);
- tvLoading.setVisibility(View.VISIBLE);
- Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.anim_show_loading);
- ivLoadingHeart.startAnimation(hyperspaceJumpAnimation);
- SharedPreferenceUtil.setBooleanValue(Utils.getContext(), "INTERCEPT_DIALOG", "INTERCEPT", false);
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- flLoading.setVisibility(View.GONE);
- tvLoading.setVisibility(View.GONE);
- }
- }, 2000);
- mViewPager.setCurrentItem(TAB_INDEX_FATE);
- mTvTabFate.setSelected(true);
- /**对viewPage的界面改变进行监听,当刷新聊天列表的界面开始刷新,刷出聊天列表界面停止刷新**/
- mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
- @Override
- public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
- }
- @Override
- public void onPageSelected(int position) {
- MessageFragment item = (MessageFragment) mainAdapter.getItem(2);
- if (position != 2) {
- item.stopRefish();
- } else {
- item.startFirstRefish();
- }
- }
- @Override
- public void onPageScrollStateChanged(int state) {
- }
- });
- // 获取位置信息并上传
- requestLocation();
- // 延时加载数据
- mTimerHandler = new TimerHandler(this);
- mTimerHandler.sendEmptyMessageDelayed(MSG_TYPE_LOAD_DATA, 1000 * 20);
- //注册广播
- // registerReceiver(mHomeKeyEventReceiver, new IntentFilter(
- // Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
- if (!mReceiverTag){ //在注册广播接受者的时候 判断是否已被注册,避免重复多次注册广播
- IntentFilter mFileter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
- mReceiverTag = true; //标识值 赋值为 true 表示广播已被注册
- this.registerReceiver(mHomeKeyEventReceiver, mFileter);
- }
- }
- /**
- * 加载页眉和推荐用户
- */
- private void loadData() {
- // 获取页眉
- // if (UserInfoXml.isShowHeadMsg()) {
- // getHeadMsg();
- //// mTimerHandler.sendEmptyMessageDelayed(MSG_TYPE_HEAD_MSG, HEAD_MSG_REFRESH_PERIOD);
- // }
- // 获取新页眉
- if (UserInfoXml.isShowHeadMsgNew()) {
- getNewHeadMsg();
- }
- // 获取推荐用户
- if (UserInfoXml.isShowRecommendUser()) {
- getRecommendUsr();
- // mTimerHandler.sendEmptyMessageDelayed(MSG_TYPE_RECOMMEND_USER, HEAD_MSG_REFRESH_PERIOD);
- }
- }
- /**
- * 获取页眉
- */
- private void getHeadMsg() {
- // CommonRequestUtil.getHeadMsg(new CommonRequestUtil.OnGetHeadMsgListener() {
- // @Override
- // public void onSuccess(HeadMsgNotice headMsgNotice) {
- // if (headMsgNotice != null) {
- // mHeadMsgNotice = headMsgNotice;
- // String message = headMsgNotice.getMessage();
- // if (mViewPager.getCurrentItem() != TAB_INDEX_MAIL && !TextUtils.isEmpty(message)) {
- // mRlHeadMsgContainer.setVisibility(View.VISIBLE);
- // mTvHeadMsgContent.setText(message);
- // } else {
- // mRlHeadMsgContainer.setVisibility(View.GONE);
- // }
- // String noticeType = headMsgNotice.getNoticeType();
- // if (!TextUtils.isEmpty(noticeType) && "1".equals(noticeType)) {
- // // 有未读消息时刷新消息列表
- // EventBus.getDefault().post(new MessageChangedEvent());
- // }
- // }
- // }
- //
- // @Override
- // public void onFail() {
- //
- // }
- // });
- }
- /**
- * 获取新页眉
- */
- private void getNewHeadMsg() {
- String lastMsgTime = new SharedPreferenceUtil(MainActivity.this).takeLastTime();
- if (!TextUtils.isEmpty(lastMsgTime)) {
- mLastMsgTime = Long.parseLong(lastMsgTime);
- }
- CommonRequestUtil.getNewHeadMsg(mLastMsgTime, new CommonRequestUtil.OnGetNewHeadMsgListener() {
- @Override
- public void onSuccess(NewHeadMsgNotice newHeadMsgNotice) {
- if (newHeadMsgNotice != null) {
- mNewHeadMsgNotice = newHeadMsgNotice;
- mLastMsgTime = newHeadMsgNotice.getLastMsgTime();
- //将时间戳保存下来
- new SharedPreferenceUtil(MainActivity.this).saveLastTime(mLastMsgTime);
- mCurrDisplayItem = 0;
- String noticeType = newHeadMsgNotice.getNoticeType();
- if (!TextUtils.isEmpty(noticeType)) {
- switch (noticeType) {
- case "0":// 没有页眉,继续轮询
- mTimerHandler.sendEmptyMessageDelayed(MSG_TYPE_HEAD_MSG_NEW, HEAD_MSG_REFRESH_PERIOD);
- break;
- case "1":// 未读消息
- // isNewHeadMsg=true;
- // 刷新聊天列表
- EventBus.getDefault().post(new MessageChangedEvent());
- setNewHeadMsg();
- break;
- case "2":// 访客
- FateUser fateUser = newHeadMsgNotice.getRemoteYuanfenUserBase();
- if (fateUser != null) {
- UserBase userBase = fateUser.getUserBaseEnglish();
- if (userBase != null) {
- if(mIvVisitorAvatar!=null && mIvVisitorAvatar.getVisibility()!=View.GONE){
- ImageLoaderUtil.getInstance().loadImage(MainActivity.this, new ImageLoader.Builder()
- .url(userBase.getImage().getThumbnailUrl()).imageView(mIvVisitorAvatar).build());
- mTvVisitorContent.setText(getString(R.string.visitor_tip, userBase.getNickName()));
- }
- }
- }
- if(mRlHeadMsgUnread!=null && mRlHeadMsgVisitor!=null){
- mRlHeadMsgUnread.setVisibility(View.GONE);
- mRlHeadMsgVisitor.setVisibility(View.VISIBLE);
- }
- showWithAnim(mFlHeadMsgNew);
- // mTimerHandler.sendEmptyMessageDelayed(MSG_TYPE_DISMISS_VISITOR, newHeadMsgNotice.getDisplaySecond() * 1000);
- mTimerHandler.sendEmptyMessageDelayed(MSG_TYPE_DISMISS_VISITOR, 3 * 1000);
- break;
- }
- }
- }
- }
- @Override
- public void onFail() {
- mTimerHandler.sendEmptyMessageDelayed(MSG_TYPE_HEAD_MSG_NEW, HEAD_MSG_REFRESH_PERIOD);
- }
- });
- }
- /**
- * 按照未读消息列表顺序显示未读信
- */
- private void setNewHeadMsg() {
- if (mNewHeadMsgNotice != null) {
- List<MsgBox> msgBoxList = mNewHeadMsgNotice.getUnreadMsgBoxList();
- if (!Util.isListEmpty(msgBoxList) && mCurrDisplayItem < msgBoxList.size()) {
- MsgBox msgBox = msgBoxList.get(mCurrDisplayItem);
- if (msgBox != null) {
- UserBase userBase = msgBox.getUserBaseEnglish();
- if (userBase != null) {
- Image image = userBase.getImage();
- if (image != null) {
- if(ImageLoaderUtil.getInstance()!=null){
- }
- ImageLoaderUtil.getInstance().loadImage(MainActivity.this, new ImageLoader.Builder()
- .url(image.getThumbnailUrl()).imageView(mIvHeadMsgAvatar).build());
- }
- mTvNickname.setText(userBase.getNickName());
- mTvAge.setText(TextUtils.concat(String.valueOf(userBase.getAge())));
- mTvAge.setSelected(userBase.getSex() == 0);
- if (userBase.getSex() == 0) {
- mTvAge.setBackgroundResource(R.drawable.shape_round_rectangle_blue_bg);
- } else {
- mTvAge.setBackgroundResource(R.drawable.shape_notification_age_women);
- }
- mTvHeight.setText(HeightUtils.getInchCmByCm(userBase.getHeightCm()));
- }
- String msgContent = msgBox.getMsg();
- if (!TextUtils.isEmpty(msgContent)) {
- // mTvMsgContent.setText(msgContent);
- mTvMsgContent.setText(getString(R.string.get_msg));
- }
- mRlHeadMsgUnread.setVisibility(View.VISIBLE);
- mRlHeadMsgVisitor.setVisibility(View.GONE);
- showWithAnim(mFlHeadMsgNew);
- }
- // 一段时间后显示下一条未读消息
- // mTimerHandler.sendEmptyMessageDelayed(MSG_TYPE_SHOW_UNREAD_MSG, mNewHeadMsgNotice.getDisplaySecond() * 1000);
- mTimerHandler.sendEmptyMessageDelayed(MSG_TYPE_SHOW_UNREAD_MSG, 5 * 1000);
- }
- }
- }
- private void showWithAnim(View view) {
- if (isShake) {
- view.setVisibility(View.VISIBLE);
- vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
- vibrator.vibrate(200);
- view.startAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.anim_in));
- }
- // view.startAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.push_bottom_in));
- }
- private void dismissWithAnim(final View view, final View view2) {
- // Animation outAnimation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.push_bottom_out);
- if(view!=null && view2!=null){
- Animation outAnimation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.anim_out);
- view.startAnimation(outAnimation);
- outAnimation.setAnimationListener(new Animation.AnimationListener() {
- @Override
- public void onAnimationStart(Animation animation) {
- }
- @Override
- public void onAnimationEnd(Animation animation) {
- view.setVisibility(View.GONE);
- view2.setVisibility(View.GONE);
- }
- @Override
- public void onAnimationRepeat(Animation animation) {
- }
- });
- }
- }
- /**
- * 获取推荐用户
- */
- private void getRecommendUsr() {
- CommonRequestUtil.getRecommendUser(cycle, new CommonRequestUtil.OnGetRecommendUserListener() {
- @Override
- public void onSuccess(RecommendUser recommendUser) {
- if (recommendUser != null) {
- mRecommendUser = recommendUser;
- cycle = recommendUser.getCycle();
- User user = recommendUser.getUser();
- if (user != null) {
- UserBase userBase = user.getUserBaseEnglish();
- if (userBase != null) {
- // 显示推荐用户
- if(mLlRecommendUser!=null && mTvRecommendContent!=null){
- mLlRecommendUser.setVisibility(View.VISIBLE);
- mTvRecommendContent.setText(TextUtils.concat(userBase.getNickName(), " ", recommendUser.getSentence()));
- }
- if(mIvRecommendAvatar!=null){
- ImageLoaderUtil.getInstance().loadImage(MainActivity.this, new ImageLoader.Builder()
- .url(userBase.getImage().getThumbnailUrl()).imageView(mIvRecommendAvatar).build());
- }
- showWithAnim(mLlRecommendUser);
- }
- }
- }
- // 一段时间后隐藏推荐用户
- mTimerHandler.sendEmptyMessageDelayed(MSG_TYPE_HIDE_RECOMMEND_USER, 5 * 1000);
- }
- @Override
- public void onFail() {
- // 一段时间后隐藏推荐用户
- mTimerHandler.sendEmptyMessageDelayed(MSG_TYPE_HIDE_RECOMMEND_USER, 5 * 1000);
- }
- });
- }
- @Override
- protected void addListeners() {
- mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
- @Override
- public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
- }
- @Override
- public void onPageSelected(int position) {
- switch (position) {
- case TAB_INDEX_FATE:
- mTvTabFate.setSelected(true);
- mTvTabSearch.setSelected(false);
- mTvTabMail.setSelected(false);
- mTvTabNearby.setSelected(false);
- mTvTabMe.setSelected(false);
- break;
- case TAB_INDEX_SEARCH:
- mTvTabFate.setSelected(false);
- mTvTabSearch.setSelected(true);
- mTvTabMail.setSelected(false);
- mTvTabNearby.setSelected(false);
- mTvTabMe.setSelected(false);
- firstIntoSearch++;
- if(firstIntoSearch==1){
- flLoading.setVisibility(View.VISIBLE);
- tvLoading.setVisibility(View.VISIBLE);
- Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.anim_show_loading);
- ivLoadingHeart.startAnimation(hyperspaceJumpAnimation);
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- flLoading.setVisibility(View.GONE);
- tvLoading.setVisibility(View.GONE);
- }
- }, 2000);
- }
- break;
- case TAB_INDEX_MAIL:
- mTvTabFate.setSelected(false);
- mTvTabSearch.setSelected(false);
- mTvTabMail.setSelected(true);
- mTvTabNearby.setSelected(false);
- mTvTabMe.setSelected(false);
- // 信箱tab页不显示页眉
- if (mRlHeadMsgContainer.isShown()) {
- mRlHeadMsgContainer.setVisibility(View.GONE);
- }
- // // 隐藏新页眉
- // if (mFlHeadMsgNew.isShown()) {
- // mFlHeadMsgNew.setVisibility(View.GONE);
- // if (mTimerHandler != null) {
- // mTimerHandler.removeMessages(MSG_TYPE_SHOW_UNREAD_MSG);
- // }
- // }
- break;
- case TAB_INDEX_NEARBY:
- mTvTabFate.setSelected(false);
- mTvTabSearch.setSelected(false);
- mTvTabMail.setSelected(false);
- mTvTabNearby.setSelected(true);
- mTvTabMe.setSelected(true);
- break;
- case TAB_INDEX_ME:
- mTvTabFate.setSelected(false);
- mTvTabSearch.setSelected(false);
- mTvTabMail.setSelected(false);
- mTvTabNearby.setSelected(true);
- mTvTabMe.setSelected(true);
- break;
- }
- }
- @Override
- public void onPageScrollStateChanged(int state) {
- }
- });
- // 查看页眉消息
- mRlHeadMsgContainer.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (mHeadMsgNotice != null) {
- mRlHeadMsgContainer.setVisibility(View.GONE);
- String noticeType = mHeadMsgNotice.getNoticeType();
- if (!TextUtils.isEmpty(noticeType)) {
- switch (noticeType) {
- case "1": // 未读消息
- if (mViewPager.getCurrentItem() != TAB_INDEX_MAIL) {
- mViewPager.setCurrentItem(TAB_INDEX_MAIL, false);
- }
- break;
- case "2":// 正在看我
- UserInfoDetailActivity.toUserInfoDetailActivity(MainActivity.this, mHeadMsgNotice.getRemoteUserId(), null, UserInfoDetailActivity.SOURCE_HEAD_MSG);
- break;
- }
- }
- }
- }
- });
- mIvHeadMsgClear.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- mRlHeadMsgContainer.setVisibility(View.GONE);
- }
- });
- // 新页眉
- mRlHeadMsgUnread.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // 查看未读消息,进入聊天页面
- mFlHeadMsgNew.setVisibility(View.GONE);
- if (mNewHeadMsgNotice != null && mCurrDisplayItem < mNewHeadMsgNotice.getUnreadMsgBoxList().size()) {
- List<MsgBox> msgBoxList = mNewHeadMsgNotice.getUnreadMsgBoxList();
- if (!Util.isListEmpty(msgBoxList)) {
- MsgBox msgBox = msgBoxList.get(mCurrDisplayItem);
- if (msgBox != null) {
- UserBase userBase = msgBox.getUserBaseEnglish();
- if (userBase != null) {
- ChatActivity.toChatActivity(MainActivity.this, userBase.getId(), userBase.getNickName(), userBase.getImage().getThumbnailUrl());
- }
- }
- }
- }
- }
- });
- mTvVisitorLook.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // 隐藏新页眉
- mRlHeadMsgVisitor.setVisibility(View.GONE);
- mFlHeadMsgNew.setVisibility(View.GONE);
- // 查看用户详情
- if (mNewHeadMsgNotice != null) {
- FateUser fateUser = mNewHeadMsgNotice.getRemoteYuanfenUserBase();
- if (fateUser != null) {
- UserBase userBase = fateUser.getUserBaseEnglish();
- if (userBase != null) {
- UserInfoDetailActivity.toUserInfoDetailActivity(MainActivity.this, userBase.getId(), null, UserInfoDetailActivity.SOURCE_HEAD_MSG);
- }
- }
- }
- }
- });
- mTvVisitorIgnore.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // 隐藏新页眉
- mRlHeadMsgVisitor.setVisibility(View.GONE);
- mFlHeadMsgNew.setVisibility(View.GONE);
- }
- });
- // 推荐用户
- mTvRecommendLook.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (mRecommendUser != null) {
- UserBase userBase = mRecommendUser.getUser().getUserBaseEnglish();
- if (userBase != null) {
- // 隐藏推荐用户
- mLlRecommendUser.setVisibility(View.GONE);
- Image image = userBase.getImage();
- if (UserInfoXml.isMale()) {
- if (UserInfoXml.isMonthly()) {// 已付费男用户进入聊天页
- ChatActivity.toChatActivity(MainActivity.this, userBase.getId(), userBase.getNickName(),
- image == null ? null : image.getThumbnailUrl());
- } else {// 未付费男用户,进入对方空间页
- UserInfoDetailActivity.toUserInfoDetailActivity(MainActivity.this, userBase.getId(), null, UserInfoDetailActivity.SOURCE_FROM_RECOMMEND_USER);
- }
- } else {// 女用户进入聊天页
- ChatActivity.toChatActivity(MainActivity.this, userBase.getId(), userBase.getNickName(),
- image == null ? null : image.getThumbnailUrl());
- }
- }
- }
- }
- });
- mTvRecommendIgnore.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // 隐藏推荐用户
- mLlRecommendUser.setVisibility(View.GONE);
- }
- });
- }
- @OnClick({R.id.main_tab_fate, R.id.main_tab_search, R.id.main_tab_mail, R.id.main_tab_nearby, R.id.main_tab_me})
- public void onClick(View view) {
- switch (view.getId()) {
- case R.id.main_tab_fate:
- mViewPager.setCurrentItem(TAB_INDEX_FATE);
- break;
- case R.id.main_tab_search:
- mViewPager.setCurrentItem(TAB_INDEX_SEARCH);
- break;
- case R.id.main_tab_mail:
- mViewPager.setCurrentItem(TAB_INDEX_MAIL);
- break;
- case R.id.main_tab_nearby:
- mViewPager.setCurrentItem(TAB_INDEX_NEARBY);
- break;
- case R.id.main_tab_me:
- mViewPager.setCurrentItem(TAB_INDEX_ME);
- break;
- }
- }
- /**
- * 请求定位信息
- */
- private void requestLocation() {
- getLatitude = SharedPreferenceUtil.getStringValue(MainActivity.this, "LOCATION", "getLatitude", "");
- getLongitude = SharedPreferenceUtil.getStringValue(MainActivity.this, "LOCATION", "getLongitude", "");
- getProvinceFromSplash =SharedPreferenceUtil.getStringValue(MainActivity.this,"GET_PROVINCE","province","");
- String country = UserInfoXml.getCountry();
- if (TextUtils.isEmpty(getLatitude) || TextUtils.isEmpty(getLongitude) || TextUtils.isEmpty(country)) {
- // 经纬度为空,重新定位
- mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
- if (ContextCompat.checkSelfPermission(MainActivity.this,
- Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED) {
- // 请求android.permission.ACCESS_FINE_LOCATION
- ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_CODE_ACCESS_FINE_LOCATION);
- } else {
- if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {// Network定位
- mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 5, mLocationListener);
- } else if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {// GPS定位
- uploadLocation(mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
- }
- }
- } else if(TextUtils.isEmpty(getProvinceFromSplash)){
- // 城市为空,重新请求谷歌获取城市的接口
- getAddress(getLatitude, getLongitude,"English", country);
- }else{
- // 都不为空,调用位置接口
- getLocation(getLatitude, getLongitude, getProvinceFromSplash);
- }
- }
- private LocationListener mLocationListener = new LocationListener() {
- @Override
- public void onLocationChanged(Location location) {
- uploadLocation(location);
- }
- @Override
- public void onStatusChanged(String provider, int status, Bundle extras) {
- }
- @Override
- public void onProviderEnabled(String provider) {
- }
- @Override
- public void onProviderDisabled(String provider) {
- }
- };
- @Override
- public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
- if (requestCode == PERMISSION_CODE_ACCESS_FINE_LOCATION) {
- if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {// 申请权限成功
- if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {// Network定位
- if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
- // TODO: Consider calling
- // ActivityCompat#requestPermissions
- // here to request the missing permissions, and then overriding
- // public void onRequestPermissionsResult(int requestCode, String[] permissions,
- // int[] grantResults)
- // to handle the case where the user grants the permission. See the documentation
- // for ActivityCompat#requestPermissions for more details.
- return;
- }
- mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 5, mLocationListener);
- } else if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {// GPS定位
- uploadLocation(mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
- }
- }
- }
- }
- /**
- * 上传位置信息
- *
- * @param location 定位成功后的信息
- */
- private void uploadLocation(Location location) {
- if (location != null) {
- String getLatitude = String.valueOf(location.getLatitude());
- String getLongitude = String.valueOf(location.getLongitude());
- String country = UserInfoXml.getCountry();
- againGetLocation=true;
- getAddress(getLatitude, getLongitude,"English", country);
- // Map<String, String> googleAddress = GoogleUtil.getGoogleAddress(getLatitude, getLongitude, "English", country);
- // if (googleAddress != null) {
- // String province = googleAddress.get("province");
- //// 英国城市为空。。。
- // if (!TextUtils.isEmpty(province) && !province.equals(UserInfoXml.getProvinceName())) {
- // UserInfoXml.setProvinceName(province);
- // getProvince = true;
- // }
- // getLocation(getLatitude, getLongitude, province);
- // }
- }
- }
- private void getLocation(String latitude, String longitude, String province) {
- LocationInfo locationInfo = new LocationInfo();
- locationInfo.setAddrStr("");
- locationInfo.setProvince(province);
- locationInfo.setCity("");
- locationInfo.setCityCode("");
- locationInfo.setDistrict("");
- locationInfo.setStreet("");
- locationInfo.setStreetNumber("");
- locationInfo.setLatitude(latitude);
- locationInfo.setLongitude(longitude);
- Map<String, LocationInfo> map = new HashMap<String, LocationInfo>();
- map.put("locationInfo", locationInfo);
- OkHttpUtils.post()
- .url(IUrlConstant.URL_UPLOAD_LOCATION)
- .addHeader("token", PlatformInfoXml.getToken())
- .addParams("platformInfo", PlatformInfoXml.getPlatformJsonString())
- .addParams("locationInfo", JSON.toJSONString(map))
- .build()
- .execute(new Callback<BaseModel>() {
- @Override
- public BaseModel parseNetworkResponse(Response response, int id) throws Exception {
- String resultJson = response.body().string();
- if (!TextUtils.isEmpty(resultJson)) {
- return JSON.parseObject(resultJson, BaseModel.class);
- }
- return null;
- }
- @Override
- public void onError(Call call, Exception e, int id) {
- }
- @Override
- public void onResponse(BaseModel response, int id) {
- if (response != null) {
- String isSucceed = response.getIsSucceed();
- if (!TextUtils.isEmpty(isSucceed) && "1".equals(isSucceed)) {// 上传成功
- LogUtil.i(LogUtil.TAG_ZL, "上传位置信息成功");
- // 发送事件,更新位置信息
- if (getProvince) {
- EventBus.getDefault().post(new UpdateUserProvince());
- EventBus.getDefault().post(new MatchInfoChangeEvent());
- }
- }
- }
- }
- });
- }
- @Override
- protected void doRegister() {
- super.doRegister();
- EventBus.getDefault().register(this);
- }
- @Override
- protected void unregister() {
- super.unregister();
- // 关闭MainActivity事件
- EventBus.getDefault().post(new CloseMainActivityEvent());
- EventBus.getDefault().unregister(this);
- }
- @Subscribe
- public void onEvent(NoSeeMeEvent event) {
- mViewPager.setCurrentItem(TAB_INDEX_FATE, false);
- }
- @Subscribe
- public void onEvent(OpenMailFragmentEvent event) {
- mViewPager.setCurrentItem(TAB_INDEX_MAIL, false);
- }
- @Subscribe
- public void onEvent(HeadMsgEvent event) {
- mViewPager.setCurrentItem(TAB_INDEX_MAIL, false);
- }
- @Subscribe
- public void onEvent(BaseOpenMailFragmentEvent event) {
- mViewPager.setCurrentItem(TAB_INDEX_MAIL, false);
- }
- @Subscribe
- public void onEvent(RegistEvent event) {
- finish();
- }
- @Subscribe
- public void onEvent(UpdateMessageCountEvent event) {
- int unreadMsgCount = event.getUnreadMsgCount();
- /**有未读消息进行刷新**/
- // if(unreadMsgCount>currentUnreadMsgCount){
- // MessageFragment item = (MessageFragment)mainAdapter.getItem(2);
- // item.startFirstRefish();
- // }
- /**改变气泡数量**/
- if (unreadMsgCount > 0) {
- mTvUnreadMsgCount.setVisibility(View.VISIBLE);
- mTvUnreadMsgCount.setText(String.valueOf(unreadMsgCount > 99 ? 99 : unreadMsgCount));
- currentUnreadMsgCount = unreadMsgCount;
- // 开始动画
- isStartAnim=true;
- setAnim();
- } else {
- mTvUnreadMsgCount.setVisibility(View.GONE);
- mTvUnreadMsgCount.clearAnimation();
- animationSet = null;
- }
- }
- private void setAnim() {
- animationSet = new AnimationSet(false);
- TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, 0, -10);
- translateAnimation.setDuration(100);
- TranslateAnimation translateAnimation2 = new TranslateAnimation(0, 0, -10, 0);
- translateAnimation2.setDuration(200);
- TranslateAnimation translateAnimation3 = new TranslateAnimation(0, 0, 0, 20);
- translateAnimation3.setDuration(250);
- if(animationSet != null){
- animationSet.setRepeatCount(20);
- animationSet.setRepeatMode(Animation.INFINITE);
- animationSet.addAnimation(translateAnimation);
- animationSet.addAnimation(translateAnimation2);
- animationSet.addAnimation(translateAnimation3);
- mTvUnreadMsgCount.startAnimation(animationSet);
- animationSet.setAnimationListener(new Animation.AnimationListener() {
- @Override
- public void onAnimationStart(Animation animation) {
- }
- @Override
- public void onAnimationEnd(Animation animation) {
- if (animationSet != null) {
- mTvUnreadMsgCount.startAnimation(animationSet);
- }
- }
- @Override
- public void onAnimationRepeat(Animation animation) {
- }
- });
- }
- }
- @Subscribe
- public void onEvent(CloseMainActivityEvent event) {
- mTimerHandler.removeMessages(MSG_TYPE_HEAD_MSG);
- mTimerHandler.removeMessages(MSG_TYPE_HEAD_MSG_NEW);
- mTimerHandler.removeMessages(MSG_TYPE_RECOMMEND_USER);
- mTimerHandler.removeMessages(MSG_TYPE_HIDE_RECOMMEND_USER);
- finish();
- }
- private class TimerHandler extends Handler {
- private WeakReference<MainActivity> mWeakReference;
- public TimerHandler(MainActivity mainActivity) {
- this.mWeakReference = new WeakReference<MainActivity>(mainActivity);
- }
- @Override
- public void handleMessage(Message msg) {
- if (null == this) { //走到了onDestory,则不再进行后续消息处理
- return;
- }
- if (MainActivity.this.isFinishing()) { //Activity正在停止,则不再后续处理
- return;
- }
- final MainActivity mainActivity = mWeakReference.get();
- switch (msg.what) {
- case MSG_TYPE_LOAD_DATA:// 加载数据
- if (mainActivity != null) {
- mainActivity.loadData();
- }
- break;
- // case MSG_TYPE_HEAD_MSG:// 页眉刷新
- // if (mainActivity != null) {
- // mainActivity.getHeadMsg();
- // }
- //// sendEmptyMessageDelayed(MSG_TYPE_HEAD_MSG, HEAD_MSG_REFRESH_PERIOD);
- // break;
- case MSG_TYPE_HEAD_MSG_NEW:// 新页眉刷新
- Log.v("Main===","新页眉刷新");
- if (mainActivity != null) {
- Log.v("Main===","新页眉刷新mainActivity");
- mainActivity.getNewHeadMsg();
- }
- break;
- case MSG_TYPE_RECOMMEND_USER:// 推荐用户刷新
- int cycle = 0;
- if (mainActivity != null) {
- mainActivity.getRecommendUsr();
- cycle = mainActivity.cycle;
- }
- // sendEmptyMessageDelayed(MSG_TYPE_RECOMMEND_USER, cycle < 20 ? HEAD_MSG_REFRESH_PERIOD : cycle * 1000);
- break;
- case MSG_TYPE_SHOW_UNREAD_MSG:// 显示未读消息页眉
- // 先隐藏上一条
- if (mainActivity != null) {
- mainActivity.dismissWithAnim(mainActivity.mFlHeadMsgNew, mainActivity.mRlHeadMsgUnread);
- mainActivity.mFlHeadMsgNew.postDelayed(new Runnable() {
- @Override
- public void run() {
- // 如果存在下一条,则显示
- if (mainActivity.mNewHeadMsgNotice != null && mainActivity.mCurrDisplayItem < mainActivity.mNewHeadMsgNotice.getUnreadMsgBoxList().size() - 1) {
- mainActivity.mCurrDisplayItem++;
- mainActivity.setNewHeadMsg();
- } else {
- // 继续轮询
- sendEmptyMessageDelayed(MSG_TYPE_HEAD_MSG_NEW, HEAD_MSG_REFRESH_PERIOD);
- }
- }
- }, 500);
- }
- break;
- case MSG_TYPE_HIDE_RECOMMEND_USER:// 隐藏推荐用户页眉
- // 隐藏上一条
- if (mainActivity != null) {
- mainActivity.dismissWithAnim(mainActivity.mLlRecommendUser, mainActivity.mLlRecommendUser);
- }
- sendEmptyMessageDelayed(MSG_TYPE_RECOMMEND_USER, HEAD_MSG_REFRESH_PERIOD);
- break;
- case MSG_TYPE_DISMISS_UNREAD_MSG:// 隐藏未读消息页眉
- if (mainActivity != null) {
- mainActivity.dismissWithAnim(mainActivity.mFlHeadMsgNew, mainActivity.mRlHeadMsgUnread);
- }
- break;
- case MSG_TYPE_DISMISS_VISITOR:// 隐藏访客页眉
- if (mainActivity != null) {
- mainActivity.dismissWithAnim(mainActivity.mFlHeadMsgNew, mainActivity.mRlHeadMsgVisitor);
- }
- sendEmptyMessageDelayed(MSG_TYPE_HEAD_MSG_NEW, HEAD_MSG_REFRESH_PERIOD);
- break;
- }
- }
- }
- private static class MainAdapter extends FragmentPagerAdapter {
- private List<Fragment> fragments = new ArrayList<>();
- public MainAdapter(FragmentManager fm) {
- super(fm);
- fragments.add(new FateCardFragment());
- fragments.add(new SearchFragment());
- fragments.add(new MessageFragment());
- fragments.add(new MeFragment());
- // fragments.add(new RecentVistorsActivity());
- }
- @Override
- public Fragment getItem(int position) {
- return fragments.get(position);
- }
- @Override
- public int getCount() {
- return fragments.size();
- }
- }
- @Override
- protected void onStart() {
- super.onStart();
- isShake = true;
- System.out.println("111111111111111111111111" + "MainonStart");
- }
- @Override
- public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
- super.onCreate(savedInstanceState, persistentState);
- System.out.println("111111111111111111111111" + "Mainoncreat");
- }
- @Override
- protected void onPause() {
- super.onPause();
- isShake = false;
- isPause=true;
- // stopRecommend=false;
- // stopMsg=false;
- // //通知UserInfoDetailActivity继续轮询页眉
- // Message msg = new Message();
- // msg.what = 3333;
- // msg.obj =mCurrDisplayItem;
- // EventBus.getDefault().post(msg);
- }
- @Override
- protected void onRestart() {
- super.onRestart();
- }
- @Override
- protected void onResume() {
- super.onResume();
- isPause=false;
- isShake = true;
- Log.v("Main===","onRestart");
- }
- @Override
- protected void onStop() {
- super.onStop();
- // isShake=false;
- System.out.println("111111111111111111111111" + "MainonStopt");
- }
- @Override
- protected void onDestroy() {
- super.onDestroy();
- // 删除广播注册
- if (mReceiverTag) { //判断广播是否注册
- mReceiverTag = false; //Tag值 赋值为false 表示该广播已被注销
- this.unregisterReceiver(mHomeKeyEventReceiver); //注销广播
- }
- if (unbinder != null) {
- unbinder.unbind();
- }
- }
- /**
- * 监听是否点击了home键将客户端推到后台
- */
- private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {
- String SYSTEM_REASON = "reason";
- String SYSTEM_HOME_KEY = "homekey";
- String SYSTEM_HOME_KEY_LONG = "recentapps";
- @Override
- public void onReceive(Context context, Intent intent) {
- String action = intent.getAction();
- if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
- String reason = intent.getStringExtra(SYSTEM_REASON);
- if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
- //表示按了home键,程序到了后台
- isShake = false;
- // mTimerHandler.removeMessages(MSG_TYPE_HEAD_MSG);
- // mTimerHandler.removeMessages(MSG_TYPE_HEAD_MSG_NEW);
- // mTimerHandler.removeMessages(MSG_TYPE_RECOMMEND_USER);
- // mTimerHandler.removeMessages(MSG_TYPE_HIDE_RECOMMEND_USER);
- // mTimerHandler.removeMessages(MSG_TYPE_SHOW_UNREAD_MSG);
- // mTimerHandler.removeMessages(MSG_TYPE_DISMISS_UNREAD_MSG);
- // mTimerHandler.removeMessages(MSG_TYPE_DISMISS_VISITOR);
- } else if (TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)) {
- //表示长按home键,显示最近使用的程序列表
- }
- }
- }
- };
- // 获取城市
- private void getAddress(String getLatitude, String getLongitude, final String language, final String country) {
- // 本地
- String url = "http://ditu.google.cn/maps/api/geocode/json?latlng="+ getLatitude + "," + getLongitude + "&&sensor=false&&language=";
- // 线上
- // String url = "http://ditu.google.com/maps/api/geocode/json?latlng="+ lat + "," + lng + "&&sensor=false&&language=";
- //获取国际化参数
- String localInfo = "en_US";
- url += localInfo; //拼接url地址
- String charset = "UTF-8";
- OkHttpUtils.get()
- .url(url)
- .build()
- .execute(new StringCallback() {
- @Override
- public void onError(Call call, Exception e, int id) {
- Log.v("Exception",e.toString());
- }
- @Override
- public void onResponse(String response, int id) {
- if (null != response) {
- JSONObject json = JSON.parseObject(response);// 转换为json数据
- JSONArray jsonArray = json.getJSONArray("results");
- Map<String, String> map = null;
- if (null != jsonArray && jsonArray.size() > 0) {// 增加验证
- JSONObject objResult = (JSONObject) jsonArray.get(0);
- JSONArray addressComponents = objResult.getJSONArray("address_components");
- //解析结果
- getByGoogleMap(addressComponents, objResult, language, country);
- }
- }
- }
- });
- }
- private void getByGoogleMap(JSONArray addressComponents, JSONObject objResult, String language, String country) {
- String countryResult="";
- String province="";
- String city="";
- if(addressComponents!=null&&addressComponents.size()>0){
- for(int i=0;i<addressComponents.size();i++){
- JSONObject obj = (JSONObject) addressComponents
- .get(i);
- JSONArray types = obj.getJSONArray("types");
- String type = (String)types.get(0);
- //获取目标解析单位的key
- String proviceKey = getGoogleProviceL1Key(country);
- if(type.equals(proviceKey)){
- province = obj.getString("long_name");// 州
- }else if(type.equals("administrative_area_level_2")){
- city = obj.getString("long_name");// 城市
- }else if (type.equals("country")){ //国家
- countryResult = obj.getString("long_name");
- }
- }
- // if(StringUtils.isBlank(province)){ //不是一级城市 取二级城市
- if(TextUtils.isEmpty(province)){ //不是一级城市 取二级城市
- province = city;
- }
- }
- String formatted_address = objResult.getString("formatted_address");
- Map<String, String> map = new HashMap<String, String>();
- map.put("city", city);
- map.put("formatted_address", formatted_address);
- map.put("province", province);
- map.put("country", countryResult);
- if(againGetLocation){
- againGetCity(map);
- }else{
- getCity(map);
- }
- }
- private void againGetCity(Map<String, String> googleAddress) {
- if (googleAddress != null) {
- String province = googleAddress.get("province");
- // 英国城市为空。。。
- if (!TextUtils.isEmpty(province) && !province.equals(UserInfoXml.getProvinceName())) {
- UserInfoXml.setProvinceName(province);
- getProvince = true;
- }
- getLocation(getLatitude, getLongitude, province);
- }
- }
- private void getCity(Map<String, String> map) {
- if (map != null) {
- String province1 = map.get("province");
- if (!TextUtils.isEmpty(province1)) {
- if (!province1.equals(UserInfoXml.getProvinceName())) {
- UserInfoXml.setProvinceName(province1);
- getProvince = true;
- }
- getLocation(getLatitude, getLongitude, province1);
- } else {
- mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
- if (ContextCompat.checkSelfPermission(MainActivity.this,
- Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED) {
- // 请求android.permission.ACCESS_FINE_LOCATION
- ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_CODE_ACCESS_FINE_LOCATION);
- } else {
- if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {// Network定位
- mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 5, mLocationListener);
- } else if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {// GPS定位
- uploadLocation(mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
- }
- }
- }
- } else {
- mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
- if (ContextCompat.checkSelfPermission(MainActivity.this,
- Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED) {
- // 请求android.permission.ACCESS_FINE_LOCATION
- ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_CODE_ACCESS_FINE_LOCATION);
- } else {
- if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {// Network定位
- mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 5, mLocationListener);
- } else if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {// GPS定位
- uploadLocation(mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
- }
- }
- }
- }
- //记录用户首次点击返回键的时间
- private long firstTime=0;
- @Override
- public boolean onKeyUp(int keyCode, KeyEvent event) {
- switch (keyCode){
- case KeyEvent.KEYCODE_BACK:
- long secondTime=System.currentTimeMillis();
- if(secondTime-firstTime>2000){
- // ToastUtil.showShortToast(MainActivity.this,getString(R.string.press_quit));
- Toast.makeText(MainActivity.this,getString(R.string.press_quit),Toast.LENGTH_SHORT);
- firstTime=secondTime;
- return true;
- }else{
- // System.exit(0);
- moveTaskToBack(false);
- return true;
- }
- // break;
- }
- return super.onKeyUp(keyCode, event);
- }
- // 点击返回退出却不销毁
- // @Override
- // public boolean onKeyDown(int keyCode, KeyEvent event) {
- // Log.v("keyCode==", String.valueOf(keyCode));
- // if (keyCode == KeyEvent.KEYCODE_BACK) {
- // new AlertDialog.Builder(this).setTitle(getString(R.string.sure_exit))
- //// .setIcon(android.R.drawable.ic_dialog_info)
- // .setPositiveButton(getString(R.string.sure), new DialogInterface.OnClickListener() {
- //
- // @Override
- // public void onClick(DialogInterface dialog, int which) {
- // // 点击“确认”后的操作
- //// MainActivity.this.finish();
- // moveTaskToBack(false);
- // }
- // })
- // .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
- //
- // @Override
- // public void onClick(DialogInterface dialog, int which) {
- // // 点击“返回”后的操作,这里不设置没有任何操作
- // }
- // }).show();
- // return true;
- //
- // }
- // return super.onKeyDown(keyCode, event);
- // }
- // @Override
- // public void onBackPressed() {
- // new AlertDialog.Builder(this).setTitle("确认退出吗?")
- // .setIcon(android.R.drawable.ic_dialog_info)
- // .setPositiveButton("确定", new DialogInterface.OnClickListener() {
- //
- // @Override
- // public void onClick(DialogInterface dialog, int which) {
- // // 点击“确认”后的操作
- // MainActivity.this.finish();
- //
- // }
- // })
- // .setNegativeButton("返回", new DialogInterface.OnClickListener() {
- //
- // @Override
- // public void onClick(DialogInterface dialog, int which) {
- // // 点击“返回”后的操作,这里不设置没有任何操作
- // }
- // }).show();
- // }
- }