class SyncWorker extends AsyncTask<Object, Object, Object> {
private static final Object LOCK = new Object();
private boolean woking;
private String[] mPath;
private IBookParser parser;
private Context mContext;
private IWorkerCallback mCallback;
private boolean failed;
private boolean insertOnly;
// private List<String> booksInserted;
private ContentResolver cr;
private static int taskCount;
private static Thread mThread;
static boolean glableWorking;
public boolean isWoking() {
return woking;
}
public SyncWorker(Context context, boolean doInsertOnly, String... path) {
ReadingWorker.getInstance();
mPath = path;
parser = BookParseManager.getInstance().getParser();
mContext = context;
insertOnly = doInsertOnly;
cr = context.getContentResolver();
}
@Override
protected Object doInBackground(Object... params) {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
synchronized (LOCK) {
taskCount++;
glableWorking = true;
if (mThread == null || !mThread.isAlive()) {
mThread = new Thread() {
@Override
public void run() {
while(glableWorking){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mContext.getContentResolver().notifyChange(EK1Uris.BOOK_CONTENT_URI, null);
}
Log.d("abc"," Refresh Thread end....");
}
};
mThread.start();
}
long time = System.currentTimeMillis();
woking = true;
// booksInserted = new ArrayList<String>();
try {
for (String path : mPath) {
Log.d("abc", "---load path--->" + path);
if (!insertOnly) {
if (path.equals(Fields.SD_BOOK_PATH)
|| path.startsWith(Fields.SD_BOOK_PATH + "/")) {
String sdid = Fields.sdcardID();
if (sdid != null) {
doInsertOrUpdate(path, sdid);
}
} else {
doInsertOrUpdate(path, null);
}
} else {
doInsert(new File(path));
}
}
mContext.getContentResolver()
.notifyChange(EK1Uris.BOOK_CONTENT_URI, null);
} catch (Throwable e) {
e.printStackTrace();
failed = true;
}
woking = false;
Log.d("abc", "--- all cost---"
+ (System.currentTimeMillis() - time) + "/nfailed?"
+ failed);
taskCount--;
if (taskCount == 0) {
glableWorking = false;
}
}
return null;
}
@Override
protected void onCancelled() {
super.onCancelled();
failed = true;
Log.d("abc", "cancel ? ->" + isCancelled());
}
@Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
mContext.getContentResolver().notifyChange(EK1Uris.BOOK_CONTENT_URI,
null);
if (mCallback != null) {
if (failed) {
mCallback.onTaskFailed();
} else {
mCallback.onTaskFinish();
}
}
//if (!failed && booksInserted != null && !booksInserted.isEmpty()) {
// Log.d("abc", "do update author and title to db...count -> "
// + booksInserted.size());
// String[] paths = new String[booksInserted.size()];
// booksInserted.toArray(paths);
// new ParseAdobeTask(paths, mContext).execute();
//}
}
}
其实AsyncTask 就和刚刚写的那个观察者一样,都是为了让程序能够异步运行---有之前和之后的操作,这个操作是在主线程中,而他的
doInBackground()方法是让里面的程序在背景线程中运行