草庐IT

Android Geofencing - 没有 future 的 Intent ?

coder 2023-11-27 原文

我有一个奇怪的问题。

我使用 Google 服务实现了地理围栏。 (下面的实现) 在我的设备(三星 Galaxy S 和 Moto X)上,它们运行完美。在其他一些设备(HTC Incredible S、Galaxy Note)上,我没有收到任何转换 Intent 。绝不。凭借出色、准确的 GPS 定位,站在栅栏中间。没有什么。日志中没有任何可疑之处。没有错误,没有警告。没有 itents 来,服务没有启动。

有没有人见过这样的东西? (这很奇怪,因为我看不到可以工作的设备和不能工作的设备之间有任何联系。它不是制造商,不是 Android 版本,Play 服务在所有这些设备上都是最新的。)

实现:

list :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.package"
android:installLocation="auto"
android:versionCode="17"
android:versionName="1.1" >

<uses-sdk
    android:minSdkVersion="7"
    android:targetSdkVersion="19" />

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />


<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <activity
        android:name="test.package.MainActivity"
        android:label="Compass"
        android:screenOrientation="portrait" />

    <service android:name="test.package.services.geofences.ShowNotificationService"
            android:label="@string/app_name"
            android:exported="false"/>

    <receiver android:name="test.package.services.geofences.UpdateGeofences">
        <intent-filter>
            <action android:name="test.package.updateGeofecnes"/>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

更新地理围栏:

 public class UpdateGeofences extends BroadcastReceiver implements
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener,
        LocationClient.OnAddGeofencesResultListener,
        DataUpdateCallback {

    private LocationClient mLocationClient;
    private Context ctx;

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("NOTICE", "Updating Geofences");
        ctx = context;
        mLocationClient = new LocationClient(context, this, this);
        mLocationClient.connect();
    }

    @Override
    public void onConnected(Bundle bundle) {
        GeofenceProvider geofenceProvider = new GeofenceProvider(ctx);
        geofenceProvider.open();

        //reactivate geofences
        List<Geofence> geofences = geofenceProvider.getActiveGeofences(mLocationClient.getLastLocation());
        Intent intent = new Intent(ctx, ShowNotificationService.class);
        PendingIntent pendingIntent = PendingIntent.getService(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        if (geofences.size() > 0) mLocationClient.addGeofences(geofences, pendingIntent, this);
        else mLocationClient.disconnect();
    }

    @Override
    public void onAddGeofencesResult(int i, String[] strings) {
        // If adding the geofences was successful
        if (LocationStatusCodes.SUCCESS != i) {
            Log.e("Geofences", "Error adding geofences: "+ Arrays.toString(strings)+ " Code: "+i);
        }
        mLocationClient.disconnect();
    }    
}

显示通知服务:

    public class ShowNotificationService extends IntentService {

    public ShowNotificationService() {
        super("ReceiveTransitionsIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d("NOTICE", "Android geofence notification!");
        if (LocationClient.hasError(intent)) {
            int errorCode = LocationClient.getErrorCode(intent);
            Log.e("ReceiveTransitionsIntentService", "Location Services error: " + Integer.toString(errorCode));
            Crashlytics.logException(new RuntimeException("Location Services error: "+errorCode));
        } else {
            int transitionType = LocationClient.getGeofenceTransition(intent);
            if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER) { //ak vstupujem pozriem sa ci uz sa mi to nevyhodilo dnes
                List<Geofence> triggerList = LocationClient.getTriggeringGeofences(intent);
                Log.d("NOTICE", "Transition Enter");
                GeofenceProvider mProvider = new GeofenceProvider(this);
                mProvider.open();
                try {
                    for (Geofence geofence : triggerList) {
                        String id = geofence.getRequestId();
                        String[] data = id.split(MyGeofence.delimiter);
                        Log.d("NOTICE", "Show notification: "+id);
                        if (data.length != 3) {
                            Crashlytics.logException(new RuntimeException("Invalid geofence id: " + id + "Data: "+ Arrays.toString(data)));
                            continue;
                        }
                        if (mProvider.updateLastFire(Integer.valueOf(data[2]))) {
                            NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
                            builder.setContentTitle(data[0]);
                            builder.setContentText(data[1]);
                            builder.setSmallIcon(R.drawable.noticon);
                            Intent result = new Intent(this, CompassActivity.class);
                            PendingIntent pendingResult = PendingIntent.getActivity(this, 0, result, PendingIntent.FLAG_UPDATE_CURRENT);
                            builder.setContentIntent(pendingResult);
                            builder.setOngoing(false);
                            builder.setAutoCancel(true);
                            Notification not = builder.build();
                            not.defaults = Notification.DEFAULT_ALL;
                            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                            int notID = Integer.valueOf(data[2]);
                            mNotificationManager.notify(notID, not);
                        }
                    }
                } catch (Exception e) {
                    Crashlytics.logException(e);
                    e.printStackTrace();
                } finally {
                    mProvider.close();
                }

            } else if(transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {    //ak odchadzam, oznacim to patricne v db
                List<Geofence> triggerList = LocationClient.getTriggeringGeofences(intent);
                Log.d("NOTICE", "Transition leave");
                GeofenceProvider mProvider = new GeofenceProvider(this);
                mProvider.open();
                try {
                    for (Geofence geofence : triggerList) {
                        String id = geofence.getRequestId();
                        String[] data = id.split(MyGeofence.delimiter);
                        if (data.length != 3) {
                            Crashlytics.logException(new RuntimeException("Invalid geofence id: " + id + "Data: "+ Arrays.toString(data)));
                            continue;
                        }
                        mProvider.invalidateLastFire(Integer.valueOf(data[2]));
                        Log.d("NOTICE", "Invalidate last fire: "+id);
                    }
                } catch (Exception e) {
                    Crashlytics.logException(e);
                    e.printStackTrace();
                } finally {
                    mProvider.close();
                }

            } else {    // An invalid transition was reported
                Log.e("ReceiveTransitionsIntentService", "Geofence transition error: " + Integer.toString(transitionType));
                Crashlytics.logException(new RuntimeException("Invalid geofence transition"));
            }
        }
    }
}

在 UpdateGeofences 中,我省略了连接到 PlayServices 所需的方法,因为它们基本上是从演示应用程序复制的,我在其他地方成功地使用了它们...

Main Activity 是无关紧要的,它只是在每次启动时发送广播来启动 UpdateGeofences。

GeofenceProvider 也不是问题,我在其他地方使用相同的代码没有问题。

最佳答案

最终,我通过在 ShowNofiticationService 中设置 exported="true"设法解决了这个问题。

像这样:

<service android:name="test.package.services.geofences.ShowNotificationService"
        android:label="@string/app_name"
        android:exported="true"/>

似乎 Intent 是由 ID 错误的进程触发的,这导致了安全错误。不确定为什么会发生这种情况......

关于Android Geofencing - 没有 future 的 Intent ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21090674/

有关Android Geofencing - 没有 future 的 Intent ?的更多相关文章

  1. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  2. ruby-on-rails - rails 目前在重启后没有安装 - 2

    我有一个奇怪的问题:我在rvm上安装了ruby​​onrails。一切正常,我可以创建项目。但是在我输入“railsnew”时重新启动后,我有“程序'rails'当前未安装。”。SystemUbuntu12.04ruby-v"1.9.3p194"gemlistactionmailer(3.2.5)actionpack(3.2.5)activemodel(3.2.5)activerecord(3.2.5)activeresource(3.2.5)activesupport(3.2.5)arel(3.0.2)builder(3.0.0)bundler(1.1.4)coffee-rails(

  3. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  4. 没有类的 Ruby 方法? - 2

    大家好!我想知道Ruby中未使用语法ClassName.method_name调用的方法是如何工作的。我头脑中的一些是puts、print、gets、chomp。可以在不使用点运算符的情况下调用这些方法。为什么是这样?他们来自哪里?我怎样才能看到这些方法的完整列表? 最佳答案 Kernel中的所有方法都可用于Object类的所有对象或从Object派生的任何类。您可以使用Kernel.instance_methods列出它们。 关于没有类的Ruby方法?,我们在StackOverflow

  5. ruby-on-rails - Rails 3,嵌套资源,没有路由匹配 [PUT] - 2

    我真的为这个而疯狂。我一直在搜索答案并尝试我找到的所有内容,包括相关问题和stackoverflow上的答案,但仍然无法正常工作。我正在使用嵌套资源,但无法使表单正常工作。我总是遇到错误,例如没有路线匹配[PUT]"/galleries/1/photos"表格在这里:/galleries/1/photos/1/edit路线.rbresources:galleriesdoresources:photosendresources:galleriesresources:photos照片Controller.rbdefnew@gallery=Gallery.find(params[:galle

  6. ruby-on-rails - 有没有办法为 CarrierWave/Fog 设置上传进度指示器? - 2

    我在Rails应用程序中使用CarrierWave/Fog将视频上传到AmazonS3。有没有办法判断上传的进度,让我可以显示上传进度如何? 最佳答案 CarrierWave和Fog本身没有这种功能;你需要一个前端uploader来显示进度。当我不得不解决这个问题时,我使用了jQueryfileupload因为我的堆栈中已经有jQuery。甚至还有apostonCarrierWaveintegration因此您只需按照那里的说明操作即可获得适用于您的应用的进度条。 关于ruby-on-r

  7. ruby - 没有类方法获取 Ruby 类名 - 2

    如何在Ruby中获取BasicObject实例的类名?例如,假设我有这个:classMyObjectSystem我怎样才能使这段代码成功?编辑:我发现Object的实例方法class被定义为returnrb_class_real(CLASS_OF(obj));。有什么方法可以从Ruby中使用它? 最佳答案 我花了一些时间研究irb并想出了这个:classBasicObjectdefclassklass=class这将为任何从BasicObject继承的对象提供一个#class您可以调用的方法。编辑评论中要求的进一步解释:假设你有对象

  8. ruby - 没有轨道的 ActiveRecord 时区 - 2

    我在非Rails项目中使用ActiveRecord。在Rails中,我可以这样做:config.time_zone='EasternTime(US&Canada)'config.active_record.default_timezone='EasternTime(US&Canada)'但如果我不使用rails,我该如何设置时区? 最佳答案 ActiveRecord::Base.default_timezone='EasternTime(US&Canada)' 关于ruby-没有轨道的A

  9. ruby-on-rails - 没有这样的文件或目录 - 用 Mini Magick 识别 - 2

    在我让另一个人重做我的前端UI之前,我的Rails应用程序运行平稳。我已经尝试解决此错误3天了。这是错误:Nosuchfileordirectory-identifyExtractedsource(aroundline#59):575859606162@post=Post.find(params[:id])authorize@postif@post.update_attributes(post_params)flash[:notice]="Postwasupdated."redirect_to[@topic,@post]else{"utf8"=>"✓","_method"=>"patc

  10. ruby-on-rails - 没有参数的 `<<`(小于两倍)是什么意思? - 2

    我在一个我想在formtasticGem中覆盖的方法中找到了这个。该方法如下所示:defto_htmlinput_wrappingdohidden_field_html是什么意思?在第三行做什么?我知道它对数组有什么作用,但在这里我不知道。 最佳答案 你可以这样读:hidden_field_htmllabel_with_nested_checkbox是连接到hidden_​​field_html末尾的参数-为了“清晰”,他们将其分成两行 关于ruby-on-rails-没有参数的`

随机推荐