从服务内部运行ASyncTask doInBackground()

时间:2014-01-16 22:50:18

标签: android android-asynctask android-service

我有一个服务,它调用LocationHelper来获取用户位置

LocationWorker locationTask = new LocationWorker();
locationTask .execute(new Boolean[] {true});

    class LocationWorker extends AsyncTask<Boolean, Integer, Boolean> {
        @Override
        protected void onPreExecute() {}    

        @Override
        protected void onPostExecute(Boolean result) {
            /* Here you can call myLocationHelper.getLat() and myLocationHelper.getLong() to get the location data.*/
            latitude= = myLocationHelper.getLat();
            longitude= = myLocationHelper.getLong();
=       }

        @Override
        protected Boolean doInBackground(Boolean... params) {
            //while the location helper has not got a lock
            while(myLocationHelper.gotLocation() == false){
                //do nothing, just wait
            }
            //once done return true
            return true;
        }
    }

这在Activity中运行良好,但我试图在A服务中运行相同的

* 我得到了这个错误和崩溃*

01-16 22:31:57.854: W/dalvikvm(23413): threadid=11: thread exiting with uncaught exception (group=0x41f42700)
01-16 22:31:57.869: E/AndroidRuntime(23413): FATAL EXCEPTION: AsyncTask #1
01-16 22:31:57.869: E/AndroidRuntime(23413): java.lang.RuntimeException: An error occured while executing doInBackground()
01-16 22:31:57.869: E/AndroidRuntime(23413):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-16 22:31:57.869: E/AndroidRuntime(23413):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
01-16 22:31:57.869: E/AndroidRuntime(23413):    at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
01-16 22:31:57.869: E/AndroidRuntime(23413):    at java.util.concurrent.FutureTask.run(FutureTask.java:239)
01-16 22:31:57.869: E/AndroidRuntime(23413):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-16 22:31:57.869: E/AndroidRuntime(23413):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-16 22:31:57.869: E/AndroidRuntime(23413):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-16 22:31:57.869: E/AndroidRuntime(23413):    at java.lang.Thread.run(Thread.java:841)
01-16 22:31:57.869: E/AndroidRuntime(23413): Caused by: java.lang.NullPointerException

谢谢

1 个答案:

答案 0 :(得分:4)

你在logcat中有它(你没有粘贴最有趣的部分):

  

引起:java.lang.NullPointerException

可能NPE原因会在它下面几行。

可能你的myLocationHelper是null,也记得总是从GUI线程执行asynctask。