2012-05-12 33 views
0

我有一個BrodcastReceiver運行的服務,它運行並提供我請求的GPS數據,並且在我完成了想要完成的任務後停止了它,但是我注意到它並沒有提供我所需的數據,沒有停止過,任何機構可以幫助我找出我的問題 的代碼如下,服務在真實設備測試:服務不起作用?

import android.app.Service; 
import android.content.Context; 
import android.content.Intent; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.os.SystemClock; 
import android.widget.Toast; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 

public class GpsService extends Service implements LocationListener{ 
    static LocationManager mlocManager; 

    }  
    @Override 
    public IBinder onBind(Intent arg0) { 
     // TODO Auto-generated method stub 
     return null; 
    } 
    public void onCreate() { 

    } 

    @Override 
    public void onDestroy() { 

    } 

    @Override 
    public void onStart(Intent intent, int startid) { 
     mlocManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE); 
     mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0, 0,this); 

    } 

     @Override 
    public void onLocationChanged(Location loc) 
    { 
    loc.getLatitude(); 
    loc.getLongitude(); 
    String Text = "My current location is: " +"Latitud = " + loc.getLatitude() +"Longitud = " + loc.getLongitude(); 
    Toast.makeText(getApplicationContext(),Text,Toast.LENGTH_SHORT).show(); 
    // Here to stop the service and make it finish its task 
    SystemClock.sleep(40000); 
    // stop the Gps system by this application 
    mlocManager.removeUpdates(this); 
    //Here to stop the service by itself 
    stopSelf(); 

    } 
    @Override 
    public void onProviderDisabled(String provider) 
    { 
    Toast.makeText(getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public void onProviderEnabled(String provider) 
    { 
    Toast.makeText(getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show(); 
    } 
    @Override 

    public void onStatusChanged(String provider, int status, Bundle extras) 
    { 
    } 


} 
+0

Husam這不是使用SystemClock.sleep(40000)的好習慣; 等待。你會使用Timer來獲得更好的結果 –

回答

0
  1. 你對清單中的正確的權限?
  2. 你爲什麼要讓這項服務睡眠很久?該服務在UI線程上工作,並且這樣的事情會導致服務在大約5秒後被系統自動終止,因爲ui線程不響應。
  3. 如果您希望延遲停止和/或顯示敬酒,請使用Handler(和postDelayed),或使用asyncTask或您自己的東西。
  4. 你打開GPS嗎?你有沒有考慮使用假的位置應用程序或模擬器來完成這項任務?
  5. 祝你好運。