有個需求需要無界面的情況下持續獲取手機gps資訊進行定位,同時將資訊發送到服務器。
于是采用了通過啟動service后臺運行的方式,但發現后臺監聽定位時只能獲取第一次的定位資料(LocationListener的 onLocationChanged方法),然后就再也沒有新的資料。確定不是service死了,因為另一個發訊息的執行緒發出的資訊服務端仍然能夠收到。
同樣的代碼如果是在activity中運行就沒有問題,可以持續獲取定位。
手機android的版本是9和10。
在網上查了很多方案均無法解決,代碼是肯定沒有問題的,已經過很多驗證。放到service后臺gps資料就無法獲取,而發送其它資料就沒問題。我現在懷疑是不是高版本android為了防止惡意app,刻意限制了后臺service方法獲取gps定位。而必須在有界面的情況下才允許持續獲取gps定位。
有此方面經驗的同學么,如果確實有此限制,那這個需求就只能作罷了。
uj5u.com熱心網友回復:
Service的代碼大致如下
package com.example.LocationGPS;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import com.example.Utils;
import com.sjzy.androidlib.util.http.HttpUtil;
public class LocationService extends Service {
private LocationUtil locationUtil = null;
@Override
public void onCreate() {
super.onCreate();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
/**
* 啟動gps定位監聽,這里封裝了代碼,實際使用的如下代碼
* LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
* locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 3, locationListener);
*/
locationUtil = new LocationUtil(LocationService.this, locationListener, LocationManager.GPS_PROVIDER);
locationUtil.startLocation();
return super.onStartCommand(intent,flags,startId);
}
/**
* 定位監聽器
*/
private LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
String data = latitude + " " + longitude;
//發送資料到服務器
HttpUtil.post(Utils.uploadLocation, String.class, data, HttpUtil.DefaultEncode, Utils.getAuthParam());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) {}
};
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/284093.html
標籤:Android
