2012-01-06 14 views
1

我有一個AsyncTask,它調用我的LocationHandler類方法getLocation(),它也運行Thread。我收到以下錯誤:調用一個包含AsyncTask線程的方法(不想調用Looper.prepare())

Can't create handler inside thread that has not called Looper.prepare() 

一些答案已包括調用Looper相關的方法,但我寧願沒有這樣做,因爲它是不好的做法

主要活動會調用的AsyncTask:

public class Main extends Activity {   
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.test); 

     StartProcess sProcess = new StartProcess(); 
     sProcess.execute(this); 
    } 
} 

的AsyncTask:

public class StartProcess extends AsyncTask<Main, Void, Void> 
{ 
    @Override 
    protected Void doInBackground(Main... params) { 
     LocationHandler lh = new LocationHandler(); 
     try { 
      lh.getLocation(null, params[0]); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 
} 

LocationHandler,似乎崩潰時,它調用requestLocationUpdates():

public class LocationHandler { 
    LocationManager mlocManager; 
    MyLocationListener mlocListener; 
    Location location; 

    public synchronized void getLocation(final View view, final Main main) throws InterruptedException 
    { 
     mlocManager = (LocationManager)main.getSystemService(Context.LOCATION_SERVICE); 
     mlocListener = new MyLocationListener(); 
      Looper.prepare(); 
     mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 1, mlocListener); 
     mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 1, mlocListener); 


     Thread uiThread = new HandlerThread("UIHandler"){ 
      public synchronized void run(){ 

       //stuff 
       } 

      } 

     }; 
     uiThread.start(); 

    } 

LocationListener的:

public class MyLocationListener implements LocationListener 
{ 
    @Override 
    public void onLocationChanged(Location loc) 
    { 

     location = new Location(loc); 

    } 

回答

0

我用@nininho建議,但我叫Looper.prepare()我在LocationHandler類稱爲requestLocationUpdates()之前之前調用Looper.prepare()。我在撥打Thread後不得不打電話Looper.loop(),否則Thread甚至不會運行。

1

我不知道如果我這樣做是正確的,但在我的功能之一,我只需添加這樣的: mHandler =新的Handler(Looper.getMainLooper()); ,它有幫助。

+0

我將如何將它集成到我的代碼? – Neeta 2012-01-06 13:04:55

+0

我真的不確定,也許試着用你的HandlerThread做些什麼? – goodm 2012-01-06 13:20:03

1

這是因爲HandlerThread的編譯器是抱怨,只是用HandlerThread

+0

這是正確的,但要確保只在該線程上調用一次Looper.prepare(),否則會出錯。 – Martyn 2012-01-06 12:58:09

+0

謝謝,我在'requestLocationUpdates()'之前調用了Looper.prepare()'(在其他任何地方都不工作),並且仍然不起作用,所以我在'uiThread.start()之後添加了'Looper.loop()' )',然後它開始工作。 – Neeta 2012-01-06 13:01:28

相關問題