我正在开发带有今年发布的地理围栏的 android 应用程序。
我的理解是当用户进入(或离开)围栏时它应该触发 onHandleIntent 方法但是我很难触发到 onHandleIntent 方法
我已经检查了 3 天来弄清楚,但我最终还是做不到。
所以我需要任何人的帮助。
这是我的代码,我真的希望有人能帮助我。
///// MainActivity
package com.example.geofence;
import java.util.ArrayList;
import java.util.List;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationClient.OnAddGeofencesResultListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationStatusCodes;
public class MainActivity extends FragmentActivity implements
ConnectionCallbacks,
OnConnectionFailedListener,
OnAddGeofencesResultListener
{
private IntentFilter mIntentFilter;
private LocationClient locationClient;
private LocationRequest locatRequest;
private PendingIntent intent;
private List<Geofence> mGeoList;
private Context mContext;
private Geofence companyLocation;
private GeofenceSampleReceiver mBroadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
locatRequest = null;
mGeoList = new ArrayList<Geofence>();
intent = null;
locationClient = new LocationClient(this,this,this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction("com.example.geofence.ACTION_GEOFENCES_ADDED");
mIntentFilter.addCategory("com.example.geofence.CATEGORY_LOCATION_SERVICES");
mBroadcastReceiver = new GeofenceSampleReceiver();
}
@Override
protected void onStart() {
companyLocation = new Geofence.Builder()
.setRequestId("1")
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
.setCircularRegion(
49.220531, -122.986772, (float)50)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build();
mGeoList.add(companyLocation);
locationClient.connect();
super.onStart();
}
@Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
intent = getTransitionPendingIntent();
locatRequest = LocationRequest.create();
locatRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
locatRequest.setInterval(5000);
try{
addGeofence();
}catch(UnsupportedOperationException e){
Toast.makeText(this, "add_geofences_already_requested_error",
Toast.LENGTH_LONG).show();
}
// locationClient.requestLocationUpdates(locatRequest, intent);
}
public void addGeofence(){
locationClient.addGeofences(mGeoList,intent , this);
}
private PendingIntent getTransitionPendingIntent() {
// Create an explicit Intent
Intent localIntent = new Intent(this,
ReceiveTransitionsIntentService.class);
/*
* Return the PendingIntent
*/
return PendingIntent.getService(
this,
0,
localIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
@Override
protected void onStop() {
locationClient.disconnect();
super.onStop();
}
@Override
public void onAddGeofencesResult(int statusCode, String[] geofenceRequestIds) {
// TODO Auto-generated method stub
Intent broadcastIntent = new Intent();
if(LocationStatusCodes.SUCCESS == statusCode){
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
broadcastIntent.setAction("com.example.android.geofence.ACTION_GEOFENCES_ADDED")
.addCategory("com.example.android.geofence.CATEGORY_LOCATION_SERVICES")
.putExtra("com.example.android.geofence.EXTRA_GEOFENCE_STATUS","test");
}
else{
Toast.makeText(this, "AddGeoError", Toast.LENGTH_SHORT).show();
}
LocalBroadcastManager.getInstance(mContext).sendBroadcast(broadcastIntent);
}
@Override
public void onConnectionFailed(ConnectionResult arg0) { // TODO Auto-generated method stub
int code = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
switch(code){
case ConnectionResult.SERVICE_MISSING :{
Toast.makeText(this, "SERVICE_MISSING " + code + " ConnectionResult.SERVICE_MISSING " +ConnectionResult.SERVICE_MISSING, Toast.LENGTH_SHORT).show();
break;
}
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:{
Toast.makeText(this, "SERVICE_VERSION_UPDATE_REQUIRED " + code + " ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED " + ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED, Toast.LENGTH_SHORT).show();
break;
}
default:{
Toast.makeText(this, "start " + code, Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, mIntentFilter);
//locationClient.connect();
super.onResume();
}
@Override
public void onDisconnected() {
// TODO Auto-generated method stub
locationClient = null;
}
/*
* Handle results returned to this Activity by other Activities started with
* startActivityForResult(). In particular, the method onConnectionFailed() in
* GeofenceRemover and GeofenceRequester may call startResolutionForResult() to
* start an Activity that handles Google Play services problems. The result of this
* call returns here, to onActivityResult.
* calls
*/
@Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
}
/**
* Define a Broadcast receiver that receives updates from connection listeners and
* the geofence transition service.
*/
public class GeofenceSampleReceiver extends BroadcastReceiver {
/*
* Define the required method for broadcast receivers
* This method is invoked when a broadcast Intent triggers the receiver
*/
@Override
public void onReceive(Context context, Intent intent) {
// Check the action code and determine what to do
String action = intent.getAction();
// Intent contains information about errors in adding or removing geofences
if (TextUtils.equals(action, "com.example.geofence.ACTION_GEOFENCES_ADDED")) {
handleGeofenceStatus(context, intent);
// Intent contains information about a geofence transition
} else if (TextUtils.equals(action, "com.example.geofence.ACTION_GEOFENCE_TRANSITION")) {
handleGeofenceTransition(context, intent);
// The Intent contained an invalid action
} else {
Toast.makeText(context,"error", Toast.LENGTH_LONG).show();
}
}
/**
* If you want to display a UI message about adding or removing geofences, put it here.
*
* @param context A Context for this component
* @param intent The received broadcast Intent
*/
private void handleGeofenceStatus(Context context, Intent intent) {
}
/**
* Report geofence transitions to the UI
*
* @param context A Context for this component
* @param intent The Intent containing the transition
*/
private void handleGeofenceTransition(Context context, Intent intent) {
/*
* If you want to change the UI when a transition occurs, put the code
* here. The current design of the app uses a notification to inform the
* user that a transition has occurred.
*/
}
/**
* Report addition or removal errors to the UI, using a Toast
*
* @param intent A broadcast Intent sent by ReceiveTransitionsIntentService
*/
private void handleGeofenceError(Context context, Intent intent) {
}
}
}
///// ReceiveTransitionsIntentService
package com.example.geofence;
import java.util.List;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.LocationClient;
public class ReceiveTransitionsIntentService extends IntentService {
/**
* Sets an identifier for the service
*/
private Context mContext;
public ReceiveTransitionsIntentService(Context c) {
super("ReceiveTransitionsIntentService");
mContext =c;
}
/**
* Handles incoming intents
*@param intent The Intent sent by Location Services. This
* Intent is provided
* to Location Services (inside a PendingIntent) when you call
* addGeofences()
*/
@Override
protected void onHandleIntent(Intent intent) {
// First check for errors
//Toast.makeText(mContext, "onHandleIntent", Toast.LENGTH_LONG).show();
if (LocationClient.hasError(intent)) {
// Get the error code with a static method
int errorCode = LocationClient.getErrorCode(intent);
// Log the error
Log.e("ReceiveTransitionsIntentService",
"Location Services error: " +
Integer.toString(errorCode));
/*
* You can also send the error code to an Activity or
* Fragment with a broadcast Intent
*/
/*
* If there's no error, get the transition type and the IDs
* of the geofence or geofences that triggered the transition
*/
} else {
int transitionType = LocationClient.getGeofenceTransition(intent);
if(transitionType == Geofence.GEOFENCE_TRANSITION_ENTER ||
transitionType == Geofence.GEOFENCE_TRANSITION_EXIT){
List<Geofence> geofences = LocationClient.getTriggeringGeofences(intent);
String[] geofenceIds = new String [geofences.size()];
for(int i = 0; i <geofences.size(); i++){
geofenceIds[i] = geofences.get(i).getRequestId();
}
String ids = "1";
String transition = ((transitionType == Geofence.GEOFENCE_TRANSITION_ENTER ) ?"you are in":"you are out");
Toast.makeText(mContext, transition, Toast.LENGTH_LONG).show();
sendNotification(transition,ids);
//FOR THE NOTIFICATION.
//NotificationManager mNotificationManager =
// (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
}
}
private void sendNotification(String transitionType, String ids) {
// Create an explicit content Intent that starts the main Activity
Intent notificationIntent =
new Intent(getApplicationContext(),MainActivity.class);
// Construct a task stack
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the main Activity to the task stack as the parent
stackBuilder.addParentStack(MainActivity.class);
// Push the content Intent onto the stack
stackBuilder.addNextIntent(notificationIntent);
// Get a PendingIntent containing the entire back stack
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);
// Set the notification contents
builder.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(
transitionType+ " geofence_transition_notification_title " +ids)
.setContentIntent(notificationPendingIntent);
// Get an instance of the Notification manager
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Issue the notification
mNotificationManager.notify(0, builder.build());
}
}
最佳答案
你的半径设置为 50,这意味着你需要从你所在的位置移动 50 米才能触发 handle 。您是否尝试过使用 2m 半径?
关于android - 谷歌播放地理围栏 onHandleIntent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16797950/
最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路
如何只加载map边界内的标记gmaps4rails?当然,在平移和/或缩放后加载新的。与此直接相关的是,如何获取map的当前边界和缩放级别? 最佳答案 我是这样做的,我只在用户完成平移或缩放后替换标记,如果您需要不同的行为,请使用不同的事件监听器:在你看来(index.html.erb):{"zoom"=>15,"auto_adjust"=>false,"detect_location"=>true,"center_on_user"=>true}},false,true)%>在View的底部添加:functiongmaps4rail
我一直在寻找一种以编程方式或通过命令行将mp3转换为aac的方法,但没有成功。理想情况下,我有一段代码可以从我的Rails应用程序中调用,将mp3转换为aac。我安装了ffmpeg和libfaac,并能够使用以下命令创建aac文件:ffmpeg-itest.mp3-acodeclibfaac-ab163840dest.aac当我将输出文件的名称更改为dest.m4a时,它无法在iTunes中播放。谢谢! 最佳答案 FFmpeg提供AAC编码功能(如果您已编译它们)。如果您使用的是Windows,则可以从here获取完整的二进制文件。
我如何用ruby编写一个脚本,当从命令行执行时播放mp3文件(背景音乐)?我试过了run="mplayer#{"/Users/bhushan/resume/m.mp3"}-aosdl-vox11-framedrop-cache16384-cache-min20/100"system(run)但它也不起作用,以上是播放器特定的。如果用户没有安装mplayer怎么办。有没有更好的办法? 最佳答案 我一般都是这样pid=fork{exec'mpg123','-q',file} 关于ruby
我正在尝试从googleAPI下载client_secret.json。我正在执行https://developers.google.com/gmail/api/quickstart/ruby中列出的步骤.使用此向导在GoogleDevelopersConsole中创建或选择项目并自动启用API。在左侧边栏中,选择同意屏幕。选择电子邮件地址并输入产品名称(如果尚未设置),然后单击“保存”按钮。在左侧边栏中,选择凭据并点击创建新客户端ID。选择应用程序类型已安装应用程序,已安装应用程序类型为其他,然后单击“创建客户端ID”按钮。点击新客户端ID下的下载JSON按钮。将此文件移动到您的工作
在我的RubyonRails应用程序中,我使用的是Geocoder。它工作正常,但我的测试速度慢了十倍!我找到了一些解决方案,但我认为它们不是很清楚?有什么方法可以在测试环境中禁用Geocoder? 最佳答案 根据gemdocumentationonGithub,您可以在测试中使用测试查找,以避免执行实际请求:Geocoder.configure(:lookup=>:test)Geocoder::Lookup::Test.add_stub("NewYork,NY",[{'latitude'=>40.7143528,'longitud
我在查询中使用geo_distancefilter和tire,它工作正常:search.filter:geo_distance,:distance=>"#{request.distance}km",:location=>"#{request.lat},#{request.lng}"我预计结果会以某种方式包括到我用于过滤器的地理位置的计算距离。有没有办法告诉elasticsearch在响应中包含它,这样我就不必在ruby中为每个结果计算它?==更新==我在谷歌群组中的foundtheanswer:search.sortdoby"_geo_distance","location"=>"
我使用geokit和geokit-railsgemforrails有一段时间了,但我还没有找到答案的一个问题是如何找到一组点的计算聚合中心。我知道如何计算两点之间的距离,但不会超过2。我的理由是,我在同一个城市中有一系列的点……一切都完美的城市会有一个我可以使用的中心,但有些城市,比如柏林没有一个完美的中心。他们有多个中心,我只想使用我数据库中的所有地点列表来计算特定分布的中心。还有其他人遇到过这个问题吗?有什么建议吗?谢谢 最佳答案 之前从未使用过Geokit,这个操作背后的数学原理相对容易自己实现。假设这些点由纬度和经度组成,您
我想用Ruby编写脚本(使用gdatagem、rest-clientgem或直接使用Net::HTTP)使用gmail-userid/password对我的google文档进行身份验证,然后下载私有(private)列表文件和文件。GDatadocuments指南清楚地说明了如何获取公开可见的文档,但不清楚我如何在我的脚本中验证自己的身份以访问私有(private)文档。authenticationmethodstheyspecify所有这些似乎都需要人工干预,要么使用验证码,要么使用某种形式的OAuth/OpenID重定向。有什么方法可以只使用用户名/密码组合来访问我的私有(priv
这是2009年,早在2001年左右,ruby中的声音播放就没有好的绑定(bind)。有变化吗?我正在寻找可以控制原始声音或mp3、ogg和flac播放的东西。我的谷歌搜索已经枯竭。编辑:Linux、OSX,如果可能的话还有Windows。 最佳答案 您没有提到平台。Thispage描述了win32-sound库,它似乎至少支持WAV播放。对于一个更加平台中立的方式,Ruby/SDL为广受欢迎的SDL提供绑定(bind)图书馆。 关于ruby声音播放,我们在StackOverflow上找到