/dateLoveInternational/src/main/java/com/datelove/online/International/activity/SplashActivity.java
Java | 764 lines | 593 code | 74 blank | 97 comment | 150 complexity | ee6e7e381118b7b78620c4ca45280d93 MD5 | raw file
- package com.datelove.online.International.activity;
- import android.Manifest;
- import android.app.ProgressDialog;
- import android.content.Context;
- import android.content.Intent;
- import android.content.pm.PackageManager;
- import android.location.Location;
- import android.location.LocationListener;
- import android.location.LocationManager;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- import android.net.Uri;
- import android.os.Build;
- import android.os.Bundle;
- import android.os.Handler;
- import android.provider.Settings;
- import android.support.annotation.NonNull;
- import android.support.v4.app.ActivityCompat;
- import android.support.v4.content.ContextCompat;
- import android.text.TextUtils;
- import android.util.Log;
- import android.view.View;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONArray;
- import com.alibaba.fastjson.JSONObject;
- import com.appsflyer.AppsFlyerLib;
- import com.baidu.android.pushservice.PushConstants;
- import com.baidu.android.pushservice.PushManager;
- import com.crashlytics.android.Crashlytics;
- import com.datelove.online.International.R;
- import com.datelove.online.International.base.BaseFragmentActivity;
- import com.datelove.online.International.bean.CheckRefresh;
- import com.datelove.online.International.bean.LocationInfo;
- import com.datelove.online.International.bean.LoginEntity;
- import com.datelove.online.International.bean.PlatformInfo;
- import com.datelove.online.International.constant.IConfigConstant;
- import com.datelove.online.International.constant.IUrlConstant;
- import com.datelove.online.International.utils.AppsflyerUtils;
- import com.datelove.online.International.utils.Cheeses;
- import com.datelove.online.International.utils.CommonRequestUtil;
- import com.datelove.online.International.utils.CountryFidUtils;
- import com.datelove.online.International.xml.PlatformInfoXml;
- import com.datelove.online.International.xml.UserInfoXml;
- import com.library.dialog.OnDoubleDialogClickListener;
- import com.library.dialog.OnSingleDialogClickListener;
- import com.library.utils.DensityUtil;
- import com.library.utils.DialogUtil;
- import com.library.utils.SharedPreferenceUtil;
- import com.library.utils.TimeUtil;
- import com.library.utils.ToastUtil;
- import com.library.utils.Util;
- import com.library.utils.VersionInfoUtil;
- import com.zhy.http.okhttp.OkHttpUtils;
- import com.zhy.http.okhttp.callback.Callback;
- import com.zhy.http.okhttp.callback.FileCallBack;
- import com.zhy.http.okhttp.callback.StringCallback;
- import java.io.File;
- import java.net.Inet4Address;
- import java.net.InetAddress;
- import java.net.NetworkInterface;
- import java.util.Enumeration;
- import java.util.HashMap;
- import java.util.Map;
- import io.fabric.sdk.android.Fabric;
- import okhttp3.Call;
- import okhttp3.Response;
- /**
- * Created by Administrator on 2016/10/18.
- */
- public class SplashActivity extends BaseFragmentActivity {
- private String UPDATE_SERVERAPK = "Flirt&Hookup";
- private LocationManager mLocationManager;
- private static final int PERMISSION_CODE_ACCESS_FINE_LOCATION = 0;
- // 埋点:获取用户对定位权限的态度:1定位成功,2定位失败,3关闭定位
- private static final String POSITION_SUCCESS = "1";
- private static final String POSITION_FAIL = "2";
- private static final String CLOSE_POSITION = "3";
- private String getCountry;
- private boolean isFinish=false;
- private boolean removeLocation=false;
- private boolean isfirstGetLoaction=true;
- @Override
- protected int getLayoutResId() {
- return R.layout.activity_splash;
- }
- @Override
- protected void initViewsAndVariables() {
- // bug统计工具
- Fabric.with(this, new Crashlytics());
- // 百度推送service初始化及绑定
- PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY, IConfigConstant.BAIDU_PUSH_API_KEY);
- // AppsFlyer初始化
- AppsFlyerLib.getInstance().setAndroidIdData(getAndroidId());
- AppsFlyerLib.getInstance().startTracking(this.getApplication(), IConfigConstant.APPSFLYER_DEV_KEY);
- // 获得platform信息
- getPlatformInfo();
- // 获取位置信息并上传
- requestLocation();
- }
- @Override
- protected void addListeners() {
- }
- /**
- * 检查GPS定位开关
- *
- * @return
- */
- private boolean checkGPS() {
- if (mLocationManager != null) {
- return (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)||mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
- }
- return false;
- }
- public void checkRefresh() {
- OkHttpUtils.post()
- .url(IUrlConstant.URL_CHECK_UPDATE)
- .addHeader("token", PlatformInfoXml.getToken())
- .addParams("platformInfo", PlatformInfoXml.getPlatformJsonString())
- .build()
- .execute(new RefreshCallBack());
- }
- private ProgressDialog pd;
- private class RefreshCallBack extends Callback<CheckRefresh> {
- @Override
- public CheckRefresh parseNetworkResponse(Response response, int id) throws Exception {
- String resultJson = response.body().string();
- if (!TextUtils.isEmpty(resultJson)) {
- return JSON.parseObject(resultJson, CheckRefresh.class);
- }
- return null;
- }
- @Override
- public void onError(Call call, Exception e, int id) {
- login();
- }
- @Override
- public void onResponse(CheckRefresh response, int id) {
- if (response != null) {
- if (response.isUpdate == null || response.isUpdate.equals("0")) {
- login();
- } else {
- DialogUtil.showSingleBtnDialog(getSupportFragmentManager(), "Update", response.updateInfo,
- getString(R.string.positive), false, new OnSingleDialogClickListener() {
- @Override
- public void onPositiveClick(View view) {
- pd = new ProgressDialog(SplashActivity.this);
- pd.setTitle("Downloading");
- pd.setCanceledOnTouchOutside(false);
- pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
- downFile("http://iospan.ilove.ren:8092/apk/" + getString(R.string.app_name) + ".apk");
- }
- });
- }
- }
- }
- }
- /**
- * 下载apk
- */
- public void downFile(final String url) {
- pd.show();
- OkHttpUtils.get()
- .url(url)
- .build()
- .execute(new FileCallBack(getExternalFilesDir(null).getPath() + File.separator, UPDATE_SERVERAPK) {
- @Override
- public void inProgress(float progress, long total, int id) {
- super.inProgress(progress, total, id);
- pd.setProgress((int) (progress * 100));
- }
- @Override
- public void onError(Call call, Exception e, int id) {
- pd.cancel();
- }
- @Override
- public void onResponse(File response, int id) {
- pd.cancel();
- update();
- }
- });
- }
- /**
- * 安装应用
- */
- public void update() {
- Intent intent = new Intent(Intent.ACTION_VIEW);
- intent.setDataAndType(Uri.fromFile(new File(getExternalFilesDir(null).getPath() + File.separator, UPDATE_SERVERAPK)),
- "application/vnd.android.package-archive");
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- startActivity(intent);
- }
- private void login() {
- OkHttpUtils.post()
- .url(IUrlConstant.URL_LOGIN)
- .addHeader("token", PlatformInfoXml.getToken())
- .addParams("platformInfo", PlatformInfoXml.getPlatformJsonString())
- .addParams("pushToken", PlatformInfoXml.getPushToken())
- .addParams("account", UserInfoXml.getUsername())
- .addParams("password", UserInfoXml.getPassword())
- .build()
- .execute(new LoginCallBack());
- }
- private class LoginCallBack extends Callback<LoginEntity> {
- @Override
- public LoginEntity parseNetworkResponse(Response response, int id) throws Exception {
- String resultJson = response.body().string();
- if (!TextUtils.isEmpty(resultJson)) {
- return JSON.parseObject(resultJson, LoginEntity.class);
- }
- return null;
- }
- @Override
- public void onError(Call call, Exception e, int id) {
- if(!isFinish){
- isFinish=true;
- Util.gotoActivity(SplashActivity.this, LoginActivity.class, true);
- finish();
- }
- }
- @Override
- public void onResponse(final LoginEntity response, int id) {
- if(!isFinish){
- isFinish=true;
- if (response != null) {
- if (!TextUtils.isEmpty(response.getMsg())) {
- ToastUtil.showShortToast(SplashActivity.this, response.getMsg());
- }
- String isSucceed = response.getIsSucceed();
- if (!TextUtils.isEmpty(isSucceed) && "1".equals(isSucceed)) {
- PlatformInfoXml.setToken(response.getToken());
- UserInfoXml.setUserInfo(response.getUserEnglish());
- // 设置页眉和互推开关
- UserInfoXml.setIsShowHeadMsg(response.getIsShowHeadNotice());
- UserInfoXml.setIsShowHeadMsgNew(response.getIsShowHeadNotice2());
- UserInfoXml.setIsShowRecommendUser(response.getIsShowCommendUser());
- UserInfoXml.setSearchInterceptor(response.getSearchInterceptor());
- // appsflyer登录
- AppsflyerUtils.login();
- CommonRequestUtil.initParamsDict(new CommonRequestUtil.OnCommonListener() {
- @Override
- public void onSuccess() {
- if (response.getIsShowUploadImg() != null && response.getIsShowUploadImg().equals("1")) {
- Util.gotoActivity(SplashActivity.this, UploadPhotoActivity.class, true);
- } else {
- if(UserInfoXml.getGender().equals("1") && response.getIsShowUploadAudioInformation() != null && response.getIsShowUploadAudioInformation().equals("1")){
- // Util.gotoActivity(SplashActivity.this,UploadAudioActivity.class,true);
- Intent intent = new Intent(SplashActivity.this, UploadAudioActivity.class);
- startActivity(intent);
- finish();
- overridePendingTransition(R.anim.login_anim_in, R.anim.login_anim_out);
- }else {
- Util.gotoActivity(SplashActivity.this, MainActivity.class, true);
- }
- }
- }
- @Override
- public void onFail() {
- if (response.getIsShowUploadImg() != null && response.getIsShowUploadImg().equals("1")) {
- Util.gotoActivity(SplashActivity.this, UploadPhotoActivity.class, true);
- } else {
- Util.gotoActivity(SplashActivity.this, MainActivity.class, true);
- }
- }
- });
- } else {
- Util.gotoActivity(SplashActivity.this, LoginActivity.class, true);
- }
- } else {
- Util.gotoActivity(SplashActivity.this, LoginActivity.class, true);
- }
- }
- }
- }
- private void getPlatformInfo() {
- PlatformInfo platformInfo = new PlatformInfo();
- platformInfo.setW(String.valueOf(DensityUtil.getScreenWidth(SplashActivity.this)));
- platformInfo.setH(String.valueOf(DensityUtil.getScreenHeight(SplashActivity.this)));
- platformInfo.setVersion(String.valueOf(VersionInfoUtil.getVersionCode(getApplicationContext())));
- platformInfo.setPhonetype(Build.MODEL);
- platformInfo.setPid(getAndroidId());
- platformInfo.setImsi(getAndroidId());
- platformInfo.setProduct(IConfigConstant.PRODUCT_ID);// 产品号
- platformInfo.setNetType(getNetType());
- platformInfo.setMobileIP(getMobileIP());
- platformInfo.setRelease(TimeUtil.getCurrentTime());
- platformInfo.setPlatform("2");
- platformInfo.setSystemVersion(Build.VERSION.RELEASE);
- if (TextUtils.isEmpty(PlatformInfoXml.getCountry())) {
- platformInfo.setCountry("America");
- platformInfo.setLanguage("English");
- }else{
- platformInfo.setLanguage(CountryFidUtils.getLanguageMap().get(PlatformInfoXml.getCountry()));
- }
- if (TextUtils.isEmpty(PlatformInfoXml.getFid())) {
- platformInfo.setFid(IConfigConstant.F_ID);
- }
- // 保存platform信息
- PlatformInfoXml.setPlatfromInfo(platformInfo);
- }
- private String getAndroidId() {
- return Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
- }
- private String getNetType() {
- String type = "";
- ConnectivityManager cm = (ConnectivityManager) SplashActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo info = cm.getActiveNetworkInfo();
- if (info == null) {
- type = "0";
- } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
- type = "2";
- } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
- String extraInfo = info.getExtraInfo();
- if (extraInfo.equals("cmwap")) {
- type = "3";
- } else if (extraInfo.equals("cmnet")) {
- type = "4";
- } else if (extraInfo.equals("ctnet")) {
- type = "5";
- } else if (extraInfo.equals("ctwap")) {
- type = "6";
- } else if (extraInfo.equals("3gwap")) {
- type = "7";
- } else if (extraInfo.equals("3gnet")) {
- type = "8";
- } else if (extraInfo.equals("uniwap")) {
- type = "9";
- } else if (extraInfo.equals("uninet")) {
- type = "10";
- }
- }
- return type;
- }
- private String getMobileIP() {
- try {
- for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
- NetworkInterface intf = en.nextElement();
- for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
- InetAddress inetAddress = enumIpAddr.nextElement();
- if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
- return inetAddress.getHostAddress().toString();
- }
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return "";
- }
- /**
- * 请求定位信息
- */
- private void requestLocation() {
- mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
- if (checkGPS()) {// GPS打开
- if (ContextCompat.checkSelfPermission(SplashActivity.this,
- Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED) {
- // 请求android.permission.ACCESS_FINE_LOCATION
- ActivityCompat.requestPermissions(SplashActivity.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));
- }
- /**添加代码**/
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- if (UserInfoXml.getUsername() != null && UserInfoXml.getPassword() != null) {
- checkRefresh();
- } else if (getCountry != null) {
- if (getCountry.contains(" ")) {
- getCountry = getCountry.replaceAll(" ", "");
- }
- boolean getLocation=false;
- for(int i=0;i<Cheeses.EN_GOUNTRY.length;i++){
- if(Cheeses.EN_GOUNTRY[i].equals(getCountry)){
- getLocation=true;
- skipRegisterActivity(POSITION_SUCCESS);
- }
- }
- if(!getLocation){
- skipRegisterActivity(POSITION_FAIL);
- }
- } else {
- skipRegisterActivity(POSITION_FAIL);
- }
- }
- }, 3000);
- /**添加代码**/
- // 。。。。。
- }
- } else {// GPS关闭
- // 跳转到设置页,打开定位开关
- DialogUtil.showDoubleBtnDialog(getSupportFragmentManager(), null, getString(R.string.near_fail), getString(R.string.dialog_set), null, true, new OnDoubleDialogClickListener() {
- @Override
- public void onPositiveClick(View view) {
- Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
- startActivityForResult(intent, 0);
- // requestLocation();
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- requestLocation();
- }
- }, 3000);
- }
- @Override
- public void onNegativeClick(View view) {
- /**添加代码**/
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- if (UserInfoXml.getUsername() != null && UserInfoXml.getPassword() != null) {
- checkRefresh();
- } else {
- // Util.gotoActivity(SplashActivity.this, RegisterActivity.class, true);
- skipRegisterActivity(CLOSE_POSITION);
- // Intent intent = new Intent(SplashActivity.this, RegisterActivity.class);
- // Bundle bundle = new Bundle();
- // bundle.putString("locationCode", "3");
- // intent.putExtras(bundle);
- // finish();
- // startActivity(intent);
- }
- }
- }, 3000);
- /**添加代码**/
- }
- });
- }
- }
- private LocationListener mLocationListener = new LocationListener() {
- @Override
- public void onLocationChanged(Location location) {
- if(!removeLocation){
- 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定位
- mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 5, mLocationListener);
- uploadLocation(mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
- } else if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {// GPS定位
- 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;
- }
- uploadLocation(mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
- }
- /**添加代码**/
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- if (UserInfoXml.getUsername() != null && UserInfoXml.getPassword() != null) {
- checkRefresh();
- } else if (getCountry != null) {
- if (getCountry.contains(" ")) {
- getCountry = getCountry.replaceAll(" ", "");
- }
- boolean getLocation=false;
- for(int i=0;i<Cheeses.EN_GOUNTRY.length;i++){
- if(Cheeses.EN_GOUNTRY[i].equals(getCountry)){
- getLocation=true;
- skipRegisterActivity(POSITION_SUCCESS);
- }
- }
- if(!getLocation){
- skipRegisterActivity(POSITION_FAIL);
- }
- // Intent intent = new Intent(SplashActivity.this, RegisterActivity.class);
- // Bundle bundle = new Bundle();
- // bundle.putString("getCountry", getCountry);
- // bundle.putString("locationCode", "1");
- // intent.putExtras(bundle);
- // finish();
- // startActivity(intent);
- // Util.gotoActivity(SplashActivity.this, RegisterActivity.class,true,"getCountry",getCountry);
- } else {
- skipRegisterActivity(POSITION_FAIL);
- // Util.gotoActivity(SplashActivity.this, RegisterActivity.class, true);
- // Intent intent = new Intent(SplashActivity.this, RegisterActivity.class);
- // Bundle bundle = new Bundle();
- // bundle.putString("locationCode", "2");
- // intent.putExtras(bundle);
- // finish();
- // startActivity(intent);
- }
- }
- }, 5000);
- /**添加代码**/
- } else {
- /**添加代码**/
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- if (UserInfoXml.getUsername() != null && UserInfoXml.getPassword() != null) {
- checkRefresh();
- } else {
- // Util.gotoActivity(SplashActivity.this, RegisterActivity.class, true);
- skipRegisterActivity(CLOSE_POSITION);
- // Intent intent = new Intent(SplashActivity.this, RegisterActivity.class);
- // Bundle bundle = new Bundle();
- // bundle.putString("locationCode", "3");
- // intent.putExtras(bundle);
- // finish();
- // startActivity(intent);
- }
- }
- }, 3000);
- /**添加代码**/
- }
- }
- }
- /**跳转到注册界面**/
- private void skipRegisterActivity(String locationCode) {
- if (!isFinish) {
- isFinish=true;
- Intent intent = new Intent(SplashActivity.this, RegisterActivity.class);
- Bundle bundle = new Bundle();
- if (!TextUtils.isEmpty(getCountry)) {
- bundle.putString("getCountry", getCountry);
- }
- if (!TextUtils.isEmpty(locationCode)) {
- bundle.putString("locationCode", locationCode);
- }
- intent.putExtras(bundle);
- finish();
- startActivity(intent);
- overridePendingTransition(R.anim.login_anim_in, R.anim.login_anim_out);
- }
- }
- /**
- * 上传位置信息
- *
- * @param location 定位成功后的信息
- */
- private void uploadLocation(Location location) {
- if (location != null) {
- LocationInfo locationInfo = new LocationInfo();
- locationInfo.setAddrStr("");
- locationInfo.setProvince("");
- locationInfo.setCity("");
- locationInfo.setCityCode("");
- locationInfo.setDistrict("");
- locationInfo.setStreet("");
- locationInfo.setStreetNumber("");
- //英国
- // String getLatitude ="52.2729944";
- // String getLongitude ="-0.8755515";
- // 印度
- // String getLatitude ="28.61345942";
- // String getLongitude ="77.20092773";
- String getLatitude = String.valueOf(location.getLatitude());
- String getLongitude = String.valueOf(location.getLongitude());
- locationInfo.setLatitude(getLatitude);
- locationInfo.setLongitude(getLongitude);
- SharedPreferenceUtil.setStringValue(SplashActivity.this,"LOCATION","getLatitude",getLatitude);
- SharedPreferenceUtil.setStringValue(SplashActivity.this,"LOCATION","getLongitude",getLongitude);
- Map<String, LocationInfo> map = new HashMap<String, LocationInfo>();
- map.put("locationInfo", locationInfo);
- // 根据经纬度获取国家和地区
- if(isfirstGetLoaction){
- isfirstGetLoaction=false;
- getAddress(getLatitude, getLongitude,"English");
- }
- }
- }
- // 获取城市
- private void getAddress(String getLatitude, String getLongitude, final String language) {
- // 本地
- 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);
- }
- }
- }
- });
- }
- private void getByGoogleMap(JSONArray addressComponents, JSONObject objResult, String language) {
- 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 ="administrative_area_level_1";
- if (type.equals("country")){ //国家
- countryResult = obj.getString("long_name");
- }
- //获取目标解析单位的key
- proviceKey = getGoogleProviceL1Key(countryResult);
- 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");
- if (!TextUtils.isEmpty(province) && !province.equals(UserInfoXml.getProvinceName())) {
- UserInfoXml.setProvinceName(province);
- }
- SharedPreferenceUtil.setStringValue(SplashActivity.this,"GET_PROVINCE","province",province);
- if(!TextUtils.isEmpty(countryResult)){
- getCountry = countryResult;
- if (UserInfoXml.getUsername() != null && UserInfoXml.getPassword() != null) {
- checkRefresh();
- } else if (getCountry != null) {
- if (getCountry.contains(" ")) {
- getCountry = getCountry.replaceAll(" ", "");
- }
- boolean getLocation=false;
- for(int i=0;i<Cheeses.EN_GOUNTRY.length;i++){
- if(Cheeses.EN_GOUNTRY[i].equals(getCountry)){
- getLocation=true;
- skipRegisterActivity(POSITION_SUCCESS);
- }
- }
- if(!getLocation){
- skipRegisterActivity(POSITION_FAIL);
- }
- }
- }
- }
- public static String getGoogleProviceL1Key(String country) {
- String proviceL1Key = "administrative_area_level_1";
- if("UnitedKingdom".equals(country) || "United Kingdom".equals(country)){
- proviceL1Key = "administrative_area_level_2";
- }
- return proviceL1Key;
- }
- @Override
- protected void onDestroy() {
- super.onDestroy();
- removeLocation=true;
- }
- }