网络超时处理

This commit is contained in:
mwang 2019-04-25 02:01:18 +08:00
parent 9f964f1e31
commit 7af2c38a0f
18 changed files with 284 additions and 115 deletions

View File

@ -71,7 +71,7 @@ public class Activity_ChgSource extends Activity_base {
@Override
protected void initData() {
pageFactory =PageFactory.getInstance();
pageFactory =PageFactory.getInstance(getApplicationContext());
mSites = new ArrayList<Site>(Arrays.asList(pageFactory.getNovelSites().getSites()));
SiteAdapter mAdapter = new SiteAdapter(this, mSites, R.layout.recycle_list_one_item, new OnItemClickListener() {

View File

@ -196,7 +196,7 @@ public class BookActivity extends Activity_base {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkPermission(BookActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE, EXTERNAL_STORAGE_REQ_CODE, "添加图书需要此权限,请允许");
}
pageFactory = PageFactory.getInstance();
pageFactory = PageFactory.getInstance(getApplicationContext());
// pageFactory.clear();
setBookInfo();//set title ,data from novel list
NetUtil.cancelRequest(mNovel.getNovelId());
@ -686,7 +686,7 @@ void onResponseProcess( String content ,String url){
if(mNovel!=null && mNovel.getId()>0) {
mNovel = LitePal.find(Novel.class, mNovel.getId()); //更新最新进度
if(pageFactory==null){
pageFactory = PageFactory.getInstance();
pageFactory = PageFactory.getInstance(getApplicationContext());
}
if(( pageFactory.getNovle()==null || mNovel.getId() !=pageFactory.getNovle().getId())){
pageFactory.prepareBook(mNovel);

View File

@ -226,7 +226,7 @@ public abstract class BasicFragment extends Fragment {
}
}.start();*/
PageFactory.getInstance().prepareBook(nv ); //打开本地小说内容
PageFactory.getInstance(activity.getApplicationContext()).prepareBook(nv ); //打开本地小说内容
Log.d(TAG, String.format("prepare book %s 开始open book.",nv.getName()) );
ReadActivity.openBook(nv ,activity);
@ -237,7 +237,7 @@ public abstract class BasicFragment extends Fragment {
public void onFault(String errorMsg) {
//失败
Toast.makeText(getActivity(),"Novel 请求失败:"+errorMsg,Toast.LENGTH_SHORT).show();
PageFactory.getInstance().prepareBook(novel ); //打开本地小说内容
PageFactory.getInstance(activity.getApplicationContext()).prepareBook(novel ); //打开本地小说内容
ReadActivity.openBook(novel ,activity);
}
},getActivity()));

View File

@ -70,7 +70,7 @@ public class BookMarkFragment extends BasicFragment implements MarkActivity.Sor
@Override
protected void initListener() {
pageFactory = PageFactory.getInstance();
pageFactory = PageFactory.getInstance(activity.getApplicationContext());
lv_bookmark.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

View File

@ -128,7 +128,7 @@ public class CatalogFragment extends BasicFragment implements MarkActivity.Sortc
showProgressDialog(false,"请稍等");
pageFactory = PageFactory.getInstance();
pageFactory = PageFactory.getInstance(activity.getApplicationContext());
Log.d(TAG, String .format("prepare book: start to open book cate of %s" , pageFactory.getNovle().getName()));

View File

@ -3,6 +3,7 @@ package com.novelbook.android.Fragments;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
@ -71,7 +72,8 @@ final String TAG = Fragment_paihang.class.getSimpleName();
MultiLayout topic_layout1;
@BindView(R.id.topic_layout2)
MultiLayout topic_layout2;
@BindView(R.id.app_bar)
AppBarLayout appBarLayout;
@ -132,10 +134,17 @@ final String TAG = Fragment_paihang.class.getSimpleName();
@Override
public void initData() {
tmp=0;
loadSearchData();
loadSearchData();
}
private void loadSearchData(){
int pn = pageNo;
if(lstSex==null){
// getSearchTabTtitle();
// initTabs();
appBarLayout.setVisibility(View.GONE);
return;
}
appBarLayout.setVisibility(View.VISIBLE);
String sex = lstSex.get(tab1Pos);
String cate = lstNt.get(tab2Pos);
if(pageNo==1) {
@ -210,12 +219,18 @@ final String TAG = Fragment_paihang.class.getSimpleName();
}
@Override
public void initViews(){
/*
showProgressDialog(false,"加载。。。。");
appBarLayout.setVisibility(View.GONE);
if(lstNt==null) {
getSearchTabTtitle();
}
else {
initTabs();
}
//showProgressDialog(false,"加载。。。。");
new Thread(){
@Override
public void run() {
Log.d(TAG, "changing Source: to get site rule" );
Log.d(TAG, "prepare book to load options for search" );
while(lstNt==null){
try {
Thread.sleep(10);
@ -223,14 +238,15 @@ final String TAG = Fragment_paihang.class.getSimpleName();
e.printStackTrace();
}
}
// initTabs();
handler.sendEmptyMessage(2);
}
}.start();*/
}.start();
// getSearchTabTtitle();
//setScrollListner();
initLoadMoreListener();
initTabs();
//initTabs();
}
@ -247,11 +263,12 @@ final String TAG = Fragment_paihang.class.getSimpleName();
}*/
List<String> lstType = Arrays.asList(lstProgress);
topic_layout.initTabNames(lstNt) ;
topic_layout1.initTabNames( lstSex) ;
topic_layout2.initTabNames(Arrays.asList(lstProgress)) ;
topic_layout2.initTabNames(lstType) ;
// topic_layout.initTabNames(lstNt);
appBarLayout.setVisibility(View.VISIBLE);
topic_layout.setOnTabSelectListener(new MultiLayout.OnTabSelectListener() {
@Override
public void select(TextView textView, int i, int i1) {
@ -479,6 +496,47 @@ final String TAG = Fragment_paihang.class.getSimpleName();
}
void getSearchTabTtitle(){
BookSubscribe.getSearchTitles(new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
@Override
public void onSuccess(String result) {
// mFirstPage= gson.fromJson(result, FirstPage.class);
try {
Constants.lstSex = GsonUtil.parserStringBlocks(result,"sex");
Constants.lstNt =GsonUtil.parserStringBlocks(result,"nt");
// Constants.lstProgress =GsonUtil.parserProgressBlocks(result,"progress");
/* getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
initTabs(); // refresh ui 的操作代码
}
});*/
initTabs();
loadSearchData();
} catch (Exception e) {
Log.e(TAG, "onSuccess: prepare book",e );
e.printStackTrace();
}
}
@Override
public void onFault(String errorMsg) {
//失败
Log.d(TAG, "error on get firstpage: " + errorMsg);
}
},getActivity()));
}
}

View File

@ -68,14 +68,14 @@ public class Main2Activity extends Activity_base
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PageFactory.createPageFactory(this);
//PageFactory.createPageFactory(this);
app =(MyApp) getApplicationContext();
// requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
config =Config.getInstance();
// ButterKnife.bind(this);
initialSexOption();
getSearchTabTtitle();
// getSearchTabTtitle();
}

View File

@ -63,7 +63,7 @@ public class MarkActivity extends Activity_base {
@Override
protected void initData() {
pageFactory = PageFactory.getInstance();
pageFactory = PageFactory.getInstance(getApplicationContext());
Log.d(TAG, "prepareBook: pagefactory.mbook is ?" + (pageFactory.getNovle() .getName()) );
//config = Config.getInstance();

View File

@ -15,7 +15,7 @@ public class MyApp extends Application {
super.onCreate();
applicationContext = getApplicationContext();
Config.createConfig(this);
// PageFactory.createPageFactory(this);
PageFactory.createPageFactory(this);
// BlurKit.init(this);

View File

@ -169,7 +169,7 @@ public class ReadActivity extends Activity_base implements SpeechSynthesizerLis
});
config = Config.getInstance();
pageFactory = PageFactory.getInstance();
pageFactory = PageFactory.getInstance(getApplicationContext());
pageFactory.setAd(this);
llTopAd.setVisibility(View.GONE);
@ -688,6 +688,7 @@ public class ReadActivity extends Activity_base implements SpeechSynthesizerLis
// | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
);
pageFactory.setBusy(true);
}
@ -752,9 +753,9 @@ public class ReadActivity extends Activity_base implements SpeechSynthesizerLis
Animation topAnim = AnimationUtils.loadAnimation(this, R.anim.dialog_top_enter);
rl_bottom.startAnimation(topAnim);
appbar.startAnimation(topAnim);
// ll_top.startAnimation(topAnim);
// ll_top.startAnimation(topAnim);// ll_top.setVisibility(View.VISIBLE);
rl_bottom.setVisibility(View.VISIBLE);
// ll_top.setVisibility(View.VISIBLE);
appbar.setVisibility(View.VISIBLE);
}
}

View File

@ -27,7 +27,7 @@ public class MarkAdapter extends BaseAdapter {
public MarkAdapter(Context context, List<BookMarks> list) {
mContext = context;
this.list = list;
pageFactory = PageFactory.getInstance();
pageFactory = PageFactory.getInstance(mContext);
config = config.getInstance();
typeface = config.getTypeface();
}

View File

@ -40,15 +40,15 @@ public class HttpMethods {
public String TAG = "HttpMethods";
public static final String CACHE_NAME = "ZHUIKE";
//public static String BASE_URL = getBaseUrl();
private static final int DEFAULT_CONNECT_TIMEOUT = 30;
private static final int DEFAULT_WRITE_TIMEOUT = 30;
private static final int DEFAULT_READ_TIMEOUT = 30;
private static final int DEFAULT_CONNECT_TIMEOUT = 5;
private static final int DEFAULT_WRITE_TIMEOUT = 5;
private static final int DEFAULT_READ_TIMEOUT = 5;
private Retrofit retrofit;
private HttpApi httpApi;
/**
* 请求失败重连次数
*/
private int RETRY_COUNT = 0;
private int RETRY_COUNT = 3;
private OkHttpClient.Builder okHttpBuilder;
private OkHttpClient okHttpClient;
//构造方法私有

View File

@ -27,6 +27,7 @@ import retrofit2.HttpException;
public class OnSuccessAndFaultSub extends DisposableObserver<ResponseBody>
implements ProgressCancelListener {
private static final String TAG= OnSuccessAndFaultSub.class.getSimpleName();
/**
* 是否需要显示默认Loading
*/
@ -74,7 +75,7 @@ public class OnSuccessAndFaultSub extends DisposableObserver<ResponseBody>
private void showProgressDialog() {
if (showProgress && null != progressDialog) {
progressDialog.setMessage("正在请求网络");
progressDialog.show();
// progressDialog.show();
}
}
@ -136,8 +137,12 @@ public class OnSuccessAndFaultSub extends DisposableObserver<ResponseBody>
mOnSuccessAndFaultListener.onFault("服务错误");
}else if(code == 502) {
HttpMethods.getInstance().changeBaseUrl(); //更新基本信息
Toast.makeText(context,"网关错误 ,请检查您的网络状态",Toast.LENGTH_LONG).show();
mOnSuccessAndFaultListener.onFault("服务错误");
try {
Toast.makeText(context, "服务器开小差了,请重试", Toast.LENGTH_LONG).show();
}catch (Exception e3){
Log.e(TAG, "prepare book onError: ",e3);
}
mOnSuccessAndFaultListener.onFault("服务器开小差了,请重试");
}else {
// ToastManager.showShortToast("请求失败");
mOnSuccessAndFaultListener.onFault("请求失败");
@ -150,7 +155,7 @@ public class OnSuccessAndFaultSub extends DisposableObserver<ResponseBody>
mOnSuccessAndFaultListener.onFault("error:" + e.getMessage());
}
} catch (Exception e2) {
e2.printStackTrace();
Log.e(TAG, "prepare book onError: ",e );
} finally {
Log.e("OnSuccessAndFaultSub", "error:" + e.getMessage());
// mOnSuccessAndFaultListener.onFault("error:" + e.getMessage());

View File

@ -217,6 +217,7 @@ public class BookUtil {
}
public void getTargetSites(){
Log.d(TAG, "prepare book: getTargetSites" );
BookSubscribe.getNovelSites(mNovel.getNovelId(),new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() {
@Override
public void onSuccess(String result) {
@ -240,6 +241,8 @@ public class BookUtil {
@Override
public void onFault(String errorMsg) {
Log.d(TAG, String.format("prepare book %s get target sites fail.thread %s ,msg %s",mNovel.getName(),Thread.currentThread().getName(),errorMsg) );
//失败
// Toast.makeText(mContext,"getMuluInfo 请求失败"+errorMsg,Toast.LENGTH_SHORT).show();
}
@ -303,8 +306,10 @@ public class BookUtil {
public int getChapterNo() {
if(chapterNo > mChapters.size()){
Log.d(TAG, String.format(" prepare book getChapterNo ,chapterNo %s, getChapters().size() %s " ,chapterNo , mChapters.size()) );
chapterNo =1;
}
Log.d(TAG, String.format(" prepare book getChapterNo ,chapterNo %s, getChapters().size() %s " ,chapterNo , mChapters.size()) );
return chapterNo;
}
@ -365,6 +370,11 @@ public class BookUtil {
return mSite !=null? mSite.getDomain():"";
}
public boolean chaptCached(int num) {
File f = new File(fileChapterName(num));
return f.exists();
}
private class BookTask extends AsyncTask<String,Void,Boolean> {
private String domain;
private int chapId;
@ -568,7 +578,7 @@ int muluRetryCount =0;
}
mMuluStatus = MuluStatus.failed;
if (muluRetryCount < 3) {
if (muluRetryCount < Constants.retryCnt) {
try {
Thread.sleep(50);
} catch (InterruptedException e1) {
@ -610,7 +620,7 @@ int muluRetryCount =0;
Log.d(TAG,String.format("prepare book loadChapts----failed, %s 目录 from %s,return code %s", mNovel.getName() ,url,response.code() ));
handler.sendEmptyMessage(3);
mMuluStatus = MuluStatus.failed;
if(muluRetryCount <3){
if(muluRetryCount <Constants.retryCnt){
Log.d(TAG,String.format("prepare book loadChapts----failed, response code %s retrying count %s",response.code(), muluRetryCount ));
muluRetryCount++;
readChaptersAsync();
@ -761,8 +771,8 @@ int muluRetryCount =0;
return line.toCharArray();
}
public char chaptCurrent(){
chapterNo = mChapters.size() < chapterNo ? 1 : chapterNo;
// chapterNo = mChapters.size() < chapterNo ? 1 : chapterNo;
// Log.d(TAG, String.format(" prepare book chaptCurrent() ,chapterNo %s, getChapters().size() %s " ,chapterNo , mChapters.size()) );
char[] charArray = chaptChars(chapterNo);
@ -1071,7 +1081,7 @@ int muluRetryCount =0;
}
synchronized void setDownloadFlag(boolean flag){
isDownloadChapt = flag;
Log.d("loadChaptContent",String.format("set download flat",isDownloadChapt) );
Log.d(TAG,String.format("set download flat",isDownloadChapt) );
}
public ChangeSource pagefactory;
Handler handler = new Handler() {
@ -1090,7 +1100,7 @@ int muluRetryCount =0;
void handlerMsg(Message msg){
if (msg.what == 123) {
isDownloadChapt =true;
Log.d("loadChaptContent",String.format("handler msg, download %s",isDownloadChapt) );
Log.d(TAG,String.format("handler msg, download %s",isDownloadChapt) );
}else if(msg.what==1){
isDownloadChapt =true;
// Toast.makeText(mContext,"网络错误",Toast.LENGTH_LONG).show();
@ -1181,12 +1191,16 @@ int muluRetryCount =0;
if(chaptCache.containsKey(Integer.valueOf(index))) {
block = chaptCache .get(index).getData().get();
}
// Log.d(TAG, String.format("prepare book begin to load content for chapter %s", index));
if (block == null) {
// cleanCacheFile(); //to remove
try {
File file = new File(fileChapterName(index));
Log.d(TAG, String.format("prepare book begin to load content for chapter %s,file exists?%s", index,file.exists()));
if (!file.exists()) {
Log.d(TAG, String.format("prepare book loadChapts---- %s, 目录数量 %s, MuluStatus %s , mChapters.size() %s, thread %s", mNovel.getName(), mChapters.size(), mMuluStatus
, mChapters.size()
, Thread.currentThread().getName()));
if (mMuluStatus == null) {
Log.d(TAG, String.format("prepare book loadChapts---- 还未有目录信息,出错了 %s 目录, 目录数量 %s, MuluStatus %s ,thread %s", mNovel.getName(), mChapters.size(), mMuluStatus, Thread.currentThread().getName()));
@ -1204,42 +1218,67 @@ int muluRetryCount =0;
}
}
if (!NetUtil.isNetworkConnected() || muluRetryCount >= 3 && (mChapters == null || mChapters.size() == 0)) {
Log.d(TAG, String.format("loadChapts----超时。。。或出错了 %s 目录, 目录数量 %s, slept %s, MuluStatus %s,thread %s", mNovel.getName(), mChapters.size(), slept, mMuluStatus, Thread.currentThread().getName()));
if (!NetUtil.isNetworkConnected() || muluRetryCount >= Constants.retryCnt && (mChapters == null || mChapters.size() == 0)) {
Log.d(TAG, String.format("prepare book loadChapts----超时。。。或出错了 %s 目录, 目录数量 %s, slept %s, MuluStatus %s,thread %s", mNovel.getName(), mChapters.size(), slept, mMuluStatus, Thread.currentThread().getName()));
String error = "网络不给力";
return error.toCharArray();
}
Log.d(TAG, String.format("loadChaptContent----start %s", new Date().toString()));
Log.d(TAG, String.format("prepare book loadChaptContent----start %s", new Date().toString()));
Log.d("loadChaptContent", String.format("begin to load content for chapter %s", index));
Log.d("loadChaptContent", String.format("isDownloadChapt: %s", isDownloadChapt));
Log.d(TAG, String.format("prepare book isDownloadChapt: %s", isDownloadChapt));
if (!chaptDownStatus.containsKey(Integer.valueOf(index))) {
chaptDownStatus.put(index, DownloadStatus.downloading);
Log.d(TAG, String.format("prepare book put chaptDownStatus index %s,start to load chapcontent", index));
loadChaptContent(index);
}
Log.d(TAG, String.format(" prepare book loadChaptContent %s for downloading,isDownload %s chaptDownStatus %s, thread %s ",
index,getDownloadStatus(), chaptDownStatus.get(Integer.valueOf(index)), Thread.currentThread().getName()));
Log.d("loadChaptContent", String.format("showing dialog "));
// Log.d(TAG,String.format("showing progress diaglog......"));
int maxSleep = 4500;
int slepttime = 0;
// while(!file.exists() && !getDownloadStatus()){//&& slepttime <maxSleep){
// while( !getDownloadStatus() && slepttime <maxSleep){
while (NetUtil.isNetworkConnected() && !getDownloadStatus() && chaptDownStatus.get(Integer.valueOf(index)) == DownloadStatus.downloading && slepttime < maxSleep) {
/* while (NetUtil.isNetworkConnected() && !getDownloadStatus() && chaptDownStatus.get(Integer.valueOf(index)) == DownloadStatus.downloading && slepttime < maxSleep) {
Thread.sleep(50);
slepttime += 50;
Log.d(TAG, String.format(" prepare book loadChaptContent slept %s for downloading,isDownload %s thread %s ", slepttime, getDownloadStatus(), Thread.currentThread().getName()));
}*/
while (!file.exists() && NetUtil.isNetworkConnected() && chaptDownStatus.get(Integer.valueOf(index)) == DownloadStatus.downloading && slepttime < maxSleep) {
Thread.sleep(50);
slepttime += 50;
Log.d(TAG, String.format(" prepare book loadChaptContent %s , slept %s for downloading,isDownload %s thread %s ",index, slepttime, getDownloadStatus(), Thread.currentThread().getName()));
}
Log.d("loadChaptContent", String.format("loadChaptContent slept %s for downloading ", slepttime));
Log.d(TAG, String.format("prepare book loadChaptContent slept %s for downloading ", slepttime));
if (chaptDownStatus.get(Integer.valueOf(index)) == DownloadStatus.failure) {
if (fileRetryCnt.containsKey(index)) {
fileRetryCnt.put(index, fileRetryCnt.get(index) + 1);
} else {
fileRetryCnt.put(index, 1);
}
Log.d(TAG, String.format("prepare book loadChaptContent %s, rertying count %s ",index, fileRetryCnt.get(index)));
if (fileRetryCnt.get(index) < Constants.retryCnt) {
Log.d(TAG, String.format("prepare book loadChaptContent ,rertying to download chapt %s ", index));
loadChaptContent(index);
}
}
}
Log.d("loadChaptContent", String.format(" %s, file.exists()? %s", file.getPath(), file.exists()));
if (!file.exists() && !NetUtil.isNetworkConnected()) {
String error = "网络不给力";
Log.d(TAG, String.format(" prepare book %s, file.exists()? %s", file.getPath(), file.exists()));
if (!file.exists()) {
String error = "下载内容失败";
if( !NetUtil.isNetworkConnected()){
error = "连不上网络";
}
Log.d(TAG, String.format("prepare book loadChaptContent retrying " ));
// return chaptChars( index);
return error.toCharArray();
}
if (mChapters.size() > index && NetUtil.isNetworkConnected()) {
@ -1311,6 +1350,7 @@ int muluRetryCount =0;
return block;
}
Map<Integer,Integer> fileRetryCnt = new HashMap<Integer,Integer>();
private void loadChaptContent(final int chapterIndex) throws JSONException, InterruptedException {
/* 章节内容没有缓存在本地
1. 根据本地的章节网络地址信息读取章节内容到本地若读取失败则
@ -1338,7 +1378,7 @@ private void loadChaptContent(final int chapterIndex) throws JSONException, Inte
setDownloadFlag(false);
Log.d( "loadChaptContent",String.format("loadChaptContent isDownloadChapt: %s",isDownloadChapt));
Log.d( TAG,String.format("loadChaptContent isDownloadChapt: %s",isDownloadChapt));
JSONObject siteJson = new JSONObject();
siteJson.put("chapterContentRegex", mSiteRule.getChapterContentRegex());
siteJson.put("chapterContentDumpRegex", mSiteRule.getChapterContentDumpRegex());
@ -1351,11 +1391,13 @@ private void loadChaptContent(final int chapterIndex) throws JSONException, Inte
// return;
}
handler.sendEmptyMessage(123);
handler.sendEmptyMessage(1);
// handler.sendEmptyMessage(123);
// handler.sendEmptyMessage(1);
chaptDownStatus.put(index,DownloadStatus.failure);
setDownloadFlag(true);
Log.d( "loadChaptContent",String.format("loadChaptContent fail, isDownloadChapt: %s",isDownloadChapt));
Log.d( TAG,String.format("prepare book loadChaptContent fail, isDownloadChapt: %s",isDownloadChapt));
e.printStackTrace();
// throw new RuntimeException("Error during writing " + fileChapterName( index));
}
@ -1365,10 +1407,10 @@ private void loadChaptContent(final int chapterIndex) throws JSONException, Inte
ResponseBody body = response.body();
if (body != null ) {
if(response.code()!=200){
Log.d(TAG, "loadChaptContent----network failure returnCode " + response.code());
Log.d(TAG, "prepare book loadChaptContent----network failure returnCode " + response.code());
setDownloadFlag(true);
chaptDownStatus.put(index,DownloadStatus.failure);
Log.d( "loadChaptContent",String.format("loadChaptContent error %s ,isDownloadChapt: %s", response.code(),isDownloadChapt));
Log.d( TAG,String.format("prepare book loadChaptContent error %s ,isDownloadChapt: %s", response.code(),isDownloadChapt));
handler.sendEmptyMessage(1);
return;
}
@ -1385,7 +1427,7 @@ private void loadChaptContent(final int chapterIndex) throws JSONException, Inte
final OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(fileChapterName(index)), charachterType);//"UTF-16LE"); // UTF-16LE utf-8 文件小
writer.write(buf);
writer.close();
Log.d( "loadChaptContent",String.format("prepare book loadChaptContent file created: %s, thread %s", file.getPath(), Thread.currentThread().getName()));
Log.d( TAG,String.format("prepare book loadChaptContent file created: %s, thread %s", file.getPath(), Thread.currentThread().getName()));
handler.sendEmptyMessage(123);
setDownloadFlag(true);
} catch (IOException | JSONException e) {

View File

@ -14,5 +14,7 @@ public class Constants {
public static List<String> lstSex =null;
public static List<String> lstNt=null;
//public static List<Progress> lstProgress=null;
public static String[] lstProgress={"连载中","已完本","新书"};
public static String[] lstProgress={"连载中","已完本","新书"};
public static int retryCnt =10;
// public static List<String> lstProgress=null;
}

View File

@ -36,7 +36,9 @@ import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//import static com.baidu.tts.loopj.AsyncHttpClient.log;
@ -188,12 +190,40 @@ public class PageFactory implements ChangeSource{
void handlerMsg(Message msg) {
if (msg.what == 1) {
changeChapter(currentChapter);
Log.d(TAG, String.format("prepare book handler get notic to download chapter %s , mBook is null? %s",currentChapter, mBook==null ) );
if (mBook != null) {
changeChapter(currentChapter);
}else{
mStatus = Status.FAIL;
drawStatus(mBookPageWidget.getCurPage());
drawStatus(mBookPageWidget.getNextPage());
}
}
}
Map<Integer,Integer> fileRetryCnt = new HashMap<Integer,Integer>();
private List<TRPage> loadCurrentChapt(int chaptId){
Log.d(TAG, String.format("prepare book, loadCurrentChapt chaptId %s, getChapters().size() %s ",chaptId,getChapters().size() ) );
Log.d(TAG, String.format("prepare book, loadCurrentChapt chaptId %s, getChapters().size() %s ,currentChapter %s",chaptId,getChapters().size() ,currentChapter) );
List<TRPage> chaptPages = new ArrayList<TRPage>();
chaptPages.add(new TRPage());
if (fileRetryCnt.containsKey(chaptId)) {
fileRetryCnt.put(chaptId, fileRetryCnt.get(chaptId) + 1);
} else {
fileRetryCnt.clear();//只保留一个章节数据
fileRetryCnt.put(chaptId, 1);
}
Log.d(TAG, String.format("prepare book loadCurrentChapt %s, rertying count %s ",chaptId, fileRetryCnt.get(chaptId)));
if(fileRetryCnt.get(chaptId) > Constants.retryCnt){
mStatus = Status.FAIL;
drawStatus(mBookPageWidget.getCurPage());
drawStatus(mBookPageWidget.getNextPage());
return chaptPages;
}
final File file = new File(getChapterFileName(chaptId));
if (!file.exists()) { //待下载
@ -202,8 +232,7 @@ public class PageFactory implements ChangeSource{
chaptId = chaptId > 0 ? chaptId : 1;
}
List<TRPage> chaptPages = new ArrayList<TRPage>();
chaptPages.add(new TRPage());
@ -227,7 +256,7 @@ public class PageFactory implements ChangeSource{
drawStatus(mBookPageWidget.getNextPage());
return chaptPages;
}
if(getChapters().size()==0 && mBookUtil.muluRetryCount>=3) {
if(getChapters().size()==0 && mBookUtil.muluRetryCount>=Constants.retryCnt) {
Log.d(TAG, String.format("prepare book download mulu 失败,重试次数: %s ,thread.name %s",mBookUtil.muluRetryCount,Thread.currentThread().getName() ) );
mBookUtil.muluRetryCount=0;
mStatus = Status.FAIL;
@ -250,7 +279,7 @@ public class PageFactory implements ChangeSource{
@Override
public void run() {
int slepttime =0;
while( !file.exists() && slepttime <100 && mBookUtil.muluRetryCount<3){
while( !file.exists() && slepttime <60 && mBookUtil.muluRetryCount<Constants.retryCnt){
try {
sleep(50);
slepttime++;
@ -261,10 +290,10 @@ public class PageFactory implements ChangeSource{
Log.d(TAG, String.format("prepare book to download chapter %s ,slepted %s ,thread.name %s",chid,slepttime*50 ,Thread.currentThread().getName() ) );
mStatus = Status.FINISH;
if( mBookUtil.muluRetryCount>=3){
if( mBookUtil.muluRetryCount>=Constants.retryCnt){
mStatus = Status.FAIL;
}
Log.d(TAG, String.format("prepare book to download chapter %s ,handler notice changeChapter %s",chid, currentChapter ) );
//notice file done
handler.sendEmptyMessage(1);
@ -294,10 +323,10 @@ public class PageFactory implements ChangeSource{
// chaptId = mChapters!=null && mChapters.size() <= chaptId ? 1 : chaptId;
Log.d(TAG, String.format("changing Source prepare book to open chapter %s ",chaptId ) );
Log.d(TAG, String.format("changing Source prepare book to open chapter %s, currentChapter %s ",chaptId ,currentChapter ) );
char[] chars = mBookUtil.chaptChars(chaptId);
String s = new String(chars);
// Log.d(TAG, String.format("prepare book to open chapter %s,chars %s ",chaptId ,s ) );
// Log.d(TAG, String.format("prepare book open chapter %s,chars %s ",chaptId ,s ) );
mBookUtil.setBookLen(chars.length);
mBookUtil.setChapterNo(chaptId);
// TRPage page = new TRPage();
@ -306,7 +335,7 @@ public class PageFactory implements ChangeSource{
while(length <chars.length ) {
pageNo++;
TRPage page = getNextChapterPage(length);
// Log.d(TAG,"prepare book page.getBegin :" + page.getBegin()+ ",chapter length "+ mBookUtil.getBookLen());
// Log.d(TAG,"prepare book page.getBegin :" + page.getBegin()+ ",chapter length "+ mBookUtil.getBookLen());
// if(page.getBegin() == mBookUtil.getBookLen() ){ //最后一页空白的情况
@ -321,6 +350,7 @@ public class PageFactory implements ChangeSource{
length= page.getEnd();
}
mStatus = Status.FINISH;
Log.d(TAG, String.format("changing Source prepare book to draw chapter %s, currentChapter %s ",chaptId ,currentChapter ) );
drawStatus(mBookPageWidget.getCurPage());
drawStatus(mBookPageWidget.getNextPage());
return chaptPages;
@ -330,9 +360,9 @@ public class PageFactory implements ChangeSource{
TRPage trPage = new TRPage();
trPage.setBegin(position +1);
Log.d(TAG,"page postion next begin:" + (position + 1) + "");
// Log.d(TAG,"page postion next begin:" + (position + 1) + "");
trPage.setLines(getNextLines());
Log.d(TAG,"page postion next end:" +mBookUtil.getPosition() + "");
// Log.d(TAG,"page postion next end:" +mBookUtil.getPosition() + "");
trPage.setEnd(mBookUtil.getPosition());
return trPage;
}
@ -400,7 +430,10 @@ public static boolean busy(){
SERVERERROR
}
public static synchronized PageFactory getInstance(){
public static synchronized PageFactory getInstance(Context context){
if(pageFactory==null){
createPageFactory(context);
}
return pageFactory;
}
@ -510,7 +543,7 @@ public static boolean busy(){
}
private void calculateLineCount(float paragrapheight){
mLineCount = (int) ((mVisibleHeight - paragrapheight ) / (m_fontSize + lineSpace));// 可显示的行数
Log.d(TAG,"line count is " + mLineCount +" paragrapheight is " +paragrapheight);
// Log.d(TAG,"line count is " + mLineCount +" paragrapheight is " +paragrapheight);
}
private void drawStatus(Bitmap bitmap){
mAd.hideSystemUI();
@ -553,9 +586,13 @@ public static boolean busy(){
if(m_lines.size()==0){
return;
}
// Log.d(TAG, String.format(" prepare book onDraw chapter %s, getChapters().size() %s ",currentChapter ,getChapters().size() ) );
if (getChapters().size() > 0 && updateChapter) {
// Log.d(TAG, String.format(" prepare book onDraw chapter to getCurrentChapter(),currentChapter %s ",currentChapter ) );
currentChapter = getCurrentChapter();
// Log.d(TAG, String.format(" prepare book onDraw chapter after getCurrentChapter(),currentChapter %s ",currentChapter ) );
}
// Log.d(TAG, String.format(" prepare book onDraw chapter _____________ %s ",currentChapter ) );
//更新数据库进度
if ( mStatus ==Status.FINISH && currentPage != null && mBook != null){
new Thread() {
@ -618,24 +655,24 @@ public static boolean busy(){
strLine =strLine.replace("\n","");
y += space;
space =m_fontSize + paragraphSpace;
Log.d( TAG ,String.format("开始新段落 %s, y plus is %s" ,strLine, m_fontSize + paragraphSpace));
// Log.d( TAG ,String.format("prepare book 开始新段落 %s, y plus is %s" ,strLine, m_fontSize + paragraphSpace));
}else{
y += space;
space =m_fontSize + lineSpace;
Log.d(TAG,String.format("%s,y plus is %s" ,strLine, m_fontSize + lineSpace));
// Log.d(TAG,String.format("prepare book %s,y plus is %s" ,strLine, m_fontSize + lineSpace));
}
c.drawText(strLine, measureMarginWidth, y, mPaint);
// word.append(strLine);
}
Log.d(TAG,String.format("getNavigationBarSize mHeight is %s ,last line height %s, power %s, %s",
mHeight,y,mHeight - CommonUtil.convertDpToPixel(mContext,10) + mBorderWidth - statusMarginBottom, lastLine));
// Log.d(TAG,String.format("getNavigationBarSize mHeight is %s ,last line height %s, power %s, %s",
// mHeight,y,mHeight - CommonUtil.convertDpToPixel(mContext,10) + mBorderWidth - statusMarginBottom, lastLine));
float adHeight = mHeight -y - space -marginHeight-statusMarginBottom;
float adY =y +space;
showAd((int)adHeight,(int)adY);
Log.d(TAG,String.format("ad + statusMarginBottom %s ",200+ statusMarginBottom));
Log.d(TAG,String.format("adHeight %s, adY %s",adHeight,adY));
// Log.d(TAG,String.format("ad + statusMarginBottom %s ",200+ statusMarginBottom));
// Log.d(TAG,String.format("adHeight %s, adY %s",adHeight,adY));
}
//画进度及时间
@ -759,7 +796,7 @@ public static boolean busy(){
}
}
Log.d(TAG, "prepare book nextPage: to open next page: ");
// Log.d(TAG, "prepare book nextPage: to open next page: ");
cancelPage = currentPage;
onDraw(mBookPageWidget.getCurPage(),currentPage.getLines(),true);
prePage = currentPage;
@ -784,6 +821,9 @@ public static boolean busy(){
}
public void prepareBook(Novel book){
Log.d(TAG, "prepare book: start prepare book " + book.getName());
if(mBook!=null &&mBook.getNovelId() !=book.getNovelId()){ //取消未上本书完成的web请求待验证效果
try {
NetUtil.cancelRequest(mBook.getNovelId() );
@ -794,7 +834,7 @@ public static boolean busy(){
}
}
Log.d(TAG, "prepare book: .start prepare book " + book.getName());
this.mBook = book ;
mBookUtil = new BookUtil();
//this.mBookUtil.setContext(context);
@ -912,7 +952,8 @@ public static boolean busy(){
*/
int nextPageNo =currentPage.getPageNo();
Log.e(TAG,"currentChaptPages.size() is " + currentChaptPages.size() +", currentpage pageno is " + nextPageNo);
Log.e(TAG,String.format("prepare book getNextPage() currentChapter %s, currentChaptPages .size() is %s,currentpage pageno is %s"
,currentChapter, currentChaptPages.size() ,currentChapter, nextPageNo));
if(nextPageNo >= currentChaptPages.size()){
preChaptPages =currentChaptPages;
currentChapter++;
@ -962,13 +1003,14 @@ public static boolean busy(){
trPage.setEnd(mBookUtil.getPosition());
return trPage;
*/
Log.d(TAG, String.format("prepare book getPageForBegin: chaptid %s, begin %s ",currentChapter,begin));
for(TRPage page : currentChaptPages)
{
if(page.getEnd() >begin){
return page;
}
}
//return new TRPage();// currentChaptPages.get(currentChaptPages.size()-1);
return currentChaptPages.get(currentChaptPages.size()-1);
}
@ -1000,7 +1042,7 @@ public static boolean busy(){
height += paragraphSpace - lineSpace;
calculateLineCount(height);
if (lines.size()>= mLineCount){
Log.d(TAG,String.format("lines count limit a %s,lines size %s",mLineCount,lines.size()));
// Log.d(TAG,String.format("lines count limit a %s,lines size %s",mLineCount,lines.size()));
line ="";
break;
}
@ -1024,7 +1066,7 @@ public static boolean busy(){
}
if (lines.size() == mLineCount){
Log.d(TAG,String.format("lines count limit c %s,lines size %s",mLineCount,lines.size()));
// Log.d(TAG,String.format("lines count limit c %s,lines size %s",mLineCount,lines.size()));
if (!line.isEmpty()){
// mBookUtil.setPostition(mBookUtil.getPosition() - line.length()-2);// mBookUtil.setPostition(mBookUtil.getPosition() - 1);
mBookUtil.setPostition(mBookUtil.getPosition() - 1);
@ -1051,9 +1093,9 @@ public static boolean busy(){
}
// lines.add(line);
}
for (String str : lines){
/*for (String str : lines){
Log.d(TAG,str + " ");
}
}*/
return lines;
}
@ -1126,7 +1168,11 @@ public static boolean busy(){
//上一章
public void preChapter(){
if (mBookUtil.getChapters().size() > 0){
fileRetryCnt.clear();
if(currentChapter==1){
Toast.makeText(mContext,"到头了",Toast.LENGTH_SHORT).show();
}
// if (mBookUtil.getChapters().size() > 0 ){
int num = currentChapter;
if (num ==1){
num = getCurrentChapter();
@ -1143,16 +1189,22 @@ public static boolean busy(){
}
}
}
//}
//下一章
public void nextChapter(){
fileRetryCnt.clear();
int num = currentChapter;
if (num == 0){
num = getCurrentChapter();
}
if(num==getChapters().size()){
Toast.makeText(mContext,"没有了",Toast.LENGTH_SHORT).show();
}
num ++;
if (num <= getChapters().size()){
if (num <= getChapters().size() || mBookUtil.chaptCached(num)){
preChaptPages =currentChaptPages;
currentChapter = num;
@ -1179,12 +1231,13 @@ public static boolean busy(){
*/
currentChapter = mBookUtil.getChapterNo();
// Log.d(TAG, String.format(" prepare book onDraw chapter after mBookUtil.getChapterNo(),currentChapter %s ",currentChapter ) );
return currentChapter ;
}
//绘制当前页面
public void currentPage(Boolean updateChapter){
Log.d(TAG, "prepare book currentPage: to open current Page : ");
// Log.d(TAG, "prepare book currentPage: to open current Page : ");
onDraw(mBookPageWidget.getCurPage(),currentPage.getLines(),updateChapter);
onDraw(mBookPageWidget.getNextPage(),currentPage.getLines(),updateChapter);
}
@ -1220,7 +1273,9 @@ public static boolean busy(){
//改变章节
public void changeChapter(int chapNum){
if (mBook == null) {
return;
}
preChaptPages =currentChaptPages;
currentChapter = chapNum;
mBookUtil.setChapterNo(currentChapter);
@ -1341,6 +1396,7 @@ public static boolean busy(){
public void clear(){
Log.d(TAG, String .format("prepare Book: clearing book info %s" , getNovle().getName()));
fileRetryCnt.clear();
//mBookUtil=null;
currentChapter = 0;
bookPath = "";

View File

@ -112,7 +112,7 @@
android:layout_height="40dp"
android:background="@color/white"
android:gravity="center"
android:text="selected texts"
android:text=""
android:textColor="@color/red"
android:textSize="15sp"
/>
@ -141,7 +141,7 @@
android:divider="#ffff0000"
android:dividerHeight="10dp"
android:nestedScrollingEnabled="true"
android:paddingBottom="50dp" />
android:paddingBottom="35dp" />

View File

@ -10,7 +10,31 @@
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:clipToPadding="true"
android:fitsSystemWindows="true"
android:theme="@style/AppTheme.AppBarOverlay"
android:visibility="gone">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/read_dialog_bg"
android:fitsSystemWindows="true"
android:minHeight="?attr/actionBarSize"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<!-- <android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>-->
<com.novelbook.android.view.PageWidget
android:id="@+id/bookpage"
android:layout_width="match_parent"
@ -36,26 +60,7 @@
</FrameLayout>
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:fitsSystemWindows="true"
android:theme="@style/AppTheme.AppBarOverlay"
android:visibility="gone">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/read_dialog_bg"
android:fitsSystemWindows="true"
android:minHeight="?attr/actionBarSize"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<!--<LinearLayout-->
<!--android:id="@+id/ll_status"-->