在Android的同步处理资料的任务 [英] Syncronizing tasks in Android
问题描述
在我的应用程序有多个地方的AsyncTask可以被调用来连接网页,下载的东西,等它可以从活动或后台服务。
In my application I have multiple places where AsyncTask can be invoked to connect to web, download stuff, etc. It can be from Activity or from background service.
有各种问题,因为我读取和写入SQLite数据库并在多个任务上类似的操作重叠(假设GetMail在后台运行,用户手动启动它)。
There is various issues because I'm reading and writing to SQLite database and when multiple tasks overlap on a similar operation (let's say GetMail runs on background and user started it manually).
我要syncronize类型的这一任务,并写道:code这样。我不知道如何测试它,它似乎是确定运行,但我希望得到你的意见,如果它是有效的。
I want to syncronize types of this tasks and wrote code like this. I'm not sure how to test it, it seems to be running OK but I wanted to get your opinion if it's valid..
public enum AsyncTasks
{
GetMail,
PostMail,
}
public class MyApplication extends Application
{
private final ArrayList<AsyncTasks> mLockedAsyncTasks = new ArrayList<AsyncTasks>();
public boolean lockAsyncTask(AsyncTasks task)
{
synchronized (mLockedAsyncTasks)
{
if (!mLockedAsyncTasks.contains(task))
{
mLockedAsyncTasks.add(task);
return true;
}
return false;
}
}
public void unlockAsyncTask(AsyncTasks task)
{
synchronized (mLockedAsyncTasks)
{
if (mLockedAsyncTasks.contains(task))
{
mLockedAsyncTasks.remove(task);
}
}
}
}
在这里的想法是,我打电话 lockAsyncTask
,如果成功 - 我着手进行HTTP的东西,否则跳过,因为它已经运行。
Idea here is that I'm calling lockAsyncTask
and if success - I proceed with HTTP stuff, otherwise skip since it's running already.
推荐答案
可能更容易只使用由单一工作线程支持的操作队列。这样的任务也将在他们收到的顺序运行。您可以轻松地使用 执行人做到这一点code>
工厂方法。这里有一个简单的例子:
It might be easier to just use an operation queue backed by a single worker thread. That way all tasks will be run in the order they are received. You can easily accomplish this by using the Executors
factory methods. Here's a simple example:
private static final ExecutorService mThreadPool =
Executors.newSingleThreadExecutor();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mThreadPool.execute(new Runnable() {
public void run() {
// Do some work here...
}
});
mThreadPool.execute(new Runnable() {
public void run() {
// Do some additional work here after
// the first Runnable has finished...
}
});
}
这篇关于在Android的同步处理资料的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!