我正在尝试构建一个触发基于地理围栏的通知的应用程序,我已设法创建地理围栏但由于某些原因通知未显示 . 如果有人可以帮助我,我会很感激 . 我在下面的代码中使用了调试器,我认为意图服务根本没有触发 .

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback<Status> {

protected ArrayList<Geofence> mGeofenceList;
protected GoogleApiClient mGoogleApiClient;
private Button mAddGeofencesButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    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();

}

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

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());
    }
}

@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();
    }
}

@Override
public void onConnected(Bundle connectionHint) {
    Log.d("Connected","Google");
}

@Override
public void onConnectionFailed(ConnectionResult result) {
    // Do something with result.getErrorCode());
    Log.d("Not Connected","Google");
}

@Override
public void onConnectionSuspended(int cause) {
    mGoogleApiClient.connect();
}

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, GeofenceTransitionsIntentService.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);
}
public void onResult(Status status) {
    if (status.isSuccess()) {
        Toast.makeText(
                this,
                "Geofences Added",
                Toast.LENGTH_SHORT
        ).show();
    } else {
        // Get the status code for the error and log it using a user-friendly message.
        System.out.println("Error");
    }
}

}

public class Constants {

public static final long GEOFENCE_EXPIRATION_IN_MILLISECONDS = 60 * 60 * 1000;
public static final float GEOFENCE_RADIUS_IN_METERS = 500;

public static final HashMap<String, LatLng> LANDMARKS = new HashMap<String, LatLng>();
static {
    // San Francisco International Airport.
    LANDMARKS.put("Mamagato", new LatLng(17.4101080, 78.4402424));

    // Googleplex.
    LANDMARKS.put("Muffakham jah", new LatLng(17.4282648, 78.442848));

    // Test
    LANDMARKS.put("Deccan", new LatLng(17.3845578, 78.4649667));

    LANDMARKS.put("Osmania", new LatLng(17.4180039, 78.5273363));
    LANDMARKS.put("JNTU", new LatLng(17.494568, 78.3920556));
}

}

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

public GeofenceTransitionsIntentService() {
    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());
        return;
    }
    String description = getGeofenceTransitionDetails(event);
    sendNotification(description);
}

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(), MainActivity.class);

    // Get a PendingIntent containing the entire back stack.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.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());
}

}