位置情報アプリで作業しています。バックグラウンド サービスで位置情報が変更されたときに、fusedlocation プロバイダーからユーザーの位置情報を取得したいと考えています。
私のサービスは間隔ごとに位置情報を提供しますが、間隔ごとではなく場所が変更されたときに位置情報が必要です
私のサービスは再起動時に開始されました。私が設定した間隔ごとに位置を取得します。しかし、時間間隔ごとではなく、場所が変更されたとき(ユーザーが新しい場所に移動したとき)に場所が必要です。
public class BacLocSerUme extends Service implements ConnectionCallbacks,
OnConnectionFailedListener, LocationListener {
protected static final String TAG = "sanu location services";
// parameters for the GoogleApiClient Location Request
private static final long INTERVAL = 1000 * 60;
private static final long FASTEST_INTERVAL = 1000 * 5;
private static final long ONE_MIN = 1000 * 60;
private static final long REFRESH_TIME = ONE_MIN * 5;
private static final float MINIMUM_ACCURACY = 50.0f;
// in it for Api params
private LocationRequest locationRequest;
private GoogleApiClient googleApiClient;
private FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
private Location mlocation;
// Flag that indicates if a request is underway.
private boolean mInProgress;
private Boolean servicesAvailable = false;
IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
public BacLocSerUme getServerInstance() {
return BacLocSerUme.this;
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return mBinder;
}
// On create Method to init all the value of request of playservices
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.i(TAG, "on create of service");
mInProgress = false;
buildGoogleApiClient();
servicesAvailable = servicesConnected();
}
private Boolean servicesConnected() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
return true;
} else {
return false;
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.i(TAG, "on start of services");
super.onStartCommand(intent, flags, startId);
if (!servicesAvailable || googleApiClient.isConnected() || mInProgress)
return START_STICKY;
setUpLocationClientIfNeeded();
if (googleApiClient.isConnected() || !googleApiClient.isConnecting()
&& !mInProgress) {
Log.i(TAG, "Services Started from service class");
mInProgress = true;
googleApiClient.connect();
}
return START_STICKY;
}
private void setUpLocationClientIfNeeded() {
if (mlocation == null) {
buildGoogleApiClient();
}
}
// Building GoogleApiClient
private void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
createLocationRequest();
}
// Building Request for googleApiClient
private void createLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
Log.i(TAG, "location request created");
}
// This Followins two mathod is generated by implements of
// connectioncallback
// on connected and on connection suspend
// this is used for connection call back//// check connected or not
@Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "Connected to GoogleApiClient");
mlocation = fusedLocationProviderApi.getLastLocation(googleApiClient);
if (mlocation == null) {
fusedLocationProviderApi.requestLocationUpdates(googleApiClient,
locationRequest, this);
}
Intent intent = new Intent(this, LocationReceiver.class);
PendingIntent locationIntent = PendingIntent.getBroadcast(
getApplicationContext(), 14872, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
fusedLocationProviderApi.removeLocationUpdates(googleApiClient,
locationIntent);
}
@Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "Connection suspended");
googleApiClient.connect();
}
// generated from inplementation from OnConnectionFailedListener
@Override
public void onConnectionFailed(ConnectionResult result) {
mInProgress = false;
Log.i(TAG, "Location Services fails. ");
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
// method generated from requestlocation listener
@Override
public void onLocationChanged(Location location) {
mlocation = location;
Log.i(TAG, "Location Changed");
appendLog(DateFormat.getDateTimeInstance().format(new Date())
+ ": location changed" + mlocation.getLatitude(),
Constants.LOG_FILE);
Toast.makeText(this, "Locatiopn Changed", Toast.LENGTH_LONG).show();
}
// ondestroid method of services
@Override
public void onDestroy() {
// TODO Auto-generated method stub
mInProgress = false;
if (servicesAvailable && googleApiClient != null) {
fusedLocationProviderApi.removeLocationUpdates(googleApiClient,
this);
// Destroy the current location client
googleApiClient = null;
}
super.onDestroy();
}
// extra methods for utill
public String getTime() {
SimpleDateFormat mDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
return mDateFormat.format(new Date());
}
public void appendLog(String text, String filename) {
File logFile = new File(filename);
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
// BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile,
true));
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}// End of main services