java - 在后台创建 Android 地理围栏而不崩溃

标签 java android service nullpointerexception android-geofence

我目前有一个 IntentService,它接收带有纬度、经度信息的 gcm 消息,我想在后台注册一个地理围栏,而无需前台应用程序。我已经尝试将工作(在 Activity 中)代码放入 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)

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

最佳答案

像这样初始化 mCurrentGeofences:

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

而不仅仅是:

List<Geofence> mCurrentGeofences; 

关于java - 在后台创建 Android 地理围栏而不崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22392732/

相关文章:

java - 如何从 Firebase 检索多项数据并将这些字符串合并在一起?

docker - 如何在 Docker-Compose 中一起使用主机网络和任何其他用户定义的网络?

Android 服务在启动时不起作用

java - JDK、JRE、Java : Version Confusion

JavaPairRDD 到 SPARK 中的数据集 <Row>

android - 未调用自定义 ArrayAdapter 的 getView

java - 有什么方法可以获取联系人应用程序的图标?

android - forceLayout() 在 Android 中是如何工作的

Android - 将 Activity 和小部件绑定(bind)到服务

java - 如何将人工智能写入我的应用程序