gpt4 book ai didi

Android 开发者 Json & Pubnub

转载 作者:行者123 更新时间:2023-11-29 00:21:40 25 4
gpt4 key购买 nike

您好,我写了一段代码来使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com