2011-08-31 58 views
0

我對Android(和移動)編程非常新穎。 我試圖通過每分鐘設置一個GPS位置來測試我的應用程序。 嘗試這樣做,使用ScheduledExecutorService的在android中設置測試任務的位置

所以這是我運行的類:

public class LocationTestScheduledTask implements Runnable {  
    private Activity activity;  
    public LocationTestScheduledTask(Activity a) 
    { 
     activity = a; 
    }  
    @Override 
    public void run() { 
     LocationManager locationManager = 
      (LocationManager)activity.getSystemService(Context.LOCATION_SERVICE); 
     locationManager.addTestProvider("Test", false, false, false, false, false, false, false, Criteria.POWER_LOW, Criteria.ACCURACY_FINE); 
     locationManager.setTestProviderEnabled("Test", true); 

     // Set up your test 

     Location location = new Location("Test"); 
     Random rand = new Random(); 

     location.setLatitude(rand.nextDouble()); 
     location.setLongitude(rand.nextDouble()); 
     locationManager.setTestProviderLocation("Test", location); 

     // Check if your listener reacted the right way 

     locationManager.removeTestProvider("Test");   
    }  
} 

在我這是怎麼調用任務從我activity.onCreate():

final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); 
final Runnable locationTest = new LocationTestScheduledTask(this); 
final ScheduledFuture sched= 
     scheduler.scheduleAtFixedRate(locationTest , 10, 10, TimeUnit.SECONDS); 

我我可能在這裏做了非常錯誤的事情,因爲我沒有看到任何位置變化。

我也試着做一些與TimerTask非常相似的東西,但沒有結果。

任何人都可以指向我的代碼是什麼問題?

回答

1

您可以使用處理程序。我會說這會使事情更容易:

Handler handler = new Handler(); 
Runnable locationTest = new LocationTestScheduledTask(this); 

handler.postDelayed(locationTest, 1000*60); // 1000 miliseconds * 60 miliseconds = 1 minute 

你會把handler.postDelayed(...)在你的onCreate以及在你的類的身體,如果你想改變位置的每一分鐘。

您可以做的更容易的事情是在模擬器上運行您的應用程序,然後轉到Eclipse中的DDMS,然後您可以發送設備gps緯度和經度座標。

您可以看到發送座標個圖像下面:

enter image description here

+0

感謝您的回答! postDelayed()已經完美地用於調度任務,但是我的setTestProviderLocation有一些問題。我在這裏找到了解決方案 - http://groups.google.com/group/android-developers/browse_thread/thread/07e56400d349817b?pli=1,現在它工作! – Ginandi