[英]Android developer Json & Pubnub
嗨,我写了一个代码来发布带有 Pubnub 频道的 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 频道接收 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();
}
如何从我的频道中获取我的 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();
}
}
如果您有任何其他问题,请告诉我!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.