4

지오 펜스로 안드로이드 튜토리얼을 사용했습니다. 지오 펜스는 앱이 닫힐 때 분명히 작동하지 않습니다. 그래서 주위를 검색 한 후, 나는 사용자 b-ryce가 BroadcastReceiver를 사용했음을 알았습니다. 따라서 앱이 활성 상태가 아니어도 지오 코딩이 트리거됩니다 (link for his SO question).지오 펜스가 발생하지 않음 (pendingintents and broadcastreceiver)

외부/등록 된 위치로 이동할 때 지오 펜스를 트리거 할 수 없습니다. 여기

/* 
* Create a PendingIntent that triggers an IntentService in your 
* app when a geofence transition occurs. 
*/ 
protected PendingIntent getTransitionPendingIntent() { 
    if (mGeoPendingIntent != null) { 
     return mGeoPendingIntent; 
    } 

    else { 

     // Create an explicit Intent 
     // Intent intent = new Intent(mContext, 
     //   ReceiveTransitionsIntentService.class); 

     Intent intent = new Intent(getClass().getPackage().getName() + ".GEOFENCE_RECEIVE"); 

     /** 
     * Return the PendingIntent 
     */ 
     return PendingIntent.getBroadcast(
       mContext, 
       0, 
       intent, 
       PendingIntent.FLAG_UPDATE_CURRENT); 

    } 
} 

나는 새로운 지오 펜스를 만드는 방법은 다음과 같습니다 :

/** 
    * GeoLocation library 
    */ 
    mGeoLocation = new GeoLocation(sInstance); 


    /** 
    * mReceiver init 
    */ 
    mReceiver = new Receiver(); 
    sInstance.registerReceiver(mReceiver, mReceiver.createIntentFilter()); 

GPS와 같은 클래스 내부 : 여기 내 절차의

     Geofence fence = new Geofence.Builder() 
           .setRequestId(hashCode) 
             // when entering this geofence 
           .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) 
           .setCircularRegion(
             Double.parseDouble(single.getSetting("latitude")), 
             Double.parseDouble(single.getSetting("longitude")), 
             Float.parseFloat(single.getSetting("radius")) // radius in meters 
           ) 
           .setExpirationDuration(Geofence.NEVER_EXPIRE) 
           .build(); 

         mGeofences.add(fence); 

배열이 채워됩니다 우리는 지오 펜스 클래스 내부 방법 AddGeofences를 호출

mGeoLocation.AddGeofences(mGeofences); 

리시버 클래스의 AndroidManifest.xml : 지오 펜스가 문제가

public void onReceive(Context context, Intent intent) { 
    String action = intent.getAction(); 

    Log.d("sfen", "Broadcast recieved "+ action +" but not needed."); 
} 

를 트리거 할 때

<!-- RECEIVER --> 
    <receiver android:name=".Receiver" > 
    </receiver> 

그리고 수신기 클래스는 그냥 내 응용 프로그램 내에서지도를 열 때 지오 펜스가 만 실행되고 있는지, 기록해야 어디 위치를 선택하십시오. 앱을 닫으면 (배경에서 실행) 아무 것도 트리거하지 않으며 지오 펜스 전환으로 아무 것도 트리거하지 않습니다.

누군가 내가 뭘 잘못하고 있다고 말할 수 있습니까?

+0

geolocation을 사용하는 다른 앱을 열 때 지오 펜스가 트리거됩니까? 예를 들어 지오 펜스를 설정 한 경우 앱을 종료하고 Google지도를 열고 지오 펜스 영역으로 또는 지리 영역 밖으로 이동합니다. 지오 펜스가 실행됩니까? –

+0

@RussWilde - 네, 백그라운드에서 앱을 옮겨서 Google지도를 열면 두 가지 작업이 모두 실행됩니다. – gregor

+0

듣기가 불행합니다. 필자는 IFTTT 및 Field Trip과 같은 다른 응용 프로그램을 포함하여 지리 울타리와 함께 매우 혼란스러운 결과를 보았습니다. 왜 일부 울타리가 안정적으로 트리거되지 않았고 Android의 기본 위치 서비스가 업데이트되지 않는지 궁금해 할 때마다 자주 모든 위치를 파악하기에 충분합니다. 슬프게도이 경우 유용한 해결책이 없습니다. 그러나 다른 사람들이 제공 할 수있는 답변에도 관심이 있습니다. –

답변

1

수신자가 아닌 지오 코딩 이벤트를 수신하려면 IntentService를 사용해야합니다. https://github.com/chenjishi/android_location_demo에 데모를 작성했습니다.

는 4.finally 수신 할 IntentService 정의 지오 펜스를

@Override 
public void onConnected(Bundle bundle) { 
    ArrayList<Store> storeList = getStoreList(); 
    if (null != storeList && storeList.size() > 0) { 
     ArrayList<Geofence> geofenceList = new ArrayList<Geofence>(); 
     for (Store store : storeList) { 
      float radius = (float) store.radius; 
      Geofence geofence = new Geofence.Builder() 
        .setRequestId(store.id) 
        .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) 
        .setCircularRegion(store.latitude, store.longitude, radius) 
        .setExpirationDuration(Geofence.NEVER_EXPIRE) 
        .build(); 

      geofenceList.add(geofence); 
     } 

     PendingIntent geoFencePendingIntent = PendingIntent.getService(this, 0, 
       new Intent(this, GeofenceIntentService.class), PendingIntent.FLAG_UPDATE_CURRENT); 
     locationClient.addGeofences(geofenceList, geoFencePendingIntent, this); 
    } 
} 

레지스터 LocationClient가

private LocationClient locationClient; 

2.init가

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    int resp = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); 
    if (resp == ConnectionResult.SUCCESS) { 
     locationClient = new LocationClient(this, this, this); 
     locationClient.connect(); 
    } 
} 

3.when 성공 연결 정의 1.first 지오 펜싱 이벤트

public class GeofenceIntentService extends IntentService { 
public static final String TRANSITION_INTENT_SERVICE = "ReceiveTransitionsIntentService"; 

public GeofenceIntentService() { 
    super(TRANSITION_INTENT_SERVICE); 
} 

@Override 
protected void onHandleIntent(Intent intent) { 
    if (LocationClient.hasError(intent)) { 
     //todo error process 
    } else { 
     int transitionType = LocationClient.getGeofenceTransition(intent); 
     if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER || 
       transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) { 
      List<Geofence> triggerList = LocationClient.getTriggeringGeofences(intent); 

      for (Geofence geofence : triggerList) { 
       generateNotification(geofence.getRequestId(), "address you defined"); 
      } 
     } 
    } 
} 

private void generateNotification(String locationId, String address) { 
    long when = System.currentTimeMillis(); 
    Intent notifyIntent = new Intent(this, MainActivity.class); 
    notifyIntent.putExtra("id", locationId); 
    notifyIntent.putExtra("address", address); 
    notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); 

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

    NotificationCompat.Builder builder = 
      new NotificationCompat.Builder(this) 
        .setSmallIcon(R.drawable.dac_logo) 
        .setContentTitle(locationId) 
        .setContentText(address) 
        .setContentIntent(pendingIntent) 
        .setAutoCancel(true) 
        .setDefaults(Notification.DEFAULT_SOUND) 
        .setWhen(when); 

    NotificationManager notificationManager = 
      (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
    notificationManager.notify((int) when, builder.build()); 
} 

+0

안녕하세요. 앞에서 언급했듯이 b-ryce의 답변도 인용 할 것입니다. '이 부분을 가지고 놀고 나면 샘플 코드에 정의 된 ReceiveTransitionsIntentService가 앱이 주변에 없을 때 알림을받지 않게됩니다. 나는 이것이 예제 코드로 큰 문제라고 생각한다. 지오 펜스를 사용하여 결과가 매우 혼합 된 것처럼 보입니다. 아직도 일부 사람들을 위해 때때로 작동하고 다른 사람들을 위해 일하는 이유에 대해 확실하지 않습니다. – gregor

+0

@gregor 귀하의 휴대 전화 위치 서비스 체크 박스가 선택되었는지 확인 했습니까 ??? 위치 정보 서비스가 필요한 지오 펜싱을 사용하려면 사용자에게 가이드를 제공해야합니다. –

+0

나는 해냈다. 그러나 전화기 중 하나에서 나는 4.4.2에서 4.4.4로 업그레이드 한 이후로 더 잘 작동한다는 것을 알았습니다. 더 많은 테스트와 결과 게시 (해당하는 경우) – gregor

관련 문제