我正在尝试编写一个简单的服务,每隔几秒就会做一些事情.但是当我在主Activity中尝试运行其他AsyncTasks时运行服务时,我注意到其他AsyncTasks卡在onPreExecute上.当我禁用该服务时,一切都按预期工作.服务的AsynTask阻塞其他AsyncTasks是否有原因?
服务
public class SVC_Syncdata extends Service { private final String TAG = "SVC_Syncdata"; private AT_Syncdata m_SyncPoll = null; public static boolean isRunning = false; public SVC_Syncdata() { } @OverrIDe public IBinder onBind(Intent intent) { return null; } @OverrIDe public voID onCreate() { super.onCreate(); Log.i(TAG, "onCreate"); m_SyncPoll = new AT_Syncdata(this); } @OverrIDe public int onStartCommand(Intent intent, int flags, int startID) { Log.i(TAG, "onStartCommand"); m_SyncPoll.execute(); isRunning = true; return START_STICKY; } @OverrIDe public voID onDestroy() { super.onDestroy(); Log.i(TAG, "onDestroy"); m_SyncPoll.cancel(false); isRunning = false; }}
AT_Syncdata的doInBackground
@OverrIDeprotected VoID doInBackground(VoID... params) { Log.i(TAG, "doInBackground"); try { while (!isCancelled()) { Log.i(TAG, "syncdata"); // Sleep until next cycle Thread.sleep(5000); } } catch (Exception ex) { ex.printstacktrace(); } return null;}
解决方法:
AsyncTask documentation声明:
Order of execution
When first introduced, AsyncTasks were executed serially on a single
background thread. Starting with DONUT, this was changed to a pool of
threads allowing multiple tasks to operate in parallel. Starting with
HONEYCOMB, tasks are executed on a single thread to avoID common
application errors caused by parallel execution.If you truly want parallel execution, you can invoke
executeOnExecutor(java.util.concurrent.Executor, Object[]) with
THREAD_POol_EXECUTOR.
因此,较新版本的androID会有你描述的这个问题.您需要使用executeOnExecutor来确保您在不同的线程上运行.
此外,如果您想要在单独的线程中运行服务,我建议:
>使用IntentService
>有时您会希望更多地控制服务的生命周期,而不是IntentService为您提供的服务,在这种情况下,您只需在服务中创建一个线程并在其中运行您的后台代码.实际上,更具体地说,创建一个包含Looper的HandlerThread,这样您就可以使用标准的androID方法在主线程和后台线程之间进行通信(消息).就个人而言,我通常会为我的服务选择此选项.
以上是内存溢出为你收集整理的java – 为什么我的服务的AsyncTask阻止来自主Activity的AsyncTasks?全部内容,希望文章能够帮你解决java – 为什么我的服务的AsyncTask阻止来自主Activity的AsyncTasks?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)