From 92a672b964133e25600bbcfbbda8f2c9778d3e1d Mon Sep 17 00:00:00 2001 From: mwang <8205347@qq.com> Date: Mon, 13 May 2019 00:18:07 +0800 Subject: [PATCH] =?UTF-8?q?intercepter=20change=20source=20=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- zhuike/build.gradle | 39 +++---- zhuike/src/main/AndroidManifest.xml | 4 +- .../com/novelbook/android/Activity_base.java | 2 + .../android/Fragments/BasicFragment.java | 1 + .../android/Fragments/CatalogFragment.java | 3 +- .../android/Fragments/Fragment_paihang.java | 2 +- .../com/novelbook/android/Main2Activity.java | 16 ++- .../com/novelbook/android/netapi/HttpApi.java | 4 +- .../novelbook/android/netapi/RandomHost.java | 8 +- .../android/netsubscribe/BookSubscribe.java | 4 +- .../android/netutils/HttpMethods.java | 36 ++++-- .../android/netutils/RetryInterceptor.java | 108 ++++++++++++------ .../android/upgrade/ParseXmlService.java | 44 +++++++ .../android/upgrade/UpdateManager.java | 58 +++++++++- .../novelbook/android/utils/CommonUtil.java | 14 ++- .../com/novelbook/android/utils/Config.java | 4 +- .../src/main/res/layout/nav_header_main2.xml | 1 + zhuike/zhuike.iml | 82 ++++--------- 18 files changed, 279 insertions(+), 151 deletions(-) diff --git a/zhuike/build.gradle b/zhuike/build.gradle index c105d9e..5af8425 100644 --- a/zhuike/build.gradle +++ b/zhuike/build.gradle @@ -12,7 +12,10 @@ android { versionName "1.0" // testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + // vectorDrawables.useSupportLibrary = true + + vectorDrawables.useSupportLibrary = true renderscriptTargetApi 24 //blurkit @@ -20,7 +23,7 @@ android { multiDexEnabled true //突破65535 manifestPlaceholders = [UMENG_CHANNEL_CALUE:"umeng"] //默认为uMeng - flavorDimensions "default" + // flavorDimensions "default" //debug时注销 } buildTypes { @@ -46,41 +49,34 @@ android { proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' - applicationVariants.all{ variant -> + /* applicationVariants.all{ variant -> variant.outputs.all{ output -> def outFile = output.outputFile if (outFile != null && outFile.name.endsWith(".apk")){ - def fileName = "${variant.productFlavors[0].name}" + ".apk" + def fileName = "${variant.productFlavors[0].name}" + "${releaseTime()}" + ".apk" outputFileName = fileName; // output.outputFile = new File(outFile.parent, fileName); } } - } + }*/ } } //渠道 - productFlavors { + /* productFlavors { // googleplay {} huawei { applicationId "com.novelbook.android.huawei" versionName "version-a-1.0"} xiaomi { applicationId "com.novelbook.android.xiaomi" versionName "version-a-1.0"} - /* wandoujia {} - baidu {} - yingyongbao {} - android360 {} - uc {} - umeng {} - meizu{} - */ + //批量配置 productFlavors.all { flavor -> flavor.manifestPlaceholders = [UMENG_CHANNEL_VALUE: name] } } - +*/ android { lintOptions { @@ -99,14 +95,11 @@ android { } + +} +def releaseTime() { + return new Date().format("yyyy-MM-dd", TimeZone.getTimeZone("UTC")) } - - - - - - - dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'com.android.support:appcompat-v7:28.0.0' @@ -148,6 +141,6 @@ dependencies { // implementation 'com.github.tangguna:SearchBox:1.0.1' implementation 'com.github.chengzipi:Searchbox:v1.0.0' implementation 'com.github.ixiaow:multilayout:1.0.0' - implementation 'com.umeng.umsdk:analytics:8.0.2' - implementation 'com.umeng.umsdk:common:2.0.2' + implementation 'com.umeng.umsdk:analytics:8.0.2' + implementation 'com.umeng.umsdk:common:2.0.2' } diff --git a/zhuike/src/main/AndroidManifest.xml b/zhuike/src/main/AndroidManifest.xml index bfd507e..05e373c 100644 --- a/zhuike/src/main/AndroidManifest.xml +++ b/zhuike/src/main/AndroidManifest.xml @@ -20,7 +20,7 @@ android:supportsRtl="true" android:theme="@style/ToolBarTheme" android:usesCleartextTraffic="true"> - + - + diff --git a/zhuike/src/main/java/com/novelbook/android/Activity_base.java b/zhuike/src/main/java/com/novelbook/android/Activity_base.java index eeeedde..375b86d 100644 --- a/zhuike/src/main/java/com/novelbook/android/Activity_base.java +++ b/zhuike/src/main/java/com/novelbook/android/Activity_base.java @@ -24,6 +24,7 @@ import android.widget.Toast; import com.google.gson.Gson; import com.novelbook.android.db.Novel; import com.novelbook.android.netsubscribe.MovieSubscribe; +import com.novelbook.android.netutils.NetUtil; import com.novelbook.android.netutils.OnSuccessAndFaultListener; import com.novelbook.android.netutils.OnSuccessAndFaultSub; import com.novelbook.android.upgrade.UpdateManager; @@ -213,6 +214,7 @@ public abstract class Activity_base extends AppCompatActivity { mProgressDialog.setCanceledOnTouchOutside(false); mProgressDialog.setMessage(message); } + if(NetUtil.isNetworkConnected()) mProgressDialog.show(); } diff --git a/zhuike/src/main/java/com/novelbook/android/Fragments/BasicFragment.java b/zhuike/src/main/java/com/novelbook/android/Fragments/BasicFragment.java index f9c3d5a..a0ccf3c 100644 --- a/zhuike/src/main/java/com/novelbook/android/Fragments/BasicFragment.java +++ b/zhuike/src/main/java/com/novelbook/android/Fragments/BasicFragment.java @@ -256,6 +256,7 @@ public abstract class BasicFragment extends Fragment { if(getActivity()==null){ return; } + if(NetUtil.isNetworkConnected()) if(mSwipeRefresh ==null || !mSwipeRefresh.isRefreshing()) { ((Activity_base) getActivity()).showProgressDialog(flag,msg); } diff --git a/zhuike/src/main/java/com/novelbook/android/Fragments/CatalogFragment.java b/zhuike/src/main/java/com/novelbook/android/Fragments/CatalogFragment.java index 0638488..0c8d967 100644 --- a/zhuike/src/main/java/com/novelbook/android/Fragments/CatalogFragment.java +++ b/zhuike/src/main/java/com/novelbook/android/Fragments/CatalogFragment.java @@ -153,7 +153,8 @@ public class CatalogFragment extends BasicFragment implements MarkActivity.Sortc new Thread() { @Override public void run() { - ArrayList list =(ArrayList) LitePal.where("novelId=? and domain =? " ,pageFactory.getNovle().getId()+"",pageFactory.getSite().getDomain()).find(Chapter.class); + // ArrayList list =(ArrayList) LitePal.where("novelId=? and domain =? " ,pageFactory.getNovle().getId()+"",pageFactory.getSite().getDomain()).find(Chapter.class); + ArrayList list =(ArrayList) LitePal.where("novelId=? and domain =? " ,pageFactory.getNovle().getId()+"",pageFactory.getNovle().getDomain()).find(Chapter.class); File file; for(Chapter cp : list){ if(!TextUtils.isEmpty(cp.getChapterPath())) { diff --git a/zhuike/src/main/java/com/novelbook/android/Fragments/Fragment_paihang.java b/zhuike/src/main/java/com/novelbook/android/Fragments/Fragment_paihang.java index 1f1799f..b444698 100644 --- a/zhuike/src/main/java/com/novelbook/android/Fragments/Fragment_paihang.java +++ b/zhuike/src/main/java/com/novelbook/android/Fragments/Fragment_paihang.java @@ -501,7 +501,7 @@ final String TAG = Fragment_paihang.class.getSimpleName(); void getSearchTabTtitle(){ - BookSubscribe.getSearchTitles(new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() { + BookSubscribe.getSearchTitles(Constants.SEX,new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() { @Override public void onSuccess(String result) { diff --git a/zhuike/src/main/java/com/novelbook/android/Main2Activity.java b/zhuike/src/main/java/com/novelbook/android/Main2Activity.java index d4c9e15..98c6032 100644 --- a/zhuike/src/main/java/com/novelbook/android/Main2Activity.java +++ b/zhuike/src/main/java/com/novelbook/android/Main2Activity.java @@ -56,6 +56,9 @@ public class Main2Activity extends Activity_base BottomNavigationView botoomNavigation; @BindView(R.id.rgSex) RadioGroup rgSex; + // @BindView(R.id.tvUser) + // TextView tvUser; + private Config config; @Override public int getLayoutRes() { @@ -78,7 +81,7 @@ public class Main2Activity extends Activity_base // ButterKnife.bind(this); initialSexOption(); - checkUpdate(true); + checkUpdate(true); // getSearchTabTtitle(); } @@ -95,6 +98,7 @@ public class Main2Activity extends Activity_base @Override protected void setTitle() { setTitle(""); + } @Override @@ -102,7 +106,7 @@ public class Main2Activity extends Activity_base creatToolbar(); setupNavi(); showHome(); - + // tvUser.setText(this.getPackageName()); } String currentActiveFragment; @@ -211,6 +215,9 @@ public class Main2Activity extends Activity_base void setupNavi() { //drawer + + + navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); @@ -219,6 +226,8 @@ public class Main2Activity extends Activity_base drawer.addDrawerListener(toggle); toggle.syncState(); + // TextView tvuser= (TextView) navigationView. findViewById(R.id.tvUser); + // tvuser.setText(this.getPackageName()); // mTextMessage = (TextView) findViewById(R.id.message); botoomNavigation = (BottomNavigationView) findViewById(R.id.navigation); botoomNavigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); @@ -458,7 +467,8 @@ private int bottomSelectedIndex; super.onResume(); // swithToolbarItems( ); // setTitle("title on resume"); - + // checkUpdate(true); + // getHostPolicy(); } @Override diff --git a/zhuike/src/main/java/com/novelbook/android/netapi/HttpApi.java b/zhuike/src/main/java/com/novelbook/android/netapi/HttpApi.java index c975774..50206e1 100644 --- a/zhuike/src/main/java/com/novelbook/android/netapi/HttpApi.java +++ b/zhuike/src/main/java/com/novelbook/android/netapi/HttpApi.java @@ -36,7 +36,7 @@ public interface HttpApi { Call downloadFile(@Url String fileUrl); //http://xiaoshuofenxiang.com/api/g/ - @GET("g") + @GET("g/") Observable getMasterDomain(); //http://xiaoshuofenxiang.com/api/n/f2619820112625133c14dcb170f5e092.json @GET("n/{id}") @@ -83,7 +83,7 @@ public interface HttpApi { Observable getSeachNolvelist(@Path("keyword")String keyWord,@Path("pageno")int pageNo,@Query("sex") int Sex); // 搜索分类 http://xiaoshuofenxiang.com/api/page/topdata @GET("page/topdata") - Observable getSearchTitles(); + Observable getSearchTitles(@Query("sex") int Sex); //返回指定id列表的小说列表api/novels/1,2 @GET("novels/{nvs}") Observable getNovelsByIds(@Path("nvs")String nvs ); diff --git a/zhuike/src/main/java/com/novelbook/android/netapi/RandomHost.java b/zhuike/src/main/java/com/novelbook/android/netapi/RandomHost.java index fb1bdad..b749aa3 100644 --- a/zhuike/src/main/java/com/novelbook/android/netapi/RandomHost.java +++ b/zhuike/src/main/java/com/novelbook/android/netapi/RandomHost.java @@ -9,7 +9,7 @@ import org.json.JSONObject; public class RandomHost { - private static final int MAX = 10; + private static final int MAX = 5; private static final Random random = new Random(); //private static final Map indexsMap = new HashMap(); @@ -28,7 +28,7 @@ public class RandomHost { if (maxFixIndex > 0) { randomFill(indexs, 0, 0, maxFixIndex - 1); } - for (int i = maxFixIndex; i < 10; i++) { + for (int i = maxFixIndex; i < MAX; i++) { indexs[i] = i; } //randomFill(indexs, maxFixIndex, maxFixIndex, MAX - 1); @@ -56,8 +56,10 @@ public class RandomHost { private int currentIndex = 0; public String next() { - if (currentIndex >= indexs.length ) + if (indexs == null || indexs.length == 0) return ""; + if (currentIndex >= indexs.length) { return ""; + } else { try { return UrlFactory.getUrl(hosts, uri, indexs[currentIndex++]); diff --git a/zhuike/src/main/java/com/novelbook/android/netsubscribe/BookSubscribe.java b/zhuike/src/main/java/com/novelbook/android/netsubscribe/BookSubscribe.java index 5285541..756fd08 100644 --- a/zhuike/src/main/java/com/novelbook/android/netsubscribe/BookSubscribe.java +++ b/zhuike/src/main/java/com/novelbook/android/netsubscribe/BookSubscribe.java @@ -75,8 +75,8 @@ public class BookSubscribe { Observable observable = HttpMethods.getInstance(String.format("/api/search/%s/%s",keyWord ,pageNo)).getHttpApi().getSeachNolvelist(keyWord,pageNo,sex); HttpMethods.getInstance().toSubscribe(observable, subscriber); } - public static void getSearchTitles(DisposableObserver subscriber){ - Observable observable = HttpMethods.getInstance("/api/page/topdata").getHttpApi().getSearchTitles(); + public static void getSearchTitles(int sex,DisposableObserver subscriber){ + Observable observable = HttpMethods.getInstance("/api/page/topdata").getHttpApi().getSearchTitles(sex); HttpMethods.getInstance().toSubscribe(observable, subscriber); } public static void getHotKeyWords(DisposableObserver subscriber){ diff --git a/zhuike/src/main/java/com/novelbook/android/netutils/HttpMethods.java b/zhuike/src/main/java/com/novelbook/android/netutils/HttpMethods.java index 904b403..07db8e8 100644 --- a/zhuike/src/main/java/com/novelbook/android/netutils/HttpMethods.java +++ b/zhuike/src/main/java/com/novelbook/android/netutils/HttpMethods.java @@ -13,6 +13,7 @@ import com.novelbook.android.utils.FileUtils; import org.json.JSONException; +import org.json.JSONObject; import java.io.File; import java.io.IOException; @@ -45,6 +46,7 @@ import retrofit2.converter.gson.GsonConverterFactory; import static com.novelbook.android.netapi.URLConstant.getRootUrl; import static com.novelbook.android.netapi.URLConstant.newRootUrl; +import static com.novelbook.android.netutils.NetUtil.getHost; public class HttpMethods { public String TAG = "HttpMethods"; @@ -85,10 +87,29 @@ public class HttpMethods { } //获取单例 public static HttpMethods getInstance(String keyUrl) { - SingletonHolder.INSTANCE.changeBaseUrl(NetUtil.getUrl(keyUrl)); + // SingletonHolder.INSTANCE.changeBaseUrl(NetUtil.getUrl(keyUrl)); + try { + SingletonHolder.INSTANCE.ChangeNoForward(keyUrl); + } catch (JSONException e) { + e.printStackTrace(); + } return SingletonHolder.INSTANCE; } - + public void ChangeNoForward(String keyUrl) throws JSONException { + // SingletonHolder.INSTANCE.changeBaseUrl(NetUtil.getUrl(keyUrl)); + // RandomHost rh = new RandomHost( getHost() ,keyUrl); + // okHttpBuilder.addInterceptor(new RetryInterceptor(rh)); + okHttpBuilder.addInterceptor(new RetryInterceptor()); + okHttpBuilder.followRedirects(false); + okHttpBuilder.retryOnConnectionFailure(false); + retrofit = new Retrofit.Builder() + .client(okHttpBuilder.build()) + .addConverterFactory(GsonConverterFactory.create()) + .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) + .baseUrl(getRootUrl()) + .build(); + httpApi = retrofit.create(HttpApi.class); + } //获取单例 public static HttpMethods getInstance() { return SingletonHolder.INSTANCE; @@ -111,9 +132,9 @@ public class HttpMethods { return retrofit; } - public void changeBaseUrl(String baseUrl) { + /*public void changeBaseUrl(String baseUrl) { okHttpBuilder.addInterceptor(new RetryInterceptor()); - // okHttpBuilder.retryOnConnectionFailure(false); + //okHttpBuilder.retryOnConnectionFailure(false); retrofit = new Retrofit.Builder() .client(okHttpBuilder.build()) .addConverterFactory(GsonConverterFactory.create()) @@ -121,7 +142,7 @@ public class HttpMethods { .baseUrl(baseUrl) .build(); httpApi = retrofit.create(HttpApi.class); - } + }*/ /* public void changeBaseUrl() { changeBaseUrl(newBaseUrl()); }*/ @@ -198,10 +219,10 @@ public class HttpMethods { }); - loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); + loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS); //设置 Debug Log 模式 okHttpBuilder.addInterceptor(loggingInterceptor); - + // okHttpBuilder.addInterceptor(new RetryInterceptor()); //设置编码 // EncodingInterceptor encodingInterceptor = new EncodingInterceptor("gbk"); // okHttpBuilder.addInterceptor(encodingInterceptor); @@ -214,6 +235,7 @@ public class HttpMethods { okHttpBuilder.connectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.SECONDS); okHttpBuilder.readTimeout(DEFAULT_WRITE_TIMEOUT, TimeUnit.SECONDS); okHttpBuilder.writeTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.SECONDS); + //错误重连 okHttpBuilder.retryOnConnectionFailure(true); diff --git a/zhuike/src/main/java/com/novelbook/android/netutils/RetryInterceptor.java b/zhuike/src/main/java/com/novelbook/android/netutils/RetryInterceptor.java index 401a487..23710db 100644 --- a/zhuike/src/main/java/com/novelbook/android/netutils/RetryInterceptor.java +++ b/zhuike/src/main/java/com/novelbook/android/netutils/RetryInterceptor.java @@ -4,6 +4,7 @@ import android.text.TextUtils; import android.util.Log; import com.novelbook.android.netapi.RandomHost; +import com.novelbook.android.utils.REUtil; import org.json.JSONException; @@ -15,45 +16,87 @@ import okhttp3.Response; public class RetryInterceptor implements Interceptor { private static final String TAG=RetryInterceptor.class.getSimpleName(); - int RetryCount = 13; - RandomHost rh ; + int RetryCount = 10; public RetryInterceptor(){ } + RandomHost rh = null; + + public RetryInterceptor(RandomHost rh) { + this.rh=rh; + } @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); - // try the request - Response response = doRequest(chain, request); - if(response!=null &&( response.isSuccessful() || response.code() ==200)){ - return response; - } - - int tryCount = 0; String oldUrl = request.url().toString(); + String prefix = REUtil.match("(?i)http[s]?://[^/]+", oldUrl); + if (prefix == null) return doRequest(chain, request); + String path = oldUrl.substring(prefix.length()); + /* if(oldUrl.indexOf("xiaoshuofenxiang.com") == -1 || !path.startsWith("/api/") || NetUtil.getHost()==null){ + rh = null; + return doRequest(chain, request); + }*/ - String key = oldUrl.substring(oldUrl.lastIndexOf(".com/")+5,oldUrl.length()); - if(rh==null) - { + + Response response = null; + while (true) { + try { + if(rh==null) { + rh = new RandomHost(NetUtil.getHost(), path); + Log.d(TAG, "HttpMethods intercept: api path is "+path); + Log.d(TAG, "HttpMethods intercept: create new RandomHost--------------------------"); + } + } catch (JSONException e) { + Log.e(TAG, "intercept: ", e); + + // TODO rh == null + } + String newPrefix = rh.next(); + if ("".equals(newPrefix)) break; + + String newUrl = newPrefix + path; + Log.d(TAG, "HttpMethods intercept: trying url is " + newUrl); + + Request newRequest = null; try { - rh = new RandomHost(NetUtil.getHost(), key); - Log.d(TAG, "HttpMethods intercept: create new RandomHost--------------------------"); - } catch (JSONException e) { - Log.e(TAG, "intercept: ", e); + + newRequest = request.newBuilder().url(newUrl).build(); + } catch (Exception e) { + Log.e(TAG, "HttpMethods intercept: " + newUrl); + Log.e(TAG, "HttpMethods intercept: ", e); + continue; + } + + + if (response != null) { try {response.close();} catch (IllegalStateException e) {} } + response = doRequest(chain, newRequest); + + Log.d(TAG, String.format("HttpMethods intercept: response is null? %s", response == null)); + + if (response != null) { + Log.d(TAG, String.format("HttpMethods intercept: response .code? %s", response.code())); + } + + if (response != null && response.isSuccessful()) { + rh = null; + Log.d(TAG, String.format("HttpMethods intercept: set rh null,return response")); + return response; } } + /* int tryCount=0; String url =oldUrl; while ( (response==null ||!response.isSuccessful()) && tryCount <= RetryCount) { - // if(tryCount>3) + // if(tryCount>3) { //三次不成功后换其他url - url = switchServer(key); + url = switchServer(path); if (url.equals(oldUrl)) { - url = switchServer(key); + url = switchServer(path); } if(TextUtils.isEmpty(url)){ + return null; } } @@ -63,6 +106,7 @@ public class RetryInterceptor implements Interceptor { } catch (Exception e) { Log.e(TAG, "HttpMethods intercept: "+url); Log.e(TAG, "HttpMethods intercept: ", e); + return null; } @@ -73,12 +117,14 @@ public class RetryInterceptor implements Interceptor { tryCount++; // retry the request response = doRequest(chain, newRequest); - } + }*/ + Log.d(TAG, String.format("HttpMethods intercept: set rh null,return response")); + rh = null; if (response == null) { + throw new IOException(); } return response; - } private Response doRequest(Chain chain, Request request) { @@ -86,20 +132,21 @@ public class RetryInterceptor implements Interceptor { try { response = chain.proceed(request); } catch (Exception e) { + // Log.e(TAG, "doRequest: error 1 ",e ); } return response; } - private String switchServer(String key) { + private String switchServer(String key) { String newUrl = rh.next(); if(TextUtils.isEmpty(newUrl)){ return newUrl; } - if(!newUrl.endsWith("/")){ + /* if(!newUrl.endsWith("/")){ newUrl+="/"; - } + }*/ return newUrl +key; } @@ -108,17 +155,4 @@ public class RetryInterceptor implements Interceptor { - - - - - - - - - - - - - } diff --git a/zhuike/src/main/java/com/novelbook/android/upgrade/ParseXmlService.java b/zhuike/src/main/java/com/novelbook/android/upgrade/ParseXmlService.java index 0d3d4b7..ec7054f 100644 --- a/zhuike/src/main/java/com/novelbook/android/upgrade/ParseXmlService.java +++ b/zhuike/src/main/java/com/novelbook/android/upgrade/ParseXmlService.java @@ -34,6 +34,8 @@ public class ParseXmlService { //遍历子节点 Node childNode = childNodes.item(j); + + if (childNode.getNodeType() == Node.ELEMENT_NODE){ Element childElement = (Element) childNode; hashMap.put(childElement.getNodeName(),childElement.getFirstChild().getNodeValue()); @@ -64,4 +66,46 @@ public class ParseXmlService } return hashMap; } + public HashMap> parseMultiXml(InputStream inStream) throws Exception + { + HashMap> hashMap = new HashMap>(); + + // 实例化一个文档构建器工厂 + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + // 通过文档构建器工厂获取一个文档构建器 + DocumentBuilder builder = factory.newDocumentBuilder(); + // 通过文档通过文档构建器构建一个文档实例 + Document document = builder.parse(inStream); + //获取XML文件根节点 + Element root = document.getDocumentElement(); + //获得所有子节点 + NodeList childNodes = root.getChildNodes(); + for (int j = 0; j < childNodes.getLength(); j++) + { + //遍历子节点 + Node childNode = childNodes.item(j); + if (childNode.getNodeType() == Node.ELEMENT_NODE){ + Element childElement = (Element) childNode; + hashMap.put(childElement.getNodeName(),parseChildXml(childNode.getChildNodes())); + } + + } + return hashMap; + } + public HashMap parseChildXml(NodeList childNodes ) throws Exception { + HashMap hashMap = new HashMap(); + for (int j = 0; j < childNodes.getLength(); j++) { + //遍历子节点 + Node childNode = childNodes.item(j); + if (childNode.getNodeType() == Node.ELEMENT_NODE) { + Element childElement = (Element) childNode; + hashMap.put(childElement.getNodeName(), childElement.getFirstChild().getNodeValue()); + } + } + + return hashMap; + + } + + } diff --git a/zhuike/src/main/java/com/novelbook/android/upgrade/UpdateManager.java b/zhuike/src/main/java/com/novelbook/android/upgrade/UpdateManager.java index 4e3f472..25f07ac 100644 --- a/zhuike/src/main/java/com/novelbook/android/upgrade/UpdateManager.java +++ b/zhuike/src/main/java/com/novelbook/android/upgrade/UpdateManager.java @@ -37,6 +37,7 @@ import com.novelbook.android.netsubscribe.BookSubscribe; import com.novelbook.android.netutils.HttpMethods; import com.novelbook.android.netutils.OnSuccessAndFaultListener; import com.novelbook.android.netutils.OnSuccessAndFaultSub; +import com.novelbook.android.utils.CommonUtil; import com.novelbook.android.utils.Constants; import com.novelbook.android.utils.GsonUtil; @@ -57,6 +58,7 @@ public class UpdateManager { private static final int DOWNLOAD_FINISH = 2; private static final int showDialog =3; HashMap mHashMap; + HashMap> multiHashMap; private String mSavePath; private int progress; private boolean cancelUpdate = false; @@ -146,7 +148,8 @@ public class UpdateManager { // String s = body.string(); // Log.d(TAG, "onSuccess: response is " + s); if (bytes != null) { - processTxtOnSuccess(bytes); + // processTxtOnSuccess(bytes); + processMultiTxtOnSuccess(bytes); } // body.close(); }catch (Exception e){ @@ -163,8 +166,44 @@ public class UpdateManager { - } - + } + void processMultiTxtOnSuccess(byte[] paramArrayOfByte) { + + boolean isUpdate=false; + int versionCode = getVersionCode(mContext); + InputStream inputStream = null; + inputStream =new ByteArrayInputStream(paramArrayOfByte); + ParseXmlService service = new ParseXmlService(); + try + { + if(inputStream!=null) + multiHashMap = service.parseMultiXml(inputStream); + + } catch (Exception e) + { + e.printStackTrace(); + } + if (null != multiHashMap) { + String packgename = mContext.getPackageName(); + mHashMap = multiHashMap.get(packgename); + if (mHashMap != null) { + int serviceCode = Integer.valueOf(mHashMap.get("version")); + // need update or not + isUpdate = serviceCode > versionCode; + } + } + + if (isUpdate) + { + mHandler.sendEmptyMessage(showDialog); + + } else + { + if(!isSilence) + Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_LONG).show(); + } + + } void processTxtOnSuccess(byte[] paramArrayOfByte) { boolean isUpdate=false; @@ -216,8 +255,15 @@ public class UpdateManager { try { // 閼惧嘲褰囨潪顖欐閻楀牊婀伴崣鍑ょ礉鐎电懓绨睞ndroidManifest.xml娑撳獘ndroid:versionCode - versionCode = context.getPackageManager().getPackageInfo("com.novelbook.android", 0).versionCode; - } catch (NameNotFoundException e) + versionCode =(int)CommonUtil.getVersionCodeLong(context);// context.getPackageManager().getPackageInfo("com.novelbook.android", 0).versionCode; + /*int versionCode2 = CommonUtil.getVersionCode(context); + long versioncode3 = CommonUtil.getVersionCodeLong(context); + + String versionname = CommonUtil.getVersion(context); + String v = CommonUtil.getVersionName(context); + String packnm = context.getPackageName(); + String p ="A";*/ + } catch ( Exception e) { Log.e(TAG, "getVersionCode: ",e); @@ -288,7 +334,7 @@ public class UpdateManager { builder.setTitle(R.string.soft_update_title); String upgradeDetails=mHashMap.get("details"); - builder.setMessage( mContext.getString(R.string.soft_update_info) +upgradeDetails ); + builder.setMessage( mContext.getPackageName() + " "+ mContext.getString(R.string.soft_update_info) +upgradeDetails ); builder.setPositiveButton(R.string.soft_update_updatebtn, new OnClickListener() { @Override diff --git a/zhuike/src/main/java/com/novelbook/android/utils/CommonUtil.java b/zhuike/src/main/java/com/novelbook/android/utils/CommonUtil.java index 1425a0e..12f4592 100644 --- a/zhuike/src/main/java/com/novelbook/android/utils/CommonUtil.java +++ b/zhuike/src/main/java/com/novelbook/android/utils/CommonUtil.java @@ -330,7 +330,19 @@ public class CommonUtil { return 0; } } - + public static long getVersionCodeLong(Context context) { + try { + PackageManager manager = context.getPackageManager(); + PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0); + return info.getLongVersionCode(); + } catch (Exception e) { + e.printStackTrace(); + return 0; + }catch (NoSuchMethodError e){ + e.printStackTrace(); + return 0; + } + } /** * 获取当前手机系统语言。 * diff --git a/zhuike/src/main/java/com/novelbook/android/utils/Config.java b/zhuike/src/main/java/com/novelbook/android/utils/Config.java index 9b57c2e..53ff537 100644 --- a/zhuike/src/main/java/com/novelbook/android/utils/Config.java +++ b/zhuike/src/main/java/com/novelbook/android/utils/Config.java @@ -187,7 +187,9 @@ public class Config { sp.edit().putString(KEY_BASE_URY,baseUrl).commit(); } public String getBaseUrl(){ - return sp.getString(KEY_BASE_URY,""); + String defaultHost ="{\"master\":[\"http:\\/\\/xiaoshuofenxiang.com\"],\"page\":[\"http:\\/\\/p.xiaoshuofenxiang.com\"],\"report\":[\"http:\\/\\/r.xiaoshuofenxiang.com\"],\"search\":[\"http:\\/\\/s.xiaoshuofenxiang.com\"],\"novel\":[\"http:\\/\\/n.xiaoshuofenxiang.com\"],\"novelsbydot\":[\"http:\\/\\/nbd.xiaoshuofenxiang.com\"],\"user\":[\"http:\\/\\/u.xiaoshuofenxiang.com\"]}"; + + return sp.getString(KEY_BASE_URY,defaultHost); } diff --git a/zhuike/src/main/res/layout/nav_header_main2.xml b/zhuike/src/main/res/layout/nav_header_main2.xml index 5bb45b5..004fe3b 100644 --- a/zhuike/src/main/res/layout/nav_header_main2.xml +++ b/zhuike/src/main/res/layout/nav_header_main2.xml @@ -21,6 +21,7 @@ app:srcCompat="@mipmap/ic_launcher_round" /> - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + @@ -138,6 +96,7 @@ + @@ -167,7 +126,6 @@ -