LibraryFragment
public class LibraryFragment extends Fragment {
private GridView gridview;
private LibraryAdpter libraryAdpter;
private List<Book> books;
private Context ctx;
private final String TAG = "LibraryFragment";
private boolean isWeb = false;
private boolean delFalg = false;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.library_fragment, container, false);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx = getActivity();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
gridview = (GridView) getActivity().findViewById(R.id.grid);
if(isWeb){
getBookFromWeb();
}else{
getBookFromNativa();
}
}
public LibraryFragment(){
}
public LibraryFragment(boolean isWeb){
this.isWeb = isWeb;
}
public static LibraryFragment newInstance(boolean isWeb) {
LibraryFragment lf = new LibraryFragment();
Bundle args = new Bundle();
lf.setArguments(args);
return lf;
}
private void getBookFromWeb() {
WebRequest.requestFromWeb(new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] arg1,
byte[] responseBody) {
if (statusCode == 200) {
String result = new String(responseBody);
String syncTime = BookDas.pushBookData2Db(result);
books = BookDas.getBooks( BookDas.getCurrentUserRestypes(), 0);
if (syncTime == null ||!syncTime.isEmpty()) {
BookDas.updateSynctime( syncTime);
}
if (books != null) {
libraryAdpter = new LibraryAdpter(ctx,
books,gridview);
gridview.setAdapter(libraryAdpter);
}
}
}
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable erro) {
Logger.e(TAG, "失败::" + erro.getLocalizedMessage());
}
}, CommConst.REQUEST_BOOKLIST_METHOD, new String[][] {
{ "platform", CommConst.PLATFORM_VAL}, {"synctime", BookDas.getLastSyncTime()}
});
}
private void getBookFromNativa(){
books = BookDas.getBooks( BookDas.getCurrentUserRestypes(),1);
if (books != null) {
libraryAdpter = new LibraryAdpter(ctx, books,gridview);
gridview.setAdapter(libraryAdpter);
gridview.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
libraryAdpter.setDelFlag(true);
delFalg = true;
return true;
}
});
gridview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
if(delFalg){
delFalg = false;
libraryAdpter.setDelFlag(false);
}
}
});
}
}
}
library_fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<View
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="6.5"
android:orientation="horizontal" >
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<GridView
android:id="@+id/grid"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="8"
android:listSelector="#00000000"
android:scrollbars="none"
android:numColumns="3" />
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5" />
</LinearLayout>
LibraryAdpter
public class LibraryAdpter extends BaseAdapter {
private List<Book> books = null;
private LayoutInflater infater = null;
private AsyncImageDownloader mDownloader;
private GridView mGridView1;
private Context mContext;
private boolean delFlag = false;
private LayoutInflater mInflater;
private static final int QUERY_DOWNLOAD_PROGRESS = 1 << 4;
private static final int QUERY_DOWNLOAD_UNZIP = 1 << 2;
private static final int DELETE_BOOK = 1 << 3;
// 下载管理类
private IwitDownloadManager manager;
// 更新进度条进度
private MyContentObserver mMyContentObserver;
// 解压类
FileManager mFileManager;
// 是否有网络
private int nativeOrLoad;
private OnClickCloseChangListener mOnClickCloseChangListener;
private String T = "BookAdapter";
private FileUtils mFileUtils;
private static final int MB = 1024 * 1024;
// 接口 监听数据库
public LibraryAdpter(Context context, List<Book> inbook, GridView mGridView) {
mContext = context;
infater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
books = inbook;
manager = IwitDownloadManager.getInstance(App.ctx);
// 内容观察数据库内容的
mMyContentObserver = new MyContentObserver(App.ctx, manager,
mOnContentListener);
mGridView1 = mGridView;
// 注册内容观察者
App.ctx.getContentResolver().registerContentObserver(
Downloads.Impl.CONTENT_URI, true, mMyContentObserver);
mFileUtils = FileUtils.getInstance();
mFileManager = FileManager.getInstance();
// 第一次将数据库的数据初始化到list里面
initFirstDataToBean();
}
@Override
public int getCount() {
return books.size();
}
@Override
public Object getItem(int position) {
return books.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertview, ViewGroup arg2) {
View view = null;
ViewHolder holder = null;
if (convertview == null || convertview.getTag() == null) {
view = infater.inflate(R.layout.library_list, null);
holder = new ViewHolder(view);
holder.setListern(position);
view.setTag(holder);
setParams(holder, view);
} else {
view = convertview;
holder = (ViewHolder) convertview.getTag();
}
Book book = (Book) getItem(position);
setCoverPic(position, holder);
holder.progressBar.setProgress(book.getProgress());
setDownloadIcon(holder, book);
holder.bookName.setText(book.getBname());
return view;
}
private OnContentListener mOnContentListener = new OnContentListener() {
@Override
public void onChange(List<DownloadInfoBean> listDownloadInfoBean) {
scanDownloadInfoBean(listDownloadInfoBean, false);
handler.sendEmptyMessage(QUERY_DOWNLOAD_PROGRESS);
}
};
/**
* 接口
*/
private OnUnZipCompleteListener mOnUnZipCompleteListener = new OnUnZipCompleteListener() {
@Override
public void onSuccess(boolean isComplete, String path) {
Message msg = new Message();
msg.what = QUERY_DOWNLOAD_UNZIP;
msg.obj = path;
handler.sendMessage(msg);
}
};
private void setParams(ViewHolder holder, View view) {
LayoutParams bookImg = (LayoutParams) holder.bookCoverPic
.getLayoutParams();
LayoutParams bookName = (LayoutParams) holder.bookName
.getLayoutParams();
LayoutParams progressBar = (LayoutParams) holder.progressBar
.getLayoutParams();
LayoutParams bookDownloadBn = (LayoutParams) holder.bookDownloadBn
.getLayoutParams();
LayoutParams bookDelBn = (LayoutParams) holder.bookDelBn
.getLayoutParams();
LayoutParams space = (LayoutParams) holder.space.getLayoutParams();
int width;
DisplayMetrics dm = view.getResources().getDisplayMetrics();
width = dm.widthPixels / 4;
bookImg.width = width;
progressBar.width = width * 9 / 10;
bookDownloadBn.width = width / 2;
bookDownloadBn.height = bookDownloadBn.width;
bookImg.height = 4 * bookImg.width / 3;
bookName.width = width;
bookDelBn.width = width / 5;
bookDelBn.height = bookDelBn.width;
space.height = bookImg.height / 9;
holder.bookCoverPic.setLayoutParams(bookImg);
holder.bookName.setLayoutParams(bookName);
holder.progressBar.setLayoutParams(progressBar);
holder.bookDownloadBn.setLayoutParams(bookDownloadBn);
holder.bookDelBn.setLayoutParams(bookDelBn);
holder.space.setLayoutParams(space);
}
/**
* 扫描本地下载数据库 初始化数据
*
* @param listDownloadInfoBean
* @param isFirstInit
*/
private void scanDownloadInfoBean(
List<DownloadInfoBean> listDownloadInfoBean, boolean isFirstInit) {
String url;
int status;
long total_size;
long current_size;
int progress;
// int[] deleteArrary = new int[50];
String delString = "-1";
for (DownloadInfoBean downloadInfoBean : listDownloadInfoBean) {
url = downloadInfoBean.getDownload_uri();
status = downloadInfoBean.getDownload_status();
total_size = downloadInfoBean.getDownload_total_bytes();
current_size = downloadInfoBean.getDownload_current_bytes();
progress = getProgressValue(total_size, current_size);
// 根据url 或者 downloadid 对比
if (books != null && books.size() > 0) {
for (int i = 0; i < books.size(); i++) {
Book book = books.get(i);
if (book != null) {
if (url.equals(CommConst.SIT_ROOT_FILE_URL_OSS
+ book.getBfname())) {
book.setDownloadId(downloadInfoBean
.getDownload_id());
book.setProgress(progress);
/**
* 当book的状态为下载后的状态 就不需要改变他 isFirstInit 是第一次进入 初始化
*/
if (book.getStatus() != CommConst.STATUS_READ_BOOK
&& book.getStatus() != CommConst.STATUS_READY) {
if (status == CommConst.STATUS_READY) {
book.setProgress(100);
book.setStatus(status);
if (isFirstInit) {
// 第一次查询为 100 时候
/**
* 第一次进入判断是否是解压完毕 如果没有解压完毕 在解压一次
*/
// 如果存在解压的文件夹 不存在解压的文件包 则解压成功
String pacpath = CommConst.ROOT_BOOK_PATH
+ book.getBname() + ".zip";
String dirpath = CommConst.ROOT_BOOK_PATH
+ book.getBid();
// 存在解压的文件包 重新解压 解压不完全 如果正在解压
// 则不会重新创建解压线程
if (!mFileUtils.isExsitDir(pacpath)) {
if (mFileUtils.isExsitDir(dirpath)) {
// BookDas.updateBookDownState(book.getBid(),1);
book.setStatus(CommConst.STATUS_READ_BOOK);
book.setDownloaded(CommConst.FLAG_DOWNLOAD_UNZIPED);
} else {
// 既没有文件夹 也没有压缩包就要自动删除所有信息
String bookPath = Environment
.getExternalStorageDirectory()
+ CommConst.ROOT_BOOK_PATH
+ book.getBid()
+ "/book";
manager.deleteDatabaseAndLocalFile(
url,
CommConst.PACKAGE_NAME);
// 先删除数据库中的数据记录,再删除SD卡中本地文件
mFileUtils.delFolder(bookPath);
try {
String sql = "update lw_book set downloaded = 0 where bid = ?";
App.getDbUtil().cud(sql,
book.getBid());
} catch (IwitApiException e) {
e.printStackTrace();
}
/*
* try {
* //WriteDas.deleteLession
* (book.getBid()); } catch
* (IwitApiException e) { //
* TODO Auto-generated catch
* block e.printStackTrace(); }
*/
book.setStatus(0);
book.setDownloaded(0);
// 如果是本地就删除数据
if (nativeOrLoad == 1) {
// 再外面去删除 先记录
delString = delString + ","
+ i;
}
}
} else {
// 解压开始
book.setStatus(CommConst.STATUS_UNZIPING);
mFileManager.unZipFile(
book.getBname() + ".zip",
CommConst.ROOT_BOOK_PATH,
CommConst.ROOT_BOOK_PATH
+ book.getBid()
+ "/",
mOnUnZipCompleteListener);
}
} else {
// 解压开始
book.setStatus(CommConst.STATUS_UNZIPING);
mFileManager.unZipFile(
book.getBname() + ".zip",
CommConst.ROOT_BOOK_PATH,
CommConst.ROOT_BOOK_PATH
+ book.getBid() + "/",
mOnUnZipCompleteListener);
}
} else {
book.setStatus(downloadInfoBean
.getDownload_status());
}
}
}
}
}
}
}
if (!delString.equals("-1")) {
Message msg = new Message();
msg.what = DELETE_BOOK;
msg.obj = delString;
handler.sendMessage(msg);
}
}
public void unregisterContentObserver() {
App.ctx.getContentResolver().unregisterContentObserver(
mMyContentObserver);
}
public int getProgressValue(long total_size, long current_size) {
int progress = 0;
progress = (int) (100 * current_size / total_size);
return progress;
}
public void initFirstDataToBean() {
List<DownloadInfoBean> listDownloadInfoBean = manager
.queryDownloadInfoByPackageName(CommConst.PACKAGE_NAME);
scanDownloadInfoBean(listDownloadInfoBean, true);
handler.sendEmptyMessage(QUERY_DOWNLOAD_PROGRESS);
}
@SuppressLint("HandlerLeak")
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case QUERY_DOWNLOAD_PROGRESS:
notifyDataSetChanged();
break;
case QUERY_DOWNLOAD_UNZIP:
String path = (String) msg.obj;
if (books != null) {
for (Book book : books) {
// 当url 一致的时候
if ((CommConst.ROOT_BOOK_PATH + book.getBname() + ".zip")
.equals(path)) {
book.setStatus(CommConst.STATUS_READ_BOOK);
BookDas.updateBookDownState(book.getBid(), 1);
book.setDownloaded(CommConst.FLAG_DOWNLOAD_UNZIPED);
book.setProgress(100);
Logger.e(T, "解压完:" + book.getStatus());
}
}
}
notifyDataSetChanged();
break;
case DELETE_BOOK:
String delString = (String) msg.obj;
String[] delArray = delString.split(",");
for (int i = 0; i < delArray.length; i++) {
if (!delArray[i].equals("-1")) {
books.remove(Integer.parseInt(delArray[i]));
}
}
notifyDataSetChanged();
break;
}
}
};
private void setCoverPic(int post, ViewHolder vHolder) {
if (!books.isEmpty() && books.get(post) != null) {
String path = CommConst.SIT_ROOT_FILE_URL
+ (String) books.get(post).getCoverpic();
// vHolder.bookCoverPic.setBackgroundResource(R.drawable.write_cover_defalt);
vHolder.bookCoverPic.setTag(path);
if (mDownloader == null) {
mDownloader = new AsyncImageDownloader(App.ctx);
}
mDownloader.imageDownload(path, vHolder.bookCoverPic,
CommConst.ROOT_PIC_PATH, new OnImageDownload() {
@Override
public void onDownloadSucc(Bitmap bitmap1,
String c_url, ImageView imageView) {
if (bitmap1 != null && !bitmap1.isRecycled()) {
if (mGridView1 != null) {
ImageView Image = (ImageView) mGridView1
.findViewWithTag(c_url);
if (Image != null && bitmap1 != null) {
Image.setImageBitmap(bitmap1);
Image.setTag("");
}
}
}
}
});
}
}
private void setDownloadIcon(ViewHolder holder, Book book) {
int status = book.getStatus();
// Logger.e(T, "bookstatus:" + status);
switch (status) {
case CommConst.FLAG_DOWNLOAD_NOT_BEGIN:// 未下载
holder.bookDownloadBn
.setBackgroundResource(R.drawable.library_bn_download);
holder.progressBar.setVisibility(View.INVISIBLE);
break;
case CommConst.STATUS_DOWNLOADING://
holder.bookDownloadBn
.setBackgroundResource(R.drawable.library_bn_pause);
holder.progressBar.setVisibility(View.VISIBLE);
break;
case CommConst.STATUS_PAUSE:
holder.bookDownloadBn
.setBackgroundResource(R.drawable.library_bn_wait);
break;
case CommConst.STATUS_READ_BOOK:
holder.proDialog.setVisibility(View.GONE);
holder.bookDownloadBn.setVisibility(View.VISIBLE);
holder.bookDownloadBn
.setBackgroundResource(R.drawable.library_bn_read);
holder.progressBar.setVisibility(View.INVISIBLE);
break;
case CommConst.STATUS_MOUNT_BEGIN:
holder.bookDownloadBn
.setBackgroundResource(R.drawable.library_bn_wait);
break;
case CommConst.STATUS_MOUNT_END:
holder.bookDownloadBn
.setBackgroundResource(R.drawable.library_bn_wait);
case CommConst.STATUS_UNZIPING:
holder.bookDownloadBn.setVisibility(View.INVISIBLE);
holder.proDialog.setVisibility(View.VISIBLE);
}
if (delFlag) {
holder.bookDelBn.setVisibility(View.VISIBLE);
} else {
holder.bookDelBn.setVisibility(View.INVISIBLE);
}
notifyDataSetChanged();
}
private class ViewHolder {
ImageView bookCoverPic, bookDownloadBn, bookDelBn;
TextView bookName;
ProgressBar progressBar;
ProgressBar proDialog;
View space;
private ViewHolder(View view) {
this.bookCoverPic = (ImageView) view.findViewById(R.id.book_img);
this.bookName = (TextView) view.findViewById(R.id.book_name);
this.bookDownloadBn = (ImageView) view
.findViewById(R.id.book_download);
this.progressBar = (ProgressBar) view
.findViewById(R.id.progressbar_download);
this.proDialog = (ProgressBar) view.findViewById(R.id.roundbar);
this.bookDelBn = (ImageView) view.findViewById(R.id.book_del);
this.space = (View) view.findViewById(R.id.space);
}
private void setListern(final int position) {
final Book mBook = books.get(position);
bookDownloadBn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mBook != null) {
if (NetWorkTools.getAPNType(mContext) == -1) {
Toast.makeText(mContext,
mContext.getString(R.string.write_no_net),
1).show();
switch (mBook.getStatus()) {
case CommConst.STATUS_READ_BOOK:
bookRead(mBook);
break;
}
} else {
switch (mBook.getStatus()) {
case CommConst.STATUS_NO_DOWNLOAD:
int count = manager
.getDownloadingCount(CommConst.PACKAGE_NAME);
String url = CommConst.SIT_ROOT_FILE_URL_OSS
+ mBook.getBfname();
// url:请求网络书籍地址
if (mBook.getDownloadId() == 0) {
// 下载的时候查看空间是否不足 如果不足提示下载失败
if (count <= 3) {
// if(WriteUtil.getPercentAvailableBlock()
// <= 0.2){
// Toast.makeText(mContext,
// "内存空间不足,请清理内存", 1).show();
// }else{
mBook.setStatus(CommConst.STATUS_DOWNLOADING);
manager.startDownload(url,
mBook.getBname() + ".zip",
CommConst.ROOT_BOOK_PATH);
// }
} else {
Toast.makeText(
mContext,
mContext.getString(R.string.write_download_too_much),
1).show();
}
} else {
manager.resumeDownload(mBook
.getDownloadId());
}
break;
case CommConst.STATUS_DOWNLOADING:
manager.pauseDownload(mBook.getDownloadId());
break;
case CommConst.STATUS_PAUSE:
manager.resumeDownload(mBook.getDownloadId());
break;
case CommConst.STATUS_READ_BOOK:
bookRead(mBook);
break;
}
}
}
}
});
bookDelBn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (bookDelBn.getVisibility() == View.VISIBLE) {
String bookPath = Environment
.getExternalStorageDirectory()
+ CommConst.ROOT_BOOK_PATH
+ books.get(position).getBid() + "/book";
books.get(position).setStatus(
CommConst.FLAG_DOWNLOAD_NOT_BEGIN);
String del_uri = CommConst.SIT_ROOT_FILE_URL_OSS
+ books.get(position).getBfname();
manager.deleteDatabaseAndLocalFile(del_uri,
CommConst.PACKAGE_NAME);
mFileUtils.delFolder(bookPath);
clickDelkBook(position);
}
}
});
}
}
private void bookRead(Book book) {
//音乐暂停
MusicManager mMusicManager = MusicManager.getInstance(mContext);
if (App.mMusicItemList != null && !App.mMusicItemList.isEmpty()) {
mMusicManager.pauseMusic();
}
String mBookPath = Environment.getExternalStorageDirectory()
+ CommConst.ROOT_BOOK_PATH + book.getBid() + "/book";
String readpath = CommConst.ROOT_BOOK_PATH + book.getBid() + "/book";
if (mFileUtils.isExsitDir(readpath)) {
MoueeReader.show(mContext, mBookPath);
} else {
Toast.makeText(mContext, "这本书不存在,请删除书本后重新下载.", 1).show();
}
}
public void setDelFlag(boolean b) {
delFlag = b;
this.notifyDataSetChanged();
}
private void clickDelkBook(int post) {
if (delFlag) {
try {
App.getDbUtil().cud(
"update lw_book set downloaded = 0 where bid = ?",
new Object[] { books.get(post).getBid() });
} catch (IwitApiException e) {
e.printStackTrace();
}
books.remove(post);
}
this.notifyDataSetChanged();
}
}
library_list.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:background="@drawable/bg_item_music_nomal"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/book_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitCenter" />
<ProgressBar
android:id="@+id/progressbar_download"
style="@style/progressBarLibrary"
android:layout_width="match_parent"
android:layout_height="10dp"
android:layout_below="@+id/book_img"
android:layout_centerHorizontal="true"
android:layout_marginTop="6dp"
android:max="100" />
<TextView
android:id="@+id/book_name"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_below="@+id/progressbar_download"
android:gravity="center_horizontal" />
<View
android:id="@+id/space"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/book_name" />
<ImageView
android:id="@+id/book_download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/book_img"
android:layout_alignLeft="@+id/book_img"
android:background="@drawable/library_bn_download" />
<ProgressBar
android:id="@+id/roundbar"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" >
</ProgressBar>
<ImageView
android:id="@+id/book_del"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/book_img"
android:layout_alignTop="@+id/book_img"
android:src="@drawable/library_bn_del" />
</RelativeLayout>