Android 我想做的服务,广播通知,如果我在地理围栏与否
这是光线投射算法,用于检查当前用户位置是否位于点内Android 我想做的服务,广播通知,如果我在地理围栏与否,android,google-maps-android-api-2,android-geofence,Android,Google Maps Android Api 2,Android Geofence,这是光线投射算法,用于检查当前用户位置是否位于点内 h.postDelayed(new Runnable(){ public void run(){ 这很好,正在检查geo fence中的当前位置。 现在我想让它成为一种服务,这样无论我是否进入那个地理围栏,它都会广播消息。我正在为此定制围栏 这段代码适用于我的地理围栏,你也可以试试 在地图上单击,您可以添加一个标记,如: if (PolyUtil.containsLocation(latLngc
h.postDelayed(new Runnable(){
public void run(){
这很好,正在检查geo fence中的当前位置。
现在我想让它成为一种服务,这样无论我是否进入那个地理围栏,它都会广播消息。我正在为此定制围栏 这段代码适用于我的地理围栏,你也可以试试 在地图上单击,您可以添加一个标记,如:
if (PolyUtil.containsLocation(latLngchangeloc, arrayPoints, true)==true) {
//Intent intent=new Intent();
//intent.setAction("MyBroadcast");
//intent.putExtra("values","enter");
//sendBroadcast(intent);
// sendNotification("enter");
//Toast.makeText(this, "enter", Toast.LENGTH_SHORT).show();
} else {
//Intent intent=new Intent();
//intent.setAction("MyBroadcast");
//intent.putExtra("values","leave");
//sendBroadcast(intent);
// sendNotification("leave");
//Toast.makeText(this, "leave", Toast.LENGTH_SHORT).show();
}
h.postDelayed(this, 3000);
}
}, delay);
}
围绕此标记开始地理围栏:
@Override
public void onMapClick(LatLng latLng) {
markerForGeofence(latLng);
}
private Marker geoFenceMarker;
//create marker for geo fence
private void markerForGeofence(LatLng model) {
MarkerOptions markerOptions = new MarkerOptions()
.position(model)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
if ( map!=null ) {
if (geoFenceMarker != null)
geoFenceMarker.remove();
geoFenceMarker = map.addMarker(markerOptions);
}
}
在谷歌地图上画圆圈:
// Start Geofence creation process
private void startGeofence() {
if( geoFenceMarker != null ) {
Geofence geofence = createGeofence( geoFenceMarker.getPosition(), GEOFENCE_RADIUS );
GeofencingRequest geofenceRequest = createGeofenceRequest( geofence );
addGeofence( geofenceRequest );
}
}
private static final long GEO_DURATION = 60 * 60 * 1000;
private static final String GEOFENCE_REQ_ID = "firstGeoFence";
private static final float GEOFENCE_RADIUS = 2000.0f; // in meters
// Create a Geofence Request
private GeofencingRequest createGeofenceRequest(Geofence geofence ) {
return new GeofencingRequest.Builder()
.setInitialTrigger( GeofencingRequest.INITIAL_TRIGGER_ENTER )
.addGeofence( geofence )
.build();
}
// Create a Geo fence
private Geofence createGeofence(LatLng latLng, float radius ) {
return new Geofence.Builder()
.setRequestId(GEOFENCE_REQ_ID)
.setCircularRegion( latLng.latitude, latLng.longitude, radius)
.setExpirationDuration( GEO_DURATION )
.setTransitionTypes( Geofence.GEOFENCE_TRANSITION_ENTER
| Geofence.GEOFENCE_TRANSITION_EXIT )
.build();
}
public void addGeofence(GeofencingRequest request) {
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
request,
createGeofencePendingIntent()
).setResultCallback(this);
}
@Override
public void onResult(@NonNull Result result) {
if ( result.getStatus().isSuccess() ) {
drawGeofence();
}
}
private final int GEOFENCE_REQ_CODE = 0;
private PendingIntent createGeofencePendingIntent() {
if ( geoFencePendingIntent != null )
return geoFencePendingIntent;
Intent intent = new Intent( this, GeofenceTrasitionService.class);
return PendingIntent.getService(
this, GEOFENCE_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT );
}
您还必须在活动中实现ResultCallback,它将覆盖onResult方法
此类将处理通知:
// Draw Geofence circle on GoogleMap
private Circle geoFenceLimits;
private void drawGeofence() {
if ( geoFenceLimits != null )
geoFenceLimits.remove();
CircleOptions circleOptions = new CircleOptions()
.center( geoFenceMarker.getPosition())
.strokeColor(Color.argb(50, 70,70,70))
.fillColor( Color.argb(100, 150,150,150) )
.radius( GEOFENCE_RADIUS );
geoFenceLimits = map.addCircle( circleOptions );
}
公共类GeofenceTrasitionService扩展了IntentService{
私有静态最终字符串标记=GeofenceTrasitionService.class.getSimpleName();
公共静态最终国际地理围栏通知ID=0;
公共地理围栏传输服务(){
超级(标签);
}
@凌驾
受保护的手部内容无效(意图){
//检索地理围栏意图
GeofencingEvent GeofencingEvent=GeofencingEvent.fromIntent(intent);
//处理错误
if(geofencingEvent.hasError()){
String errorMsg=getErrorString(geofencingEvent.getErrorCode());
返回;
}
//恢复地理位置
int geoFenceTransition=geofencingEvent.getGeofenceTransition();
//检查转换类型是否正确
如果(geoFenceTransition==Geofence.Geofence\u TRANSITION\u输入||
geoFenceTransition==Geofence.Geofence_TRANSITION_EXIT){
//获取触发的地理围栏
List triggeringGeofences=geofencingEvent.getTriggeringGeofences();
//创建接收到Geofines的详细信息
字符串geofenceTransitionDetails=getGeofenceTrasitionDetails(geoFenceTransition,triggeringGeofences);
//以字符串形式发送通知详细信息
发送通知(geofenceTransitionDetails);
}
}
//创建接收到Geofines的详细信息
私有字符串getGeofenceTrasitionDetails(int-geoFenceTransition,List-triggeringGeofences){
//获取触发的每个地理围栏的ID
ArrayList triggeringGeofencesList=新建ArrayList();
用于(地理围栏:触发地理围栏){
triggeringgeofensslist.add(geofense.getRequestId());
}
字符串状态=空;
如果(geoFenceTransition==Geofence.Geofence\u TRANSITION\u ENTER)
状态=“进入”;
else if(geoFenceTransition==Geofence.Geofence\u TRANSITION\u EXIT)
状态=“正在退出”;
返回状态+TextUtils.join(“,”,triggeringGeofencesList);
}
//发送通知
私有void sendNotification(字符串msg){
//开始主要活动的意图
Intent notificationIntent=新意图(getApplicationContext(),MapActivity.class);
TaskStackBuilder stackBuilder=TaskStackBuilder.create(此);
addParentStack(MapActivity.class);
stackBuilder.addNextIntent(通知意图);
PendingEvent NotificationPendingEvent=stackBuilder.GetPendingEvent(0,PendingEvent.FLAG_UPDATE_CURRENT);
//创建和发送通知
通知经理通知=
(NotificationManager)getSystemService(Context.NOTIFICATION_服务);
通知(
土工围栏通知ID,
createNotification(消息,NotificationPendingContent));
}
//创建通知
私有通知createNotification(字符串消息,PendingEvent NotificationPendingEvent){
NotificationCompat.Builder notificationBuilder=新建NotificationCompat.Builder(此);
通知生成器
.setSmallIcon(R.mipmap.ic_启动器)
.setColor(颜色.红色)
.setContentTitle(msg)
.setContentText(“地理围栏通知!”)
.setContentIntent(NotificationPendingContent)
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_vibration | Notification.DEFAULT_SOUND)
.setAutoCancel(真);
返回notificationBuilder.build();
}
//处理错误
私有静态字符串getErrorString(int errorCode){
开关(错误代码){
案例GeofenceStatusCodes.GEOFENCE\u不可用:
返回“地理围栏不可用”;
案例GeofenceStatusCodes.GEOFENCE\u太多\u GEOFENCE:
返回“太多地理围栏”;
案例GeofenceStatusCodes.GEOFENCE\u太多\u未决\u意图:
返回“太多未决意图”;
违约:
返回“未知错误”;
}
}
}
在清单文件中:
public class GeofenceTrasitionService extends IntentService {
private static final String TAG = GeofenceTrasitionService.class.getSimpleName();
public static final int GEOFENCE_NOTIFICATION_ID = 0;
public GeofenceTrasitionService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
// Retrieve the Geofencing intent
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
// Handling errors
if ( geofencingEvent.hasError() ) {
String errorMsg = getErrorString(geofencingEvent.getErrorCode() );
return;
}
// Retrieve GeofenceTrasition
int geoFenceTransition = geofencingEvent.getGeofenceTransition();
// Check if the transition type
if ( geoFenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
geoFenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT ) {
// Get the geofence that were triggered
List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
// Create a detail message with Geofences received
String geofenceTransitionDetails = getGeofenceTrasitionDetails(geoFenceTransition, triggeringGeofences );
// Send notification details as a String
sendNotification( geofenceTransitionDetails );
}
}
// Create a detail message with Geofences received
private String getGeofenceTrasitionDetails(int geoFenceTransition, List<Geofence> triggeringGeofences) {
// get the ID of each geofence triggered
ArrayList<String> triggeringGeofencesList = new ArrayList<>();
for ( Geofence geofence : triggeringGeofences ) {
triggeringGeofencesList.add( geofence.getRequestId() );
}
String status = null;
if ( geoFenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER )
status = "Entering ";
else if ( geoFenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT )
status = "Exiting ";
return status + TextUtils.join( ", ", triggeringGeofencesList);
}
// Send a notification
private void sendNotification( String msg ) {
// Intent to start the main Activity
Intent notificationIntent = new Intent(getApplicationContext(), MapActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MapActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Creating and sending Notification
NotificationManager notificatioMng =
(NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE );
notificatioMng.notify(
GEOFENCE_NOTIFICATION_ID,
createNotification(msg, notificationPendingIntent));
}
// Create a notification
private Notification createNotification(String msg, PendingIntent notificationPendingIntent) {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder
.setSmallIcon(R.mipmap.ic_launcher)
.setColor(Color.RED)
.setContentTitle(msg)
.setContentText("Geofence Notification!")
.setContentIntent(notificationPendingIntent)
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
.setAutoCancel(true);
return notificationBuilder.build();
}
// Handle errors
private static String getErrorString(int errorCode) {
switch (errorCode) {
case GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE:
return "GeoFence not available";
case GeofenceStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES:
return "Too many GeoFences";
case GeofenceStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS:
return "Too many pending intents";
default:
return "Unknown error.";
}
}
}
我理解这一点。但我想检查用户的当前位置是否在geofence中。这是我想在服务中执行的操作,然后通知用户他是否在geofence中。记住,我通过在地图上标记点来创建geofence,然后通过光线投射算法检查用户是否在geofence中。您可以做的是,在地图上添加一个标记,单击并通过创建一个createGeofence区域来围绕该位置开始地理围栏。@DaniyalIrfan检查新答案!!是的,兄弟,我知道做geofence的方法。但我的要求是在地图上任何形状的运行时创建geofence。不仅仅是在圆圈中,所以我必须自己实现每一件事情。。
<service android:name="com.jaspreet.mapdemo.geoFence.GeofenceTrasitionService" />