簡體   English   中英

背景中的連續位置更新

[英]Continuous location updates in background

我正在開發一個應用程序,它將從后台服務連續發送位置更新。 我試過以下代碼。

public class LocationService extends Service implements LocationListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
    LocationRequest mLocationRequest;
    LocationClient mLocationClient;
    @Override
     public void onCreate() {
     //creating log file in mobile
        appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Service created:", com.example.locationservice.Constants.LOG_FILE);

      mLocationRequest = LocationRequest.create();
      mLocationRequest.setInterval(5*1000);
      mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    //  mLocationRequest.setFastestInterval(5*1000);
      mLocationClient = new LocationClient(getApplicationContext(), this,this);
      mLocationClient.connect();

     }
    @Override
     public void onStart(Intent intent, int startId) {
      int start = Service.START_STICKY;
        appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Service Started:", com.example.locationservice.Constants.LOG_FILE);

     }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        // TODO Auto-generated method stub
        appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Connection to client failed", com.example.locationservice.Constants.LOG_FILE);
        this.stopSelf();

    }

    @Override
    public void onConnected(Bundle arg0) {
        // TODO Auto-generated method stub
        Log.i("info", "Location Client is Connected");
        appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Location Client Connectd:", com.example.locationservice.Constants.LOG_FILE);
        //checking for locaton enabled or not
        if(Util.isLocationEnabled(getApplicationContext())){
        //checking for internet available or not
            if(Util.isInternetOn(getApplicationContext())){
                mLocationClient.requestLocationUpdates(mLocationRequest, this);
            }else{
              Log.i("info", "Internet not available");
                appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Internet not available", com.example.locationservice.Constants.LOG_FILE);
                this.stopSelf();
            }
          }else{
            Log.i("info", "Location Acess disabled");
            appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Location Acess disabled", com.example.locationservice.Constants.LOG_FILE);
            this.stopSelf();
          }
          Log.i("info", "Service Connect status :: " + isServicesConnected());

    }

    @Override
    public void onDisconnected() {
        // TODO Auto-generated method stub
        appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Location Client DisConnectd:", com.example.locationservice.Constants.LOG_FILE);
        Log.i("info", "Location Client is DisConnected");

    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        double latitude = location.getLatitude();
          double longitude = location.getLongitude();
            appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Location Changed:", com.example.locationservice.Constants.LOG_FILE);
          Log.i("info", "Latitude :: " + latitude);
          Log.i("info", "Longitude :: " + longitude);
          if(Util.isInternetOn(getApplicationContext())){
          //sending location details
          sendLocation(location);
          }else{
              this.stopSelf();
              Log.i("info", "Internet not available");
                appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Internet not available", com.example.locationservice.Constants.LOG_FILE);
          }
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
     public void onDestroy() {
      // TODO Auto-generated method stub
      Log.i("info", "Service is destroyed");
      mLocationClient.removeLocationUpdates(this);  
        appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Service Destroyed:", com.example.locationservice.Constants.LOG_FILE);
      super.onDestroy();
     }
    private boolean isServicesConnected() {
          // Check that Google Play services is available
          int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(LocationService.this);
          // If Google Play services is available
          if (ConnectionResult.SUCCESS == resultCode) {           
           return true;
          } else {
           return false;
          }
         }
}

onLocationChanged僅在我打開內置地圖應用程序時調用。 另外,它不會更新位置詳細信息。 我從使用警報服務的活動開始這項服務。 alarmManager每隔一分鍾觸發一次。 任何人都可以告訴我為什么onLocationChanged不會連續調用。

提前致謝。

試試這個:

@Override
 public void onCreate() {
 //creating log file in mobile
    appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Service created:", com.example.locationservice.Constants.LOG_FILE);

  mLocationClient = new LocationClient(getApplicationContext(), this,this);
 }

將onStart替換為:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mLocationClient.connect();
}

和:

@Override
public void onConnected(Bundle arg0) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(5*1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}

調用您的服務:

startService(yourServiceIntent);

你也可以在這里查看我的代碼

它在后台工作正常嗎? 在后台運行45分鍾后服務不會停止? - Noman 2015年11月3日6:18

這是一個很好的評論。 在我的項目中,我有一些proglem在位置更新中持續不斷。 45分鍾后它真的停了下來。

我的服務是前台。 我用

StartForeground(ServicesId.Push,notification);

我每隔45分鍾就會喚醒位置更新

_timer = new Timer(); _timer.Schedule(新的TimerTaskTrek(this),45 * 60 * 1000 + 10 * 1000,45 * 60 * 1000 + 10 * 1000);

並在timerTask中

嘗試{

 Looper.Prepare(); 

} catch(例外e){

}

_client = new> GoogleApiClient.Builder(this).AddApi(LocationServices.API).AddConnectionCallbacks(this).AddOnConnectionFailedListener(this).Build();

_client.Connect();

它非常簡單,而且工作非常好。 請享用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM