Frank Frank - 1 month ago 21
Android Question

PubNub not publishing from Service

I've previously used PubNub from a background service to publish location updates on android. I wish to use it for a different project and wrote a simple service to test the new API. However, publishing always fails and I am unable to pinpoint why.

Here is the service code:

public class MessageService extends Service {
private static final String TAG = "MessageService";
private PubNub pubnub;
private Timer timer = new Timer();

public MessageService() {
PNConfiguration config = new PNConfiguration();
config.setPublishKey("pub_key_removed_for_privacy");
pubnub = new PubNub(config);
}

TimerTask task = new TimerTask() {
@Override
public void run() {
pubnub.publish()
.channel("demo")
.message("hello from service")
.async(new PNCallback<PNPublishResult>() {
@Override
public void onResponse(PNPublishResult result, PNStatus status) {
if (status.isError()) {
Log.e(TAG, "Publish failed");
} else {
Log.d(TAG, "Publish successful");
}
}
});
}
};

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
timer.schedule(task, 0, 5000);

return START_REDELIVER_INTENT;
}

@Override
public void onDestroy() {
super.onDestroy();

timer.cancel();
}

@Override
public IBinder onBind(Intent intent) {
return binder;
}

private final IBinder binder = new ServiceBinder();

public class ServiceBinder extends Binder {
public MessageService getService() {
return MessageService.this;
}
}
}


In the MainActivity, I simply call startService() and watch the logs and I always get the failure message. I do have the internet and network_state permissions in my manifest and can't think of any other reasons why this is not working. Any suggestions?

Answer

PubNub Subscribe Key is Always Required

You are initializing PubNub with only the publish key. The subscribe key is always required when you config/init PubNub, even if you are only going to publish.

If you do not init with a subscribe key, or it is invalid (typo or disabled) then you will get a 400 - Invalid Subscribe Key error response when you try to execute a PubNub operation (subscribe, publish, history, etc.)

public MessageService() {
    PNConfiguration config = new PNConfiguration();
    config.setPublishKey("your-pub-key");
    config.setSubscribeKey("your-sub-key");
    pubnub = new PubNub(config);
}