AsyncTask 的用法

本文介绍了一个基于AsyncTask实现的同步工作类,该类用于在后台线程执行任务,并在主线程中更新UI。通过继承AsyncTask并重写其方法,可以实现异步加载数据的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()方法是让里面的程序在背景线程中运行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值