2016-09-22 28 views
0

我試圖從它自己的進程中運行的未綁定的服務日誌一體化位置更新到文件「:locationProcess」。Android的 - 登錄融合位置更新的文件在後臺服務

AndroidManifest.xm

<service 
    android:name=".LocationUpdate" 
    android:process=":locationProcess" 
    android:enabled="true" 
    android:exported="true" /> 

LocationUpdate.java

public class LocationUpdate extends Service implements GoogleApiClient.ConnectionCallbacks, 
    GoogleApiClient.OnConnectionFailedListener {... 

onBind設置爲返回null

@Override 
public IBinder onBind(Intent arg0) { 
    return null; 
} 

onStartC ommand返回START_STICKY。

我創建的文件中的谷歌播放服務onConnected在LocationUpdate服務回調方法...

@Override 
public void onConnected(Bundle arg0) { 

    try { 
     pwFile = new PrintStream(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "gps.csv")); 
     pwFile.println("date,latitude,longtitude,altitude,bearing,accuracy"); 
    } catch (IOException e) { 
     // TODO: Handle the exception 
    } 

    mLocationRequest = LocationRequest.create(); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 
    mLocationRequest.setInterval(10000); 
    mLocationRequest.setFastestInterval(5000); 
    startLocationUpates(); 
} 

,並從LocationListener的寫出來的onLocationChange回調的GPS細節...

@Override 
public void onLocationChanged(Location location) { 
    currentLat = location.getLatitude(); 
    currentLng = location.getLongitude(); 

    // Get current date time 
    Date newDate = new Date(System.currentTimeMillis()); 

    // Write lat and long out to a file 
    pwFile.println(newDate.toString() + "," + String.format("%.6f", currentLat) + "," + 
      String.format("%.6f", currentLng) + "," + String.format("%.4f", location.getAltitude()) + "," + 
      String.format("%.4f", location.getBearing()) + "," + String.format("%.4f", location.getAccuracy())); 
} 

我開始在我的應用程序類的OnCreate覆蓋服務...

public class App extends Application { 
    Intent LocationService; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 

     LocationService = new Intent(this, LocationUpdate.class); 
     startService(LocationService); 
    } 
} 

所有作品,應用<application>標籤機器人被宣佈:在的Manifest.xml的名字= 「mypackage.app」。

這是沒有我想的服務繼續登錄位置的文件,即使有在前臺另一個應用程序的一部分...

如果用戶故意關閉應用程序,它應該停止記錄。閱讀Android文檔後,我認爲我的代碼可以正常工作。

據我所知道的,服務也繼續運行時,應用程序是不是在前臺。如果用戶專門關閉了我不想要的應用程序,並且由於某種原因,我不明白服務本身正在被銷燬並在應用程序正在運行時重新創建,因此服務正在被重新調用所以日誌文件被有效覆蓋。

這是更多的一個架構問題,我猜。

基本上,我想我的位置服務,以可靠地記錄到文件中,而應用程序是不是在前臺啓動後,當應用程序是由用戶終止停止。

希望是有道理的。我看過很多Github上的示例,但他們只是在應用程序處於前臺時才記錄日誌。

任何幫助真的很感激,這一切都讓我有點瘋狂。

謝謝。

回答

0

您將服務作爲開始服務(而非意向服務)。然後在服務的onStartCommand上,返回START_STICKY。這將告訴操作系統,如果出於任何原因需要關閉服務,請在有足夠資源時再次運行該服務。在你的情況下,當用戶關閉活動/殺死應用程序時,服務進程將被終止,但通常會重新打開。