01/10/2018, 14:02

Lỗi khi dùng Geofence Api

em đang tính tìm hiểu về api Geofence , em có lên mạng tìm hiểu và chạy thử code example nhưng lúc addGeofences thì nó cứ bị lỗi : " Status{statusCode=SUCCESS, resolution=null} "
code đây ạ :

GeofencesManagingService :

public class GeofencesManagingService extends IntentService {
protected static final String TAG = "GeofenceMS";
public GeofencesManagingService() {
    super(TAG);
}
  @Override
  public void onCreate() {
     super.onCreate();
 }
@Override
protected void onHandleIntent(Intent intent) {
    System.out.println("tesssssssssst");
    // Check sự kiện Geofencing
    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
    // Kiểm tra và return ngay nếu có lỗi
    if (geofencingEvent.hasError()) {
        String errorMessage = ErrorMessages.getErrorString(this, geofencingEvent.getErrorCode());
        return;
    }
    // Nếu không có lỗi, lấy kiểu di chuyển (vào hay ra khỏi geofence)
    int geofenceTransition = geofencingEvent.getGeofenceTransition();
    // Gửi Notification về nếu kiểu di chuyển thuộc loại vào hoặc ra geofence
    if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
            geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
        // Lấy ra list các geofences đã kích hoạt Intent
        List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
        // Tổng hợp lại vào message cho
        String geofenceTransitionDetails = getGeofenceTransitionDetails(
                this,
                geofenceTransition,
                triggeringGeofences
        );
        // Gửi Notification
        sendNotification(geofenceTransitionDetails);
        Log.i(TAG, geofenceTransitionDetails);
    } else {
        // Log lỗi không xác định được kiểu di chuyển
        Log.e(TAG, getString(R.string.geofence_transition_invalid_type, geofenceTransition));
    }
}
private String getGeofenceTransitionDetails(
        Context context,
        int geofenceTransition,
        List<Geofence> triggeringGeofences) {
    String geofenceTransitionString = getTransitionString(geofenceTransition);
    // Lấy ids tất cả các geofence kích hoạt intent
    ArrayList triggeringGeofencesIdsList = new ArrayList();
    for (Geofence geofence : triggeringGeofences) {
        triggeringGeofencesIdsList.add(geofence.getRequestId());
    }
    String triggeringGeofencesIdsString = TextUtils.join(", ", triggeringGeofencesIdsList);
    return geofenceTransitionString + ": " + triggeringGeofencesIdsString;
}
private void sendNotification(String notificationDetails) {
    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(notificationIntent);
    PendingIntent notificationPendingIntent =
            stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(),
                    R.mipmap.ic_launcher))
            .setColor(Color.RED)
            .setContentTitle(notificationDetails)
            .setContentText(getString(R.string.geofence_transition_notification_text))
            .setContentIntent(notificationPendingIntent);
    builder.setAutoCancel(true);
    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(0, builder.build());
}
private String getTransitionString(int transitionType) {
    switch (transitionType) {
        case Geofence.GEOFENCE_TRANSITION_ENTER:
            return getString(R.string.geofence_transition_entered);
        case Geofence.GEOFENCE_TRANSITION_EXIT:
            return getString(R.string.geofence_transition_exited);
        default:
            return getString(R.string.unknown_geofence_transition);
    }
}

}

MainActivity 
 public class MainActivity extends AppCompatActivity implements
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, 
ResultCallback {
protected static final String TAG = "MainActivity";
protected GoogleApiClient mGoogleApiClient;
protected ArrayList<Geofence> mGeofenceList;
private boolean mGeofencesAdded;
private PendingIntent mGeofencePendingIntent;
private SharedPreferences mSharedPreferences;
private Button mAddGeofencesButton;
private Button mRemoveGeofencesButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mAddGeofencesButton = (Button) findViewById(R.id.add_geofences_button);
    mRemoveGeofencesButton = (Button) findViewById(R.id.remove_geofences_button);
    // List các geofences
    mGeofenceList = new ArrayList<Geofence>();
    mGeofencePendingIntent = null;
    mSharedPreferences = getSharedPreferences(CommonConstants.SHARED_PREFERENCES_NAME,
            MODE_PRIVATE);
    mGeofencesAdded = mSharedPreferences.getBoolean(CommonConstants.GEOFENCES_ADDED_KEY, false);
    setButtonsEnabledState();
    // Lấy ra các geofences đã được đăng ký ở file CommonConstants
    updateGeofenceList();
    // build GoogleApiClient
    buildGoogleApiClient();
    int x;
}
//--------------------------------------------------------------
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}
private void updateGeofenceList() {
    for (Map.Entry<String, LatLng> entry : CommonConstants.AREA_LANDMARKS.entrySet()) {
        mGeofenceList.add(new Geofence.Builder()
                .setRequestId(entry.getKey())
                .setCircularRegion(
                        entry.getValue().latitude,
                        entry.getValue().longitude,
                        CommonConstants.GEOFENCE_RADIUS_IN_METERS
                )
                .setExpirationDuration(840000)
                .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
                        Geofence.GEOFENCE_TRANSITION_EXIT)
                .build());
    }
}
private void setButtonsEnabledState() {
    if (mGeofencesAdded) {
        mAddGeofencesButton.setEnabled(false);
        mRemoveGeofencesButton.setEnabled(true);
    } else {
        mAddGeofencesButton.setEnabled(true);
        mRemoveGeofencesButton.setEnabled(false);
    }
}
   //--------------------------------------------------------
 @Override
    protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
    Log.i(TAG, "Connected to GoogleApiClient");
}
@Override
public void onConnectionSuspended(int i) {
    Log.i(TAG, "Connection suspended");
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
}
public void addGeofencesButtonHandler(View view) {
    if (!mGoogleApiClient.isConnected()) {
        Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show();
        return;
    }
    if (ActivityCompat.checkSelfPermission(MainActivity.this,
            android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                111);
    }
    try {
        LocationServices.GeofencingApi.addGeofences(
                mGoogleApiClient,
                getGeofencingRequest(),
                getGeofencePendingIntent()
        ).setResultCallback(this);
    } catch (SecurityException securityException) {
        logSecurityException(securityException);
    }
}
public void removeGeofencesButtonHandler(View view) {
    if (!mGoogleApiClient.isConnected()) {
        Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show();
        return;
    }
    try {
        LocationServices.GeofencingApi.removeGeofences(
                mGoogleApiClient,
                getGeofencePendingIntent()
        ).setResultCallback(this); // Result processed in onResult().
    } catch (SecurityException securityException) {
        logSecurityException(securityException);
    }
}
private void logSecurityException(SecurityException securityException) {
    Log.e(TAG, "Invalid location permission. " +
            "Lấy thêm quyền ACCESS_FINE_LOCATION ở AndroidManifest nhé!", securityException);
}
//    public void onResult(Status status) {
//        if (status.isSuccess()) {
//            mGeofencesAdded = !mGeofencesAdded;
//            SharedPreferences.Editor editor = mSharedPreferences.edit();
//            editor.putBoolean(CommonConstants.GEOFENCES_ADDED_KEY, 
mGeofencesAdded);
//            editor.apply();
//
//            setButtonsEnabledState();
//
//            Toast.makeText(
//                    this,
//                    getString(mGeofencesAdded ? R.string.geofences_added :
//                            R.string.geofences_removed),
//                    Toast.LENGTH_SHORT
//            ).show();
//        } else {
//            // Get the status code for the error and log it using a user-friendly message.
//            String errorMessage = ErrorMessages.getErrorString(this,
//                    status.getStatusCode());
//            Log.e(TAG, errorMessage);
//        }
//    }
@Override
public void onResult(@NonNull Result result) {
    System.out.println("tesssssssssst");
    Log.e(TAG, String.format("Error adding/removing geofence : %s",
            result.getStatus().toString()));
}
private PendingIntent getGeofencePendingIntent() {
    if (mGeofencePendingIntent != null) {
        return mGeofencePendingIntent;
    }
    Intent intent = new Intent(this, GeofencesManagingService.class);
    return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
//------------------------------------------------------
private GeofencingRequest getGeofencingRequest() {
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
    builder.addGeofences(mGeofenceList);
    return builder.build();
}

}

source : https://github.com/ngoduyson/GeofencesManaging
bài giới thiệu : https://viblo.asia/p/lam-mot-task-voi-geofencing-trong-android-thi-mat-bao-lau-3KbvZqELGmWB

Bài liên quan
0