create android geofence in background without crashing

喜夏-厌秋 提交于 2019-12-25 02:45:14

问题


I currently have an IntentService that receives gcm messages with lat,lng infos and I would like to register a geofence in the background without a foreground app. I already tried putting the working (in an activity) code into the IntentService but I get a nullpointerexception and I have no idea why.

@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();
    }

this is the error message:

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)

Any ideas or tips how I could achieve this?


回答1:


Initialize mCurrentGeofences like this:

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

Instead of just:

List<Geofence> mCurrentGeofences; 


来源:https://stackoverflow.com/questions/22392732/create-android-geofence-in-background-without-crashing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!