[英]Location background Service using GoogleApiClient
我想每次檢查用戶的坐標(前景和背景),如果他接近某個地方,我會調用我的API並發送GCM。
所以我重新啟動設備后調用了BroadcastReceiver。
<receiver android:name=".LocationReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
這個接收器以這種方式調用服務:
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(),
LocationService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
此LocationService使用GoogleApiClient獲取位置並檢查與我的位置的距離。
public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
@Override
public void onCreate() {
super.onCreate();
mGoogleClient = new GoogleApiClient.Builder(this, this, this)
.addApi(LocationServices.API)
.build();
}
當我獲得一個新位置時,我使用這個新位置調用一個名為LocationHandler的IntentService
@Override
public void onConnected(Bundle bundle) {
LocationRequest locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
.setFastestInterval(5000L)
.setInterval(10000L)
.setSmallestDisplacement(75.0F);
PendingIntent pendingIntent = PendingIntent.getService(this, 0,
new Intent(this, LocationHandler.class),
PendingIntent.FLAG_UPDATE_CURRENT);
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleClient, locationRequest, pendingIntent);
}
此處理程序驗證距離並調用API
public class LocationHandler extends IntentService {
@Override
protected void onHandleIntent(Intent intent) {
final Location location = intent.getParcelableExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED);
if (location != null) {...
我想我錯過了一些東西,因為這個流程在重新啟動后被觸發但是......如何從我的應用程序的第一個活動中調用所有這些步驟?
我還有其他錯誤的做法嗎?
謝謝!
在第二個代碼塊中的onReceive()方法中,您調用了startWakefulService以使滾動滾動。 如果您希望從活動而不是系統觸發的意圖獲得相同的效果,只需以指向您的LocationService的相同方式調用startService()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.