2016-09-05 6 views
0

まず、これはサイト上の他の質問と重複していません。私はServiceとGoogle APIの両方を使って位置更新を見た。GoogleロケーションサービスAPIを使用してバックグラウンドでも位置情報を取得するにはどうすればよいですか?

私は両方を試してみたが、サービスの場合には、それが機能していません。しかし、第1リンクのコードは完全に正常に動作しており、位置の更新が正しく行われます。しかし、私はそれがアプリがバックグラウンドにあるときに更新を得ることはできないと思う。

私のアプリケーションがバックグラウンドであっても継続的に位置更新を得ることができるサービス内にそのコードを入れたいです。

しかし、この2つのコードをマージする方法を理解できません。もしあなたが私が何を試してみるのですか?私はサービスクラスの一般的なメソッドをコピーしているだけです。 。。!

サービス:この私がAndroidに新たなんだ、私を提案してください事前に

おかげ

答えて

0

試しのために利用可能な代替がある場合でも、それは私にエラーが多すぎる:(

を与えます.java

import android.app.Service; 
import android.content.Context; 
import android.content.Intent; 
import android.location.Location; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.support.annotation.Nullable; 
import android.util.Log; 
import android.widget.Toast; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.location.LocationListener; 
import com.google.android.gms.location.LocationRequest; 
import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.location.LocationServices; 


import java.io.IOException; 
import java.io.OutputStreamWriter; 

public class GPSService extends Service implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,LocationListener { 



private GoogleApiClient mGoogleApiClient; 

private LocationRequest mLocationRequest; 

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


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

    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addApi(LocationServices.API) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .build(); 

} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 

    mGoogleApiClient.connect(); 

    return super.onStartCommand(intent, flags, startId); 
} 

@Override 
public void onDestroy() { 


    mGoogleApiClient.disconnect(); 
    super.onDestroy(); 



} 


@Override 
public void onConnected(Bundle bundle) { 
    mLocationRequest = LocationRequest.create(); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    mLocationRequest.setInterval(1000); // Update location every second 

    LocationServices.FusedLocationApi.requestLocationUpdates(
      mGoogleApiClient, mLocationRequest, this); 
} 

@Override 
public void onConnectionSuspended(int i) { 
    Toast.makeText(this,"GoogleApiClient connection has been suspend",Toast.LENGTH_LONG).show(); 
} 

@Override 
public void onConnectionFailed(ConnectionResult connectionResult) { 
    Toast.makeText(this,"GoogleApiClient connection has failed",Toast.LENGTH_LONG).show(); 
} 

とMainActivity.java

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Intent i = new Intent(this,GPSService.class); 
    startService(i); 


}