0

지오 펜스에 완전히 새로운 것이므로 지오 펜스 설정에 대한 다음 자습서를 따랐습니다 : http://io2015codelabs.appspot.com/codelabs/geofences#4.지오 펜스에 들어가면 간단한 메시지를 토스트하는 방법?

코드가 실행되었지만 지리적 울타리로 들어갈 때 아무 일도 일어나지 않습니다 ... 내가 입력하거나 지오 펜스를 떠날 때 토스트는 어떻게 될까요? 내 코드는 가이드의 코드와 정확히 같습니다. 그래서 사람들이 나를 도와 줄 수 있기를 바랍니다. I

여기

지리적 울타리 클래스 :

public class Constants 
{ 
    public static final long GEOFENCE_EXPIRATION_IN_MILLISECONDS = 12 * 60 * 60 * 1000; 
    public static final float GEOFENCE_RADIUS_IN_METERS = 20; 

    public static final HashMap<String, LatLng> LANDMARKS = new HashMap<String, LatLng>(); 
    static { 
     // San Francisco International Airport. 
     LANDMARKS.put("Westwood", new LatLng(34.067313, -118.461164)); //34.065767, -118.459658 LANDMARKS.put("Westwood", new LatLng(34.065767, -118.459658)); 

     // Googleplex. 
     LANDMARKS.put("Japantown", new LatLng(37.785281,-122.4296384)); 

     // Test 
     LANDMARKS.put("SFO", new LatLng(37.621313,-122.378955)); 
    } 
} 
+0

다음 단계에 따라, 그리고'어딘가에 onHandleIntent'에서 축배를 보여줍니다. – stkent

+0

@stkent 그래서 난 onHandleIntent에 간단한 Toast 문을 씁니다. –

+0

나는 안내자가 그것을 한 방법과 onHandleIntent를 구현했는데 아무 일도 없었다는 것을 의미합니까? ...? –

답변

1

이 가이드의 코드가 표시됩니다 : 여기

public class GeoFence extends AppCompatActivity implements 
     GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener, 
     ResultCallback<Status> 
{ 
    protected ArrayList<Geofence> mGeofenceList; 
    protected GoogleApiClient mGoogleApiClient; 
    private Button mAddGeofencesButton; 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_geo_fence); 
     mAddGeofencesButton = (Button) findViewById(R.id.add_geofences_button); 
     // Empty list for storing geofences. 
     mGeofenceList = new ArrayList<Geofence>(); 

     // Get the geofences used. Geofence data is hard coded in this sample. 
     populateGeofenceList(); 

     // Kick off the request to build GoogleApiClient. 
     buildGoogleApiClient(); 

    } 

    public void populateGeofenceList() { 
     for (Map.Entry<String, LatLng> entry : Constants.LANDMARKS.entrySet()) { 
      mGeofenceList.add(new Geofence.Builder() 
        .setRequestId(entry.getKey()) 
        .setCircularRegion(
          entry.getValue().latitude, 
          entry.getValue().longitude, 
          Constants.GEOFENCE_RADIUS_IN_METERS 
        ) 
        .setExpirationDuration(Constants.GEOFENCE_EXPIRATION_IN_MILLISECONDS) 
        .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | 
          Geofence.GEOFENCE_TRANSITION_EXIT) 
        .build()); 
     } 
    } 
    protected synchronized void buildGoogleApiClient() { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
    } 
    public void addGeofencesButtonHandler(View view) { 
     if (!mGoogleApiClient.isConnected()) { 
      Toast.makeText(this, "Google API Client not connected!", Toast.LENGTH_SHORT).show(); 
      return; 
     } 

     try { 
      LocationServices.GeofencingApi.addGeofences(
        mGoogleApiClient, 
        getGeofencingRequest(), 
        getGeofencePendingIntent() 
      ).setResultCallback(this); // Result processed in onResult(). 
     } catch (SecurityException securityException) { 
      // Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission. 
     } 
    } 
    private GeofencingRequest getGeofencingRequest() { 
     GeofencingRequest.Builder builder = new GeofencingRequest.Builder(); 
     builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER); 
     builder.addGeofences(mGeofenceList); 
     return builder.build(); 
    } 
    private PendingIntent getGeofencePendingIntent() { 
     Intent intent = new Intent(this, GTIS.class); 
     // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling addgeoFences() 
     return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 
    } 
    @Override 
    public void onConnected(Bundle connectionHint) { 

    } 

    @Override 
    public void onConnectionFailed(ConnectionResult result) { 
     // Do something with result.getErrorCode()); 
    } 
    @Override 
    public void onConnectionSuspended(int cause) { 
     mGoogleApiClient.connect(); 
    } 
    @Override 
    protected void onStart() { 
     super.onStart(); 
     if (!mGoogleApiClient.isConnecting() || !mGoogleApiClient.isConnected()) { 
      mGoogleApiClient.connect(); 
     } 
    } 

    @Override 
    protected void onStop() { 
     super.onStop(); 
     if (mGoogleApiClient.isConnecting() || mGoogleApiClient.isConnected()) { 
      mGoogleApiClient.disconnect(); 
     } 
    } 

    public void onResult(Status status) 
    { 
     if (status.isSuccess()) { 
      Toast.makeText(
        this, 
        "Geofences Added", 
        Toast.LENGTH_SHORT 
      ).show(); 
     } else { 
      Toast.makeText(this,"No geo fence :(",Toast.LENGTH_SHORT).show(); 
     } 
    } 
} 

내 상수 클래스가있는 GeofenceTransitionsIntentService 클래스 다음

public class GTIS extends IntentService 
{ 
    protected static final String TAG = "GeofenceTransitionsIS"; 

    public GTIS() { 
     super(TAG); // use TAG to name the IntentService worker thread 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
     GeofencingEvent event = GeofencingEvent.fromIntent(intent); 
     if (event.hasError()) { 
      Log.e(TAG, "GeofencingEvent Error: " + event.getErrorCode()); 
      String description = getGeofenceTransitionDetails(event); 
      sendNotification(description); 
      return; 
     } 
    } 
    private static String getGeofenceTransitionDetails(GeofencingEvent event) { 
     String transitionString = 
       GeofenceStatusCodes.getStatusCodeString(event.getGeofenceTransition()); 
     List triggeringIDs = new ArrayList(); 
     for (Geofence geofence : event.getTriggeringGeofences()) { 
      triggeringIDs.add(geofence.getRequestId()); 
     } 
     return String.format("%s: %s", transitionString, TextUtils.join(", ", triggeringIDs)); 
    } 

    private void sendNotification(String notificationDetails) { 
     // Create an explicit content Intent that starts MainActivity. 
     Intent notificationIntent = new Intent(getApplicationContext(), Geofence.class); 

     // Get a PendingIntent containing the entire back stack. 
     TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); 
     stackBuilder.addParentStack(GeoFence.class).addNextIntent(notificationIntent); 
     PendingIntent notificationPendingIntent = 
       stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); 

     // Get a notification builder that's compatible with platform versions >= 4 
     NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 

     // Define the notification settings. 
     builder.setColor(Color.RED) 
       .setContentTitle(notificationDetails) 
       .setContentText("Click notification to return to App") 
       .setContentIntent(notificationPendingIntent) 
       .setAutoCancel(true); 

     // Fire and notify the built Notification. 
     NotificationManager notificationManager = 
       (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
     notificationManager.notify(0, builder.build()); 
    } 

} 

입니다 Notification은 아니요 Toast입니다. 당신이 오류가 당신이해야 할 일은

을 발생하지 않기 때문에 귀하의 경우에는 트리거하지 않는 if(event.hasError()) 문 내부 sendNotification()를 호출하기 때문에 그것은 당신을 위해 작동하지 않는 것은 :

다시
@Override 
protected void onHandleIntent(Intent intent) { 
    GeofencingEvent event = GeofencingEvent.fromIntent(intent); 
    if (event.hasError()) { 
     Log.e(TAG, "GeofencingEvent Error: " + event.getErrorCode()); 
    } 
    String description = getGeofenceTransitionDetails(event); 
    sendNotification(description); 
} 

,이 코드가 보여 주 시겠어요

  1. 앱도 그냥 보여주는 지오 펜스 전환과 토스트의 번에 활성화 할 수 없습니다 O : 이러한 이유로 실제 생활 응용 프로그램에 Toast보다 더 나을 Notification 아무리해도 이상하게 보일 수 있습니다.
  2. 알림 당신이 더 많은 정보 (제목 및 텍스트)를 표시하고 어쩌면 앱에 다시 지시 할 수 있습니다
  3. 그것은 사용자에게 읽고 당신은 여전히 ​​원하는 경우 자신의 편리

에서이를 기각 할 수있는 기회를 제공

  • 어쨌든 Toast을 보여주기 위해, 당신은 그것을 당신이 Activity에서 할 것 같은 방법으로해야한다 (IntentService 것은 너무 Context입니다) :

    Toast.makeText(this, description, Toast.LENGTH_LONG).show();