【问题标题】:create android geofence in background without crashing在后台创建 android 地理围栏而不会崩溃
【发布时间】:2014-03-13 22:54:37
【问题描述】:

我目前有一个 IntentService,它接收带有 lat、lng 信息的 gcm 消息,我想在没有前台应用程序的情况下在后台注册地理围栏。我已经尝试将工作(在活动中)代码放入 IntentService 但我得到一个空指针异常,我不知道为什么。

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {  
                Double lat = Double.parseDouble(extras.getString("lat"));
                Double lng = Double.parseDouble(extras.getString("lng"));
                Float radius = Float.parseFloat("600");
                createGeofences(lat,lng,radius);

        }
    }
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

public void createGeofences(Double lat, Double lng, Float radius) {


    mRequestType = GeofenceUtils.REQUEST_TYPE.ADD;
    SimpleGeofence mGeofence = new SimpleGeofence(
        "1",
        lat,
        lng,
        radius,
        GEOFENCE_EXPIRATION_IN_MILLISECONDS,
        Geofence.GEOFENCE_TRANSITION_ENTER);

    // Store this flat version in SharedPreferences
    //mPrefs.setGeofence("1", mGeofence);


    /*
     * Add Geofence objects to a List. toGeofence()
     * creates a Location Services Geofence object from a
     * flat object
     */
    mCurrentGeofences.add(mGeofence.toGeofence());

    try {
        mGeofenceRequester.addGeofences(mCurrentGeofences);
    } catch (UnsupportedOperationException e) {
        Toast.makeText(this, R.string.add_geofences_already_requested_error,
                    Toast.LENGTH_LONG).show();
    }

这是错误信息:

java.lang.NullPointerException
at com.app.portalalert.GcmIntentService.createGeofences(GcmIntentService.java:142)
at com.app.portalalert.GcmIntentService.onHandleIntent(GcmIntentService.java:85)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.os.HandlerThread.run(HandlerThread.java:61)

我有什么想法或技巧可以实现这一目标吗?

【问题讨论】:

  • GcmIntentService.java:142 有什么内容?
  • mCurrentGeofences.add(mGeofence.toGeofence());
  • 你在哪里初始化mCurrentGeofences
  • 全局:列出 mCurrentGeofences;

标签: java android service nullpointerexception android-geofence


【解决方案1】:

像这样初始化 mCurrentGeofences:

List<Geofence> mCurrentGeofences = new ArrayList<Geofence>(); 

不仅仅是:

List<Geofence> mCurrentGeofences; 

【讨论】:

  • 我现在得到了同样的错误,但是这行:mGeofenceRequester.addGeofences(mCurrentGeofences);
  • 你是如何初始化 mGeofenceRequester 的?
  • private GeofenceRequester mGeofenceRequester;
  • 那么,如何正确初始化mGeofenceRequester呢?实例化地理围栏请求? mGeofenceRequester = new GeofenceRequester(this);不起作用。
  • 谢谢你追了一天。你能解释一下有什么区别吗?在我将此代码移入服务之前,这对我来说不是问题。
猜你喜欢
  • 2016-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-01
  • 1970-01-01
  • 2021-11-24
  • 2019-06-18
相关资源
最近更新 更多