您好,我编写了一段代码来通过 Pubnub channel 发布 json:
pubnubMessage = new Pubnub("demo", "demo");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(id.map);
map = mapFragment.getMap();
LocationManager = new MyLocation(this);
LocationManager.initLocation();
callback = new LocationCallback() {
@Override
public void onNewLocation(Location location, String name) {
// *****sending the json string*****
JsonSendLocation jsonsendlocation = new JsonSendLocation();
jsonsendlocation.setLatitude(location.getLatitude());
jsonsendlocation.setLongtitude(location.getLongitude());
jsonsendlocation.setUsername(preferencesUtils.getName(
getApplicationContext(), preName, key));
Gson json = new Gson();
String jsonString = json.toJson(jsonsendlocation,
JsonSendLocation.class);
JSONObject ff;
try {
ff = new JSONObject(jsonString);
publishToPubnub(MY_CHANNEL, ff);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
现在我想从我的 Pubnub channel 接收 json 对象,我写道:
Pubnub recieve = new Pubnub("demo", "demo");
try {
recieve.subscribe("MyChannel", new com.pubnub.api.Callback() {
@Override
public void successCallback(String arg0, Object arg1) {
// TODO Auto-generated method stub
}
});
} catch (PubnubException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
如何从我的 channel 获取 json?
最佳答案
首先,您可以使用 Pubnub
对象的一个实例,只需将其声明为实例变量并在 onCreate
中实例化即可。然后您可以使用同一个 Pubnub 对象进行发布和订阅。
private Pubnub mPubNub;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.mPubNub = new Pubnub(Constants.PUBLISH_KEY, Constants.SUBSCRIBE_KEY);
subscribe();
// publish();
}
现在,当您在 successCallback
中接收对象时,Java 类型转换是完全有效的。我喜欢使用 instanceof
进行检查,这样如果消息由于某种原因无效,我的应用程序就不会崩溃。
public void subscribe(){
Callback callbacks = new Callback() {
@Override
public void successCallback(String channel, Object message) {
if (message instanceof JSONObject){
JSONObject json = (JSONObject) message;
// Handle JSON
} else if (message instanceof String){
String str = (String) message;
// Handle String
}
Log.d("PUBNUB", "Channel: " + channel + " Msg: " + message.toString());
}
};
try {
this.mPubNub.subscribe("MyChannel", callbacks);
} catch (PubnubException e) {
e.printStackTrace();
}
}
如果您有任何其他问题,请告诉我!
关于Android 开发者 Json 和 Pubnub,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22581017/