Я пытаюсь создать приложение для геообстановки, но, похоже, только регистрирует геофорумы при запуске основного действия, а служба намерения перестает получать их, когда приложение закрыто. Таким образом, я переместил логику добавления geofence в службу намерения (вместе с кодом обработки намерений) и убедитесь, что сервис запущен, но теперь служба не получает никаких намерений вообще!Приложение для Android добавляет геообъекты и получает намерения в одном сервисе
Определение сервиса
public class GeofenceTransitionsIntentService extends IntentService implements ConnectionCallbacks, OnConnectionFailedListener, ResultCallback<Status>
Все в службе (апи клиент Google построен и подключен) осуществляется в onCreate
, как с намерением обработчиков и регистрации геозоны вещи onConnected
регистры Геозоны и т.д. В принципе, я ve попытался внедрить тяжелый заимствованный пример кода геофикации (из документов) в той же службе, которая предназначена для обработки этих намерений.
Все основные виды деятельности - это запуск службы и привлечение тех, которые связаны с уведомлениями о геозонности, полученными в сервисе.
Если вам нужна дополнительная информация, просто дайте мне знать.
редактировать
Ok, так что кажется, что нам нужно больше информации - план службы:
public class GeofenceTransitionsIntentService extends IntentService implements ConnectionCallbacks, OnConnectionFailedListener, ResultCallback<Status> {
protected static final String TAG = "GeofenceTransitionsIS";
protected GoogleApiClient mGoogleApiClient;
protected ArrayList<Geofence> mGeofenceList;
private boolean mGeofencesAdded;
private PendingIntent mGeofencePendingIntent;
private SharedPreferences mSharedPreferences;
public GeofenceTransitionsIntentService() {
super(TAG);
}
@Override
public void onCreate() {
super.onCreate();
buildGoogleApiClient();
populateGeofenceList();
mGoogleApiClient.connect();
}
...
@Override
protected void onHandleIntent(Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
// handle the intent, send a notification
}
private void sendNotification(String notificationDetails) {
// sends a notification
}
@Override
public void onConnected(Bundle connectionHint)
{
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
getGeofencingRequest(),
getGeofencePendingIntent()
).setResultCallback(this);
}
// straight out of the example
private GeofencingRequest getGeofencingRequest()
{
...
}
// from a branch of the example that reuses the pending intent
private PendingIntent getGeofencePendingIntent()
{
if (mGeofencePendingIntent != null)
{
return mGeofencePendingIntent;
}
Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
mGeofencePendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return mGeofencePendingIntent;
}
public void populateGeofenceList() {
for (thing place : listofplaces) {
mGeofenceList.add(...)
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public void onResult(Status status)
{
// were fences added? usually yes
}
}
Мое исследование было разочарование - я вижу людей, которые утверждают, что способны сделать что-то подобное из широковещательного приемника (см. первый комментарий), но не от службы?
У меня есть довольно искаженное manifest.xml от всех изменений я работаю через:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<service android:name=".GeofenceTransitionsIntentService"
android:exported="true"
android:enabled="true">
<intent-filter >
<action android:name="com.aol.android.geofence.ACTION_RECEIVE_GEOFENCE"/>
</intent-filter>
</service>
...
</application>
Ни добавления intent-filter
ни android:exported="true"
к определению службы помогло вообще.
Я не разработчик android dev * – opticaliqlusion
Возможно, этот вопрос может вам помочь. http://stackoverflow.com/questions/21090674/android-geofencing-no-coming-intents?rq=1 – TychoTheTaco
@TychoTheTaco благодарит за ответ, но он, похоже, не имеет никакого эффекта - добавлен «экспортирован», перестроен и перезапущен приложение + сервис, по-прежнему ничего. Больше раздражает, нет отладочной информации, чтобы предположить, почему она не может работать! – opticaliqlusion