**ReadData.java**
package com.example.acer.readdata;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Message;
import android.util.Log;
/**
* Created by acer on 2015/11/11.
*/
public class ReadData extends BroadcastReceiver {
MainActivity execactivity;
private static final String TAG = "UsbStateReceiver";
public static final int USB_STATE_MSG = 0x00020;
public static final int USB_STATE_ON = 0x00021;
public static final int USB_STATE_OFF = 0x00022;
public IntentFilter filter = new IntentFilter();
public ReadData(Context context) {
execactivity = (MainActivity) context;
filter.addAction(Intent.ACTION_MEDIA_MOUNTED); //表示SD卡已挂载
filter.addAction(Intent.ACTION_MEDIA_CHECKING);//表示正在检测SD卡
filter.addAction(Intent.ACTION_MEDIA_EJECT);//表示用户欲卸载SD卡,但是SD卡上的部分内容尚处于打开状态
filter.addAction(Intent.ACTION_MEDIA_REMOVED);//表示SD卡已经被移除
filter.addDataScheme("file");//必须要有此行,否则无法接收到广播
Log.v("msg","filter");
}
//登记接收器
public Intent registerReceiver(){
return execactivity.registerReceiver(this,filter);
}
//关闭接收器
public void unregisterReceiver(){
execactivity.unregisterReceiver(this);
}
@Override
public void onReceive(Context context, Intent intent) {
if(execactivity.mHandler == null){
Log.v("msg","null");
return;
}
Message msg = new Message();
msg.what = USB_STATE_MSG;
if( intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED )/* || intent.getAction().equals(Intent.ACTION_MEDIA_CHECKING)*/){
msg.what = USB_STATE_ON;
Log.v("msg","msg.arg1 = USB_STATE_ON");
execactivity.mHandler.sendMessage(msg);
}else{
msg.what = USB_STATE_OFF;
Log.v("msg","msg.arg1 = USB_STATE_OFF");
execactivity.mHandler.sendMessage(msg);
}
Log.v("msg", "sendMessage");
}
}
**MyDatabastHelper.java**
package com.example.acer.readdata;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by acer on 2015/11/16.
*/
public class MyDatabaseHelper extends SQLiteOpenHelper {
/*
*catalog_table 分类表
* type 所属应用 0属于绘本 1属于视频 2属于游戏
* name 名称
* icon 图标
* index 放置的顺序序号 最小的放在最前面
*/
public static final String catalog_table = "create table catalog("
+ "id integer primary key autoincrement,"
+ "type integer"
+ "name text"
+ "icon text"
+ "index integer)";
/*
*book_table 内容表
* parentid 0属于绘本 1属于视频 2属于游戏
* catalogid 分类id
* type Book类别 按照类别,来打开这本书,可能是视频,可能是绘本的zip,也可能是apk
* name 名称
* icon 图标
* url 书的路径 (书或者是个apk)
* index 显示的序号
* readcount 阅读的次数
* pos 上次阅读的位置 (百分比表示 20表示为阅读到20%)
* readtume 最近一次阅读时间
* reverse1 0是竖版,1是横版
*reverse2 扩展为书的别名(例如 猴子捞月亮,别名:hzlyl)
*/
public static final String book_table = "create table book("
+ "id integer primary key autoincrement,"
+ "parentid integer"
+ "catalogid integer"
+ "type integer"
+ "name text"
+ "icon text"
+ "url text"
+ "index integer"
+ "readcount integer"
+ "pos integer"
+ "readtime integer"
+ "reverse1 integer"
+ "reverse2 integer)";
public MyDatabaseHelper(Context context,String name,SQLiteDatabase.CursorFactory factory,int version){
super(context,name,factory,version);
Log.v("SQL", " MyDatabaseHelper");
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(catalog_table);
db.execSQL(book_table);
Log.v("SQL", "onCreate");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists book_table");
db.execSQL("drop table if exists catalog_table");
Log.v("SQL","onUpgrade");
onCreate(db);
}
}
**MainActivity.java**
package com.example.acer.readdata;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Scanner;
import java.util.logging.LogRecord;
import static android.widget.Toast.*;
//采用广播方式监听U盘插拔的信息
public class MainActivity extends Activity {
MyHandler mHandler;
MyThread thread;
ProgressDialog progressDialog;
private ReadData usbstates;
private MyDatabaseHelper dbHelper;
private int i = 2;
private int type;
private int csvline = 2; //csv内有多少行记录
private int nShowProgress = 0x1000; //显示进度条
private int nHideProgress = 0x1001; //隐藏进度条
private int nStepProgress = 0x1002; //更新进度条
private int nMutiProgress = 0x1003; //更新进度条
private int toast = 0x1004;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
// 让数据库更新执行(未用)
dbHelper = new MyDatabaseHelper(this, "book.db", null, 5);
Log.v("msg2", "dbHelper");
mHandler = new MyHandler();
thread = new MyThread();
usbstates = new ReadData(this);
//进度条
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setIcon(R.mipmap.ic_launcher);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
protected void onStart() {
super.onStart();
usbstates.registerReceiver();
}
protected void onStop() {
super.onStop();
usbstates.unregisterReceiver();
}
class MyHandler extends Handler {
public MyHandler() {
}
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.v("msg", "ainactivity handler");
if (msg.what == 0x0021) {
Log.v("msg", "Main.SB_STATE_ON");
thread.start();
Log.v("msg", "Main.thread.start");
} else if (msg.what == 0x0022) {
Log.v("msg", "Main SB_STATE_OFF");
} else if (msg.what == 8888) {
useChoice();
Log.v("msg", "useChoice");
}
else if(msg.what == nShowProgress)
{
progressDialog.setTitle("更新数据中");
int nMaxProgress = msg.arg2;
Log.v("bar", "msg.what =" + nShowProgress + "msg.arg2 =" + nMaxProgress );
progressDialog.setMax(nMaxProgress);
progressDialog.show();
}
else if(msg.what == nHideProgress)
{
Log.v("bar", "msg.what =" + nShowProgress);
progressDialog.hide();
}
else if(msg.what == nStepProgress) {
int iStep = msg.arg2;
Log.v("bar", "msg.what =" + nShowProgress + "" + iStep);
progressDialog.setProgress(iStep);
}
else if(msg.what == nMutiProgress)
{
int nMax = msg.arg1;
int iStep = msg.arg2;
progressDialog.setMax(nMax);
Log.v("bar", "msg.what =" + nShowProgress + "" + iStep);
progressDialog.setProgress(iStep);
}
else if(msg.what == toast) {
Toast.makeText(MainActivity.this, "更新成功", Toast.LENGTH_SHORT).show();
Log.v("copy ","弹出更新成功");
}
}
}
//判断ini,发消息给主线程,让主线程弹出一个对话框,让用户选择是否更新数据
class MyThread extends Thread {
public MyThread() {}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
Log.v("msg1", "Main.MyThread");
//扫描U盘\HappyChildren_update下的update.ini文件,若文件内update=yes则提示用户是否更新数据
// 读取U盘指定目录下的文件
File file = new File("/storage/external_storage/sda1/HappyChildren_update/update.ini");
if (file == null) {
Log.v("msg1", "file is null");
} else
Log.v("msg1", "file is not null");
try {
Log.v("msg1", "try");
//判断文件内update是否等于YES
FileReader in = new FileReader(file);
Log.v("msg1", "in" + in);
char byt[] = new char[1024];
String substr = "update=YES";
int len = in.read(byt); //将字节读取数组
Log.v("msg1", "in.read:" + len);
String text = new String(byt, 0, len); //获取信息
Log.v("msg1", "text:" + text);
//如果为YES
if (text.equals(substr)) {
// if(true){
Log.v("msg", "eqyals");
//让用户选择是否更新数据
//发消息给主线程,让主线程弹出一个对话框
Message msg = new Message();
msg.what = 8888;
mHandler.sendMessage(msg);
Log.v("msg", "用户选择更新数据");
} else {
Log.v("msg", "else");
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//弹出对话框让用户选择
public void useChoice() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("更新数据");//窗口名
builder.setIcon(R.mipmap.ic_launcher); //添加一个小图片
builder.setMessage("是否更新数据?");
Log.v("msg2", "useChoice is use");
//用户选择确定
builder.setPositiveButton("更新", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//隐藏后选择窗口
dialog.dismiss();
Log.v("msg2", "useChoice is onClick yes");
//操作数据库和文件
dowithFile();
}
});
//若用户选择取消,则结束
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
//操作数据库和文件
private void dowithFile()
{
Thread th = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
File file = new File("/storage/external_storage/sda1/HappyChildren_update/update.csv");
//判断csv是否存在
if (file.exists()) {
Log.v("msg2", "useChoice is exosts");
// 存在则进行while循环
try {
Log.v("msg2", "useChoice is try");
BufferedReader reader = new BufferedReader(new FileReader("/storage/external_storage/sda1/HappyChildren_update/update.csv"));
reader.readLine();
String line = null;
Log.v("msg2", "useChoice is tryover");
//获取csv总行数
reader.mark((int) file.length() + 1); //在行首做个标记
while ((line = reader.readLine()) != null) {
csvline++;
Log.v("csv", "csvline: " + csvline);
}
//发消息给主线程,让主线程弹出一个对话框,显示操作数据库的进度条
Message msg = mHandler.obtainMessage();
msg.what = nShowProgress;
msg.arg2 = csvline;
mHandler.sendMessage(msg);
Log.v("copy", "显示进度条");
reader.reset(); //从mark那一行开始读
while ((line = reader.readLine()) != null) {
//打开数据库
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase("/storage/emulated/0/HappyChildren1/db/book.db", null);
//对csv中栏目进行判断
String sType = csv(i, 3);
Log.v("csv", "sType: " + sType);
if (sType.equals("绘本教学") == true) {
type = 0;
Log.v("type", "sType type = 0");
} else if (sType.equals("视频教学") == true) {
type = 1;
Log.v("type", "sType type = 1");
} else if (sType.equals("游戏娱乐") == true) {
type = 2;
Log.v("type", "sType type = 2");
}
//根据type和书分类去判断是否和catalog_table表中的type和name相同,若相同,返回id;若不存在则创建记录,并返回id
Cursor catalogtable = db.rawQuery("select * from catalog_table where type = ? and name like ?", new String[]{String.valueOf(type), csv(i, 4)});
int count = catalogtable.getCount();
Log.v("type", "catalogtable : " + count);
if (count == 0) {
//catalog_table不存在该条记录,插入读取到的数据
ContentValues values2 = new ContentValues();
Log.v("type", "values2: " + values2);
values2.put("type", type);
values2.put("name", csv(i, 4));
long catalogId = db.insert("catalog_table", null, values2);
//根据catalog_table表中返回的id和csv读取到的书的名称去判断book_table表中是否存在该记录,若存在,则update;若不存在,则insert记录
typeSort(catalogId, type);
} else {
//已经存在该记录,提取该记录的id
Cursor cursor = db.rawQuery("select * from catalog_table where type = ? and name = ?", new String[]{String.valueOf(type), csv(i, 4)});
cursor.moveToFirst();
int catalogId = cursor.getInt(cursor.getColumnIndex("_id"));
Log.v("type", "catalogId : " + catalogId);
//根据catalog_table表中返回的id和csv读取到的书的名称去判断book_table表中是否存在该记录,若存在,则update;若不存在,则insert记录
typeSort(catalogId, type);
}
++i;
//进度表
Message msg1 = mHandler.obtainMessage();
msg1.what = nStepProgress;
msg1.arg2 = i;
mHandler.sendMessage(msg1);
// Thread.sleep(500);
} //while循环结束
//copy文件夹
String oldPath = "/storage/external_storage/sda1/HappyChildren_update/books";
String newPath = "/storage/emulated/0/HappyChildren1/books";
Log.v("copy", "oldpath: " + oldPath + " newpath:" + newPath);
copyFolder(oldPath, newPath);
Log.v("copy", "copyFolder");
//隐藏进度表
Message msg3 = mHandler.obtainMessage();
msg3.what = nHideProgress;
mHandler.sendMessage(msg3);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
//如果文件不存在,则提示用户缺少csv文件,无法更新
Toast.makeText(MainActivity.this, "U盘缺少csv文件,无法更新", LENGTH_SHORT).show();
}
//将ini文件内的YES改为NO
iniFile();
//提示用户更新成功
Message msg1 = mHandler.obtainMessage();
msg1.what = toast;
mHandler.sendMessage(msg1);
Log.v("copy","提示用户更新完成");
}
});
th.start();
}
//操作book_table表内的记录,增加或修改
public void typeSort(long catalogId, int parentid) {
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase("/storage/emulated/0/HappyChildren1/db/book.db", null);
//根据catalog_table表中返回的id和csv读取到的书的名称去判断book_table表中是否存在该记录
Cursor booktable = db.rawQuery("select * from book_table where catalogid = ? and name like ?", new String[]{String.valueOf(catalogId), csv(i, 1)});
int count = booktable.getCount();
Log.v("type", "booktable : " + count);
if (count == 0) {
//创建记录
ContentValues values = new ContentValues();
values.put("name", csv(i, 1));
values.put("icon", csv(i, 6));
values.put("reverse1", csv(i, 8));
values.put("parentid", String.valueOf(parentid));
values.put("type", 0);
values.put("catalogid",String.valueOf(catalogId));
values.put("url", csv(i, 7));
db.insert("book_table", null, values);
} else {
//更新记录 update
ContentValues values3 = new ContentValues();
values3.put("url",csv(i,7));
db.update("book_table", values3, "name = ?", new String[]{csv(i, 1)});
}
}
//读取csv内数据
public String csv(int row, int col) {
String sRet = "";
Log.v("msg2", "Csv");
try {
Log.v("msg2", "CsvTry");
InputStream in = new FileInputStream(new File("/storage/external_storage/sda1/HappyChildren_update/update.csv"));
InputStreamReader input = new InputStreamReader(in, "gb2312");
// BufferedReader reader = new BufferedReader(new FileReader("/storage/external_storage/sda1/HappyChildren_update/update.csv"));
BufferedReader reader = new BufferedReader(input);
Log.v("msg2", "CsvReader");
// reader.readLine();//第一行信息,为标题信息,不用,如果需要,注释掉
String line = null;
int index = 0;
while ((line = reader.readLine()) != null) {
Log.v("msg2", "CsvWhile");
if (index == row - 1) {
String item[] = line.split(",");//CSV格式文件为逗号分隔符文件,这里根据逗号切分
Log.v("msg2", "CsvIf");
if (item.length >= col - 1) {
Log.v("msg2", "CsvIFif");
String last = item[col - 1];//所要数据
sRet = last;
Log.v("msg2", "last: " + last);
}
break;
}
//int value = Integer.parseInt(last);//如果是数值,可以转化为数值
index++;
Log.v("msg2", "index: " + index);
}
} catch (Exception e) {
e.printStackTrace();
Log.v("msg2", "exception");
}
Log.v("csv", "sRet = " + sRet);
return sRet;
}
//copy整个文件夹内容,oldPath 原文件路径 ,newPath 复制到的路径
public void copyFolder(String oldPath, String newPath) {
try {
(new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
// 获取源文件夹当前下的文件或目录
File f = new File(oldPath);
Log.v("copy", "f: " + f);
String[] file = f.list();
int nFile = (int) file.length;
//发送消息,弹出进度条
Message msg = mHandler.obtainMessage();
msg.what = nMutiProgress;
msg.arg1 = nFile;
msg.arg2 = 0;
mHandler.sendMessage(msg);
Log.v("copy", "显示进度条");
File temp = null;
for (int i = 0; i < file.length; i++) {
if (oldPath.endsWith(File.separator)) {
temp = new File(oldPath + file[i]);
Log.v("copy", "temp: " + temp);
} else {
temp = new File(oldPath + File.separator + file[i]);
Log.v("copy", "temp: " + temp);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()).toString());
byte[] b = new byte[1024 * 1024];
int len;
File newfile = new File(newPath);
while ((len = input.read(b)) != -1) {
Log.v("copy", "len:" + len);
output.write(b, 0, len);
Log.v("copy", "len: " + len);
//进度表
Message msg1 = mHandler.obtainMessage();
msg1.what = nMutiProgress;
msg1.arg1 = nFile;
msg1.arg2 = i+1;
mHandler.sendMessage(msg1);
Log.v("copy", "sendMessage(msg1)");
}
Log.v("copy", "while over");
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()) {//如果是子文件夹
copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
Log.v("copy", "子文件夹");
}
}
} catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
}
//将ini文件内的update=YES修改为update=NO;
public void iniFile() {
File file = new File("/storage/external_storage/sda1/HappyChildren_update/update.ini");
Log.v("msg2", "iniFile");
try {
FileInputStream in = new FileInputStream(file);
byte byt[] = new byte[1024];
int len = in.read(byt); //从文件中读取信息
Log.v("msg2", "len:" + len);
//创建FileOUtputStream对象
FileOutputStream out = new FileOutputStream(file);
//创建byte数组
byte by[] = "update=NO".getBytes();
out.write(by); //将数组信息写入到文件中
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
时间: 2024-10-12 07:43:06