Android 我对geofences过渡出口有问题。我正在处理他进出该位置时收到的通知
当我输入Constants.java中提到的位置时,我正在处理通知。问题是…我使用了fakelocation应用程序并保留了一些较远的位置,但仍然收到通知,如entered和when exit..也收到了输入通知 我的完整代码: 在这里输入代码 Constants.java:Android 我对geofences过渡出口有问题。我正在处理他进出该位置时收到的通知,android,Android,当我输入Constants.java中提到的位置时,我正在处理通知。问题是…我使用了fakelocation应用程序并保留了一些较远的位置,但仍然收到通知,如entered和when exit..也收到了输入通知 我的完整代码: 在这里输入代码 Constants.java: public class Constants { public static final long GEOFENCE_EXPIRATION_IN_MILLISECONDS = 12 * 60 * 60 * 1000; p
public class Constants {
public static final long GEOFENCE_EXPIRATION_IN_MILLISECONDS = 12 * 60 * 60 * 1000;
public static final float GEOFENCE_RADIUS_IN_METERS = 1000;
public static final HashMap<String, LatLng> LANDMARKS = new HashMap<String, LatLng>();
static {
// Shoppers Stop
LANDMARKS.put("Shoppers Stop", new LatLng(17.729192, 83.314607));
// aucampus
LANDMARKS.put("aucampus", new LatLng(17.729020, 83.320096));
//my home
LANDMARKS.put("Krishna temple",new LatLng(17.735146, 83.327637));
//central
LANDMARKS.put("cmr central",new LatLng(17.734472, 83.318418));
LANDMARKS.put("Spencers",new LatLng(17.730323, 83.314254));
}
}
MAinActivity.java
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);
Button mAddGeofencesButton = (Button) findViewById(R.id.add_geofences_button);
mGeofenceList = new ArrayList<Geofence>();
populateGeofenceList();
// Kick off the request to build GoogleApiClient.
buildGoogleApiClient();
}
@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnecting() || mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
@Override
protected void onStart() {
super.onStart();
if (!mGoogleApiClient.isConnecting() || !mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
private 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
public void onConnected(Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
Toast.makeText(
this,
"Geofences Added",
Toast.LENGTH_SHORT
).show();
new GeofenceTransitionsIntentService().onHandleIntent(getIntent());
} else {
Toast.makeText(
this,
"Geofences not Added",
Toast.LENGTH_SHORT
).show();
}
}
//for adding geofences //
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 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);
}
private GeofencingRequest getGeofencingRequest() {
GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
// builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
builder.addGeofences(mGeofenceList);
return builder.build();
}
}
GeofenceTransitionsIntentService.java
public class GeofenceTransitionsIntentService extends IntentService {
private static final String TAG = "GeofenceTransitionsIS";
public GeofenceTransitionsIntentService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
GeofencingEvent event = GeofencingEvent.fromIntent(intent);
if (event.hasError()) {
Log.e(TAG, "GeofencingEvent Error: " + event.getErrorCode());
return;
}
// Get the transition type.
int geofenceTransition1 = event.getGeofenceTransition();
// Test that the reported transition was of interest.
if (geofenceTransition1 == Geofence.GEOFENCE_TRANSITION_ENTER ||
geofenceTransition1 == Geofence.GEOFENCE_TRANSITION_EXIT||geofenceTransition1==Geofence.GEOFENCE_TRANSITION_DWELL) {
// Get the geofences that were triggered. A single event can trigger multiple geofences.
List<Geofence> triggeringGeofences = event.getTriggeringGeofences();
// Get the transition details as a String.
String geofenceTransitionDetails = getGeofenceTransitionDetails(
this,
geofenceTransition1,
triggeringGeofences
);
Log.i(TAG, geofenceTransitionDetails);
String geofenceTransition =getTransitionString(geofenceTransition1);
// Send notification and log the transition details.
sendNotification(geofenceTransition);
// String description = getGeofenceTransitionDetails(event);
// sendNotification(description);
}
// getTransitionString(geofenceTransition);
}
private void sendNotification(String geofenceTransition) {
// Create an explicit content Intent that starts the main Activity.
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
// Construct a task stack.
TaskStackBuilder stackBuilder = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
stackBuilder = TaskStackBuilder.create(this);
// }
// Add the main Activity to the task stack as the parent.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
stackBuilder.addParentStack(MainActivity.class);
}
// Push the content Intent onto the stack.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
stackBuilder.addNextIntent(notificationIntent);
}
// Get a PendingIntent containing the entire back stack.
PendingIntent notificationPendingIntent =
null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
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.setSmallIcon(android.R.color.background_dark)
// In a real app, you may want to use a library like Volley
// to decode the Bitmap.
.setColor(Color.RED)
.setContentTitle("Notification")
.setContentText(geofenceTransition.toString())
.setContentIntent(notificationPendingIntent);
// Dismiss notification once the user touches it.
builder.setAutoCancel(true);
// Get an instance of the Notification manager
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Issue the notification
mNotificationManager.notify(0, builder.build());
}
}
private String getGeofenceTransitionDetails(GeofenceTransitionsIntentService geofenceTransitionsIntentService, int geofenceTransition, List<Geofence> triggeringGeofences) {
String geofenceTransitionString = getTransitionString(geofenceTransition);
// Get the Ids of each geofence that was triggered.
ArrayList triggeringGeofencesIdsList = new ArrayList();
for (Geofence geofence : triggeringGeofences) {
triggeringGeofencesIdsList.add(geofence.getRequestId());
}
String triggeringGeofencesIdsString = TextUtils.join(", ", triggeringGeofencesIdsList);
return geofenceTransitionString + ": " + triggeringGeofencesIdsString;
}
public String getTransitionString(int geofenceTransition) {
switch (geofenceTransition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
return "entered";
case Geofence.GEOFENCE_TRANSITION_EXIT:
return "exited";
default:
return "happyy";
}
}
}
公共类常量{
公共静态最终长地理围栏\u到期时间\u毫秒=12*60*60*1000;
公共静态最终浮式土工围栏半径(单位:米)=1000;
public static final HashMap LANDMARKS=new HashMap();
静止的{
//购物者停止
LANDMARKS.put(“购物者停止”,new LatLng(17.729192,83.314607));
//奥坎普斯
LANDMARKS.put(“奥坎普斯”,新拉特林(17.729020,83.320096));
//我家
LANDMARKS.put(“克里希纳神庙”,新拉特宁(17.735146,83.327637));
//中央的
LANDMARKS.put(“cmr central”,新LatLng(17.734472,83.318418));
LANDMARKS.put(“斯宾塞”,新拉特林(17.730323,83.314254));
}
}
MAinActivity.java
公共类MainActivity扩展AppCompatActivity实现GoogleAppClient.ConnectionCallbacks,
GoogleAppClient.OnConnectionFailedListener,
结果回拨{
受保护的阵列列表mGeofenceList;
受保护的GoogleapClient MGoogleapClient;
专用按钮,由按钮组成;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
按钮mAddGeofencesButton=(按钮)findViewById(R.id.add_geofences_按钮);
mGeofenceList=newarraylist();
populateGeofenceList();
//启动构建GoogleAppClient的请求。
buildGoogleAppClient();
}
@凌驾
受保护的void onStop(){
super.onStop();
if(mGoogleApiClient.isConnecting()| | mGoogleApiClient.isConnected()){
mGoogleApiClient.disconnect();
}
}
@凌驾
受保护的void onStart(){
super.onStart();
如果(!mGoogleApiClient.isConnecting()| |!mGoogleApiClient.isConnected()){
mGoogleApiClient.connect();
}
}
受保护的同步无效BuildGoogleAppClient(){
mgoogleapclient=新的Googleapclient.Builder(此)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.addApi(LocationServices.API)
.build();
}
私有void populateGeofenceList(){
对于(Map.Entry:Constants.LANDMARKS.entrySet()){
mGeofenceList.add(new geofinence.Builder()
.setRequestId(entry.getKey())
.setCircularRegion(
entry.getValue().latitude,
entry.getValue()经度,
常数。土工围栏半径(单位:米)
)
.setExpirationDuration(常数.geofense\u EXPIRATION\u以毫秒为单位)
.setTransitionTypes(geofnce.geofnce\u TRANSITION\u输入|
土工围栏。土工围栏(过渡段和出口)
.build());
}
}
@凌驾
未连接的公共空间(捆绑包){
}
@凌驾
公共空间连接暂停(int i){
}
@凌驾
公共无效onConnectionFailed(ConnectionResult ConnectionResult){
}
@凌驾
公共void onResult(状态){
if(status.issucess()){
Toast.makeText(
这
“添加地理围栏”,
吐司长度
).show();
新的GeofenceTransitionsIntentService().onHandleIntent(getIntent());
}否则{
Toast.makeText(
这
“未添加地理围栏”,
吐司长度
).show();
}
}
//用于添加地理围栏//
公共无效addGeofencesButtonHandler(视图){
如果(!mgoogleapClient.isConnected()){
Toast.makeText(这是“Google API客户端未连接!”,Toast.LENGTH_SHORT.show();
返回;
}
试一试{
LocationServices.GeofencingApi.AddGeofines(
MGoogleapClient,
getGeofencingRequest(),
getGeofencePendingIntent()
).setResultCallback(this);//在onResult()中处理的结果。
}捕获(SecurityException SecurityException){
//如果应用程序未使用“访问\罚款\位置”权限,则生成捕获异常。
}
}
私有PendingEvent GetGeoFencePendingEvent(){
意向意向=新意向(这是GeofenceTransitionsIntentService.class);
//我们使用FLAG_UPDATE_CURRENT,以便在调用addgeofines()时获得相同的挂起意图
返回pendingent.getService(this,0,intent,pendingent.FLAG_UPDATE_CURRENT);
}
私人GeofencingRequest getGeofencingRequest(){
GeofencingRequest.Builder=新的GeofencingRequest.Builder();
//builder.setInitialTrigger(GeofencingRequest.INITIAL\u TRIGGER\u ENTER);
建造商。添加地理围栏(MGEOFENCESLIST);
返回builder.build();
}
}
GeofenceTransitionsIntentService.java
公共类GeofenceTransitionsIntentService扩展了IntentService{
私有静态最终字符串TAG=“GeoFenceTransitions”;
公共地理围栏TransitionsIntentService(){
超级(标签);
}
@凌驾
受保护的手部内容无效(意图){
GeofencingEvent事件=GeofencingEvent.fromIntent(intent);
if(event.hasError()){
Log.e(标记“GeofencingEvent Error:+event.getErrorCode());
返回;
}
//获取转换类型。
int geofenceTransition1=event.getGeofenceTransition();