I am using Twilio Programmable chat APIs in android for 1 to 1 chat.
Following is my usecase:
1) I create a unique channel name
2) Check if the channel already exists or not
if channel exists:
user joins channel
else
create a channel with unique name
user joins channel
end
Now, what is happening is, when I am trying to join the channel, it is giving me the error: "Member already exists". So, at this point if I try to check the members of the channel, I get the Member object to be null.
I have 2 doubts at this point:
1) Shouldn't the user object contain this member if it is already a part of the channel?
2) If the user is already a part of the channel, I should be able to send mesages to the channel, by just adding the channelListener, which in this case is not happening.
I don't understand the issue. Following are my code snippets:
ChatClient.Properties props = new ChatClient.Properties.Builder()
.createProperties();
ChatClient.create(ChatActivity.this, accessToken, props, mChatClientCallback);
private CallbackListener<ChatClient> mChatClientCallback =
new CallbackListener<ChatClient>() {
#Override
public void onSuccess(ChatClient chatClient) {
mChatClient = chatClient;
//loadChannels();
Log.i(TAG, "Success creating Twilio Chat Client");
createOrJoinChannel();
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.i(TAG,"Error creating Twilio Chat Client: " + errorInfo.getMessage());
}
};
private void createOrJoinChannel(){
//Only SID or unique name of channel can be supplied as parameter
mChatClient.getChannels().getChannel(UNIQUE_CHANNEL_NAME, new CallbackListener<Channel>() {
#Override
public void onSuccess(Channel channel) {
if (channel != null) {
joinChannel(channel);
} else {
Log.i(TAG, "Error occurred in getting channel");
}
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.i(TAG,"Error retrieving channel: " + errorInfo.getMessage());
createChannel();
}
});
}
private void joinChannel(final Channel channel) {
Log.i(TAG, "inside join channel" + channel.getUniqueName());
Log.i(TAG, "channel status: " + channel.getStatus());
Members members = channel.getMembers();
if(members!=null){
ArrayList<Member> list = (ArrayList<Member>) members.getMembersList();
for(int i=0; i<list.size(); i++){
Log.i(TAG, "member " + i + list.get(i).getIdentity());
}
}else{
Log.i(TAG, "null object"); //Getting this even when I get
//"Member already exists" error
}
channel.join(new StatusListener() {
#Override
public void onSuccess() {
mGeneralChannel = channel;
mGeneralChannel.addListener(mDefaultChannelListener);
}
#Override
public void onError(ErrorInfo errorInfo) {
//Error joining channel: Member already exists
Log.i(TAG,"Error joining channel: " + errorInfo.getMessage());
});
}
private void createChannel(){
mChatClient.getChannels().createChannel(FRIENDLY_CHANNEL_NAME,
Channel.ChannelType.PUBLIC, new CallbackListener<Channel>() {
#Override
public void onSuccess(Channel channel) {
if (channel != null) {
setUniqueNameAndJoin(channel);
}
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.i(TAG,"chats: " + "Unique name could not be set: " + errorInfo.getMessage());
}
});
}
private void setUniqueNameAndJoin(final Channel channel){
channel.setUniqueName(UNIQUE_CHANNEL_NAME, new StatusListener() {
#Override
public void onSuccess() {
Log.i(TAG, "channel with unique name created " + channel.getUniqueName());
joinChannel(channel);
}
#Override
public void onError(ErrorInfo errorInfo) {
super.onError(errorInfo);
}
});
}
private ChannelListener mDefaultChannelListener = new ChannelListener() {
#Override
public void onMessageAdded(final Message message) {
Log.i(TAG, "Message added");
ChatActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// need to modify user interface elements on the UI thread
mMessages.add(message);
mMessagesAdapter.notifyItemInserted(mMessages.size()-1);
}
});
}
#Override
public void onMessageUpdated(Message message, Message.UpdateReason updateReason) {
Log.i(TAG, "Message updated: " + message.getMessageBody());
}
#Override
public void onMessageDeleted(Message message) {
Log.d(TAG, "Message deleted");
}
#Override
public void onMemberAdded(Member member) {
Log.i(TAG, "Member added: " + member.getIdentity());
}
#Override
public void onMemberUpdated(Member member, Member.UpdateReason updateReason) {
}
#Override
public void onMemberDeleted(Member member) {
}
#Override
public void onTypingStarted(Channel channel, Member member) {
}
#Override
public void onTypingEnded(Channel channel, Member member) {
}
#Override
public void onSynchronizationChanged(Channel channel) {
}
};
Can someone please explain to me, what am I doing wrong or what should be the correct way of doing things? Thanks in advance!
Twilio developer evangelist here.
You need to check the channel's status for your current user, using channel.getStatus(). There's a good example of this in the Android chat tutorial.
if (this.currentChannel.getStatus() == Channel.ChannelStatus.JOINED) {
// already in the channel, load the messages
} else {
// join the channel
}
Related
I have created a private channel, and joined the channel. I like to invite another user to join that channel and chat. To be clear, this should be a chat between two members only.
public class MainActivity extends AppCompatActivity {
/*
Change this URL to match the token URL for your Twilio Function
*/
final static String SERVER_TOKEN_URL = "https://example.com/twilio/token/";
final static String MY_CHANNEL_NAME = "testchat1234567810";
final static String TAG = "TwilioChat";
// Update this identity for each individual user, for instance after they login
private String mIdentity ;
private String accessToken;
private RecyclerView mMessagesRecyclerView;
private MessagesAdapter mMessagesAdapter;
private ArrayList<Message> mMessages = new ArrayList<>();
private EditText mWriteMessageEditText;
private Button mSendChatMessageButton;
private ChatClient mChatClient;
private Channel mGeneralChannel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMessagesRecyclerView = (RecyclerView) findViewById(R.id.messagesRecyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
// for a chat app, show latest at the bottom
layoutManager.setStackFromEnd(true);
mMessagesRecyclerView.setLayoutManager(layoutManager);
mMessagesAdapter = new MessagesAdapter();
mMessagesRecyclerView.setAdapter(mMessagesAdapter);
mWriteMessageEditText = (EditText) findViewById(R.id.writeMessageEditText);
mSendChatMessageButton = (Button) findViewById(R.id.sendChatMessageButton);
mSendChatMessageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
createOrJoinChannel();
if (mGeneralChannel != null) {
String messageBody = mWriteMessageEditText.getText().toString();
Message.Options options = Message.options().withBody(messageBody);
// mGeneralChannel.getMembers().add();
Members members = mGeneralChannel.getMembers();
if (members != null) {
ArrayList<Member> list = (ArrayList<Member>) members.getMembersList();
for (int i = 0; i < list.size(); i++) {
Log.i(TAG, "member " + i + list.get(i).getIdentity());
}
}
mGeneralChannel.getMembers().inviteByIdentity("user1#gmail.com", new StatusListener() {
#Override
public void onSuccess() {
Log.d(TAG, "User Invited on send!");
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.i(TAG, "chats: inviting user" + errorInfo.getMessage());
}
});
mGeneralChannel.getMembersCount(new CallbackListener<Long>() {
#Override
public void onSuccess(Long aLong) {
Log.e("member count >>", aLong + "");
}
});
mGeneralChannel.getMessages().sendMessage(options, new CallbackListener<Message>() {
#Override
public void onSuccess(Message message) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Message created");
// need to modify user interface elements on the UI thread
mWriteMessageEditText.setText("");
}
});
}
});
}
}
});
retrieveAccessTokenfromServer();
}
private void retrieveAccessTokenfromServer() {
String deviceId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
Log.e("deviceid >>",deviceId);
String tokenURL = SERVER_TOKEN_URL + deviceId;
Ion.with(this)
.load(tokenURL)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
Log.e("result >>", result.toString() + "");
if (e == null) {
mIdentity = result.get("identity").getAsString();
accessToken = result.get("token").getAsString();
setTitle(mIdentity);
ChatClient.Properties.Builder builder = new ChatClient.Properties.Builder();
// ChatClient.setLogLevel(Log.VERBOSE);
ChatClient.Properties props = builder.createProperties();
ChatClient.create(MainActivity.this, accessToken, props, mChatClientCallback);
} else {
Toast.makeText(MainActivity.this,
R.string.error_retrieving_access_token, Toast.LENGTH_SHORT)
.show();
}
}
});
}
private CallbackListener<ChatClient> mChatClientCallback =
new CallbackListener<ChatClient>() {
#Override
public void onSuccess(ChatClient chatClient) {
mChatClient = chatClient;
// createOrJoinChannel();
// loadChannels();
Log.d(TAG, "Success creating Twilio Chat Client");
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.e(TAG, "Error creating Twilio Chat Client: " + errorInfo.getMessage());
}
};
private void createOrJoinChannel() {
//Only SID or unique name of channel can be supplied as parameter
mChatClient.getChannels().getChannel(MY_CHANNEL_NAME, new CallbackListener<Channel>() {
#Override
public void onSuccess(Channel channel) {
if (channel != null) {
if (channel.getStatus() == Channel.ChannelStatus.JOINED) {
// already in the channel, load the messages
mGeneralChannel = channel;
mGeneralChannel.addListener(mDefaultChannelListener);
} else if (channel.getStatus() == Channel.ChannelStatus.NOT_PARTICIPATING) {
// already in the channel, load the messages
mGeneralChannel = channel;
mGeneralChannel.addListener(mDefaultChannelListener);
} else {
// join the channel
joinChannel(channel);
}
} else {
Log.i(TAG, "Error occurred in getting channel");
}
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.i(TAG, "Error retrieving channel: " + errorInfo.getMessage());
createChannel();
}
});
}
private void joinChannel(final Channel channel) {
Log.i(TAG, "inside join channel" + channel.getUniqueName());
Log.i(TAG, "channel status: " + channel.getStatus());
Members members = channel.getMembers();
if (members != null) {
ArrayList<Member> list = (ArrayList<Member>) members.getMembersList();
for (int i = 0; i < list.size(); i++) {
Log.i(TAG, "member " + i + list.get(i).getIdentity());
}
} else {
Log.i(TAG, "null object"); //Getting this even when I get
//"Member already exists" error
}
channel.join(new StatusListener() {
#Override
public void onSuccess() {
mGeneralChannel = channel;
mGeneralChannel.addListener(mDefaultChannelListener);
}
#Override
public void onError(ErrorInfo errorInfo) {
//Error joining channel: Member already exists
Log.i(TAG, "Error joining channel: " + errorInfo.getMessage());
}
});
}
private void createChannel() {
mChatClient.getChannels().createChannel(MY_CHANNEL_NAME,
Channel.ChannelType.PUBLIC, new CallbackListener<Channel>() {
#Override
public void onSuccess(final Channel channel) {
if (channel != null) {
/* channel.getMembersCount(new CallbackListener<Long>() {
#Override
public void onSuccess(Long aLong) {
Log.e("member count >>",aLong+"");
}
});*/
channel.getMembers().inviteByIdentity("user1#gmail.com", new StatusListener() {
#Override
public void onSuccess() {
Log.d(TAG, "User Invited!");
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.i(TAG, "chats: inviting user" + errorInfo.getMessage());
}
});
channel.join(new StatusListener() {
#Override
public void onSuccess() {
}
});
setUniqueNameAndJoin(channel);
}
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.i(TAG, "chats: " + "Unique name could not be set: " + errorInfo.getMessage());
}
});
}
private void setUniqueNameAndJoin(final Channel channel) {
channel.setUniqueName(MY_CHANNEL_NAME, new StatusListener() {
#Override
public void onSuccess() {
Log.i(TAG, "channel with unique name created " + channel.getUniqueName());
joinChannel(channel);
}
#Override
public void onError(ErrorInfo errorInfo) {
super.onError(errorInfo);
}
});
}
private ChannelListener mDefaultChannelListener = new ChannelListener() {
#Override
public void onMessageAdded(final Message message) {
Log.d(TAG, "Message added");
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// need to modify user interface elements on the UI thread
mMessages.add(message);
mMessagesAdapter.notifyDataSetChanged();
}
});
}
#Override
public void onMessageUpdated(Message message, Message.UpdateReason updateReason) {
Log.d(TAG, "Message updated: " + message.getMessageBody());
}
#Override
public void onMessageDeleted(Message message) {
Log.d(TAG, "Message deleted");
}
#Override
public void onMemberAdded(Member member) {
Log.d(TAG, "Member added: " + member.getIdentity());
}
#Override
public void onMemberUpdated(Member member, Member.UpdateReason updateReason) {
Log.d(TAG, "Member updated: " + member.getIdentity());
}
#Override
public void onMemberDeleted(Member member) {
Log.d(TAG, "Member deleted: " + member.getIdentity());
}
#Override
public void onTypingStarted(Channel channel, Member member) {
Log.d(TAG, "Started Typing: " + member.getIdentity());
}
#Override
public void onTypingEnded(Channel channel, Member member) {
Log.d(TAG, "Ended Typing: " + member.getIdentity());
}
#Override
public void onSynchronizationChanged(Channel channel) {
}
};
class MessagesAdapter extends RecyclerView.Adapter<MessagesAdapter.ViewHolder> {
class ViewHolder extends RecyclerView.ViewHolder {
public TextView mMessageTextView;
public ViewHolder(TextView textView) {
super(textView);
mMessageTextView = textView;
}
}
public MessagesAdapter() {
}
#Override
public MessagesAdapter
.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
TextView messageTextView = (TextView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.message_text_view, parent, false);
return new ViewHolder(messageTextView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Message message = mMessages.get(position);
String messageText = String.format("%s: %s", message.getAuthor(), message.getMessageBody());
holder.mMessageTextView.setText(messageText);
}
#Override
public int getItemCount() {
return mMessages.size();
}
}
}
And also, I need to accept the invite. How it can be done?
I am getting always error while checking channel name like
mChatClient.getChannels().getChannel("one", new CallbackListener<Channel>() {
#Override
public void onSuccess(Channel channel) {
if (channel != null) {
joinChannel(channel);
} else {
mChatClient.getChannels().createChannel("one",
Channel.ChannelType.PUBLIC, new CallbackListener<Channel>() {
#Override
public void onSuccess(Channel channel) {
if (channel != null) {
joinChannel(channel);
}
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.e(TAG,"Error creating channel: " + errorInfo.getErrorText());
}
});
}
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.e(TAG,"Error retrieving channel: " + errorInfo.getErrorText());
}
});
in this always coming to error block only. May i know what is the wrong?
What you are doing is:
Checking if the channel is available or not.
If available check if the channel is null and if so create the channel.
If you look at the code you see you are doing the create in the onSuccess, however, if your channel can't be found, onSuccess is never triggered, so it won't try to create the channel.
What you should do instead is in the onError create the channel. (untested, might be some errors):
mChatClient.getChannels().getChannel("one", new CallbackListener<Channel>() {
#Override
public void onSuccess(Channel channel) {
joinChannel(channel);
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.e(TAG,"Error retrieving channel: " + errorInfo.getErrorText());
mChatClient.getChannels().createChannel("one", Channel.ChannelType.PUBLIC, new CallbackListener<Channel>() {
#Override
public void onSuccess(Channel channel) {
if (channel != null) {
joinChannel(channel);
}
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.e(TAG,"Error creating channel: " + errorInfo.getErrorText());
}
});
}
});
As already answered we need to create channel in onerror() but that would lead to creating new channel each time.
Reason behind creating new channel each time is because we are comparing with unique name in getchannel() method; whereas the one we set in createChannel() method is friendly name. Try setting uniquename of the channel on success. Alternately you may try this code:
mChatClient.getChannels().getChannel("general", new CallbackListener<Channel>() {
#Override
public void onSuccess(Channel channel) {
if (channel != null) {
joinChannel(channel);
}
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.e(TAG,"Error retrieving channel: " + errorInfo.getMessage());
mChatClient.getChannels().channelBuilder().withUniqueName("general").withType(Channel.ChannelType.PUBLIC).build(new CallbackListener<Channel>() {
#Override
public void onSuccess(Channel channel) {
if (channel != null) {
joinChannel(channel);
}
}
#Override
public void onError(ErrorInfo errorInfo) {
Log.e(TAG,"Error creating channel: " + errorInfo.getMessage());
}
});
}
});
I have created an application that implements app to app calling using Sinch. It works only when the caller knows the name of the recipient.
To overcome this Sinch suggested to use PubNub to get the user state. They also have a tutorial here. The problem is that tutorial is old and PubNub has updated their API since. I tried to implement the functionality using their new API on my own using their docs, but it is not working or more accurately I don't know how to do it.
My current code is:
public class LoggedUsers extends Activity {
private PubNub pubNub;
String name;
private ArrayList users;
private JSONArray loggedUserList;
ListView UserList;
TextView allUsers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_list);
allUsers = (TextView) findViewById(R.id.JSONFromPubNub);
SharedPreferences sp = getSharedPreferences("User_Details", MODE_APPEND);
try {
name = sp.getString("UserName", "");
} catch (NullPointerException e) {
}
final PNConfiguration pnc = new PNConfiguration();
pnc.setPublishKey("publish key");
pnc.setSubscribeKey("subscribe key");
pnc.setUuid(name);
pubNub = new PubNub(pnc);
users = new ArrayList<String>();
UserList = (ListView) findViewById(R.id.listView);
String user = getUserStatus();
allUsers.setText(user);
final ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), R.layout.single_item_list, users);
UserList.setAdapter(adapter);
pubNub.addListener(new SubscribeCallback() {
#Override
public void status(PubNub pubnub, PNStatus status) {
if (status.getCategory() == PNStatusCategory.PNUnexpectedDisconnectCategory) {
// This event happens when radio / connectivity is lost
HashMap <String,String> map = new HashMap();
map.put("State","Offline");
pubNub.setPresenceState().channels(Arrays.asList("CallingChannel1")).state(map).uuid(pnc.getUuid());
} else if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
// Connect event. You can do stuff like publish, and know you'll get it.
// Or just use the connected event to confirm you are subscribed for
// UI / internal notifications, etc
HashMap <String,String> map = new HashMap();
map.put("State","Online");
pubNub.setPresenceState().channels(Arrays.asList("CallingChannel1")).state(map).uuid(pnc.getUuid());
/* if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
pubnub.publish().channel("awesomeChannel").message("hello!!").async(new PNCallback<PNPublishResult>() {
#Override
public void onResponse(PNPublishResult result, PNStatus status) {
// Check whether request successfully completed or not.
if (!status.isError()) {
// Message successfully published to specified channel.
}
// Request processing failed.
else {
// Handle message publish error. Check 'category' property to find out possible issue
// because of which request did fail.
//
// Request can be resent using: [status retry];
}
}
});
}*/
} else if (status.getCategory() == PNStatusCategory.PNReconnectedCategory) {
HashMap <String,String> map = new HashMap();
map.put("State","Online");
pubNub.setPresenceState().channels(Arrays.asList("CallingChannel1")).state(map).uuid(pnc.getUuid());
// Happens as part of our regular operation. This event happens when
// radio / connectivity is lost, then regained.
} else if (status.getCategory() == PNStatusCategory.PNDecryptionErrorCategory) {
// Handle messsage decryption error. Probably client configured to
// encrypt messages and on live data feed it received plain text.
}
}
#Override
public void message(PubNub pubnub, PNMessageResult message) {
}
#Override
public void presence(PubNub pubnub, PNPresenceEventResult presence) {
}
});
}
public String getUserStatus(){
final StringBuilder allUsers = new StringBuilder();
pubNub.subscribe().channels(Arrays.asList("CallingChannel1")).withPresence().execute();
pubNub.hereNow()
// tailor the next two lines to example
.channels(Arrays.asList("CallingChannel1"))
.includeState(true)
.includeUUIDs(true)
.async(new PNCallback<PNHereNowResult>() {
#Override
public void onResponse(PNHereNowResult result, PNStatus status) {
if (status.isError()) {
// handle error
return;
}
for (PNHereNowChannelData channelData : result.getChannels().values()) {
allUsers.append("---");
allUsers.append("channel:" + channelData.getChannelName());
allUsers.append("occoupancy: " + channelData.getOccupancy());
allUsers.append("occupants:");
for (PNHereNowOccupantData occupant : channelData.getOccupants()) {
allUsers.append("uuid: " + occupant.getUuid() + " state: " + occupant.getState());
}
}
}
});
return allUsers.toString();
}
#Override
protected void onResume() {
super.onResume();
}
}
Here are my problems:
I am trying to display all the data that I receive in a textview (later it will arranged in a listview or a recycler view) but I am getting a blank screen so I am getting null from the server.
The user status should be constantly updated to know if the user changes state (online -> offline) but there seems to be no async calls made in the code so I think it will be executed only once and then the dataset is not being changed.
How can I solve my problems?
PubNub Presence
You can monitor online and state changes using PubNub Presence. When you subscribe, subscribe with presence enabled and you will get state-change, join, leave & timeout events in the presence callback.
Callback callback = new Callback() {
#Override
public void successCallback(String channel, Object message) {
System.out.println(channel + " : "
+ message.getClass() + " : " + message.toString());
// take action on the presence events here
}
#Override
public void connectCallback(String channel, Object message) {
System.out.println("CONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
#Override
public void disconnectCallback(String channel, Object message) {
System.out.println("DISCONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
#Override
public void reconnectCallback(String channel, Object message) {
System.out.println("RECONNECT on channel:" + channel
+ " : " + message.getClass() + " : "
+ message.toString());
}
#Override
public void errorCallback(String channel, PubnubError error) {
System.out.println("ERROR on channel " + channel
+ " : " + error.toString());
}
};
try {
pubnub.presence("my_channel", callback);
}
catch (PubnubException e) {
System.out.println(e.toString());
}
It appears Sinch is using a rather old version of the PubNub Android SDK. I would think you could still use PubNub Android SDK v4 to do what you need to do outside of Sinch SDK unless there is some explicit requirements by Sinch to use the same version of the SDK.
I was hoping someone may be able to help or at least point me in the right direction. I'm writing an android app that publishes/receives messages and i'm trying to use PubNub to accomplish this task. In my view I firstly unsubscribe from a group name and then subscribe to it. When I then publish a message, I successfully get one message. If I then leave the view and re-enter it, when I publish a message I get a duplicate. If I do the same again, the message is triplicated and so on.
Could someone please look at my code or give me any advice.
Many thanks.
private Pubnub pubnub = new Pubnub("pub-key", "sub-key");
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(com.rickeshjobanputra.snapapp.R.layout.activity_group);
GroupName = intent.getStringExtra("GroupName");
String uuid = "12345";
pubnub.setUUID(uuid);
pubnub.unsubscribe(GroupName);
try {
pubnub.subscribe(GroupName, new Callback() {
#Override
public void successCallback(String channel, final Object message) {
System.out.println("SUBSCRIBE : " + channel + " : "
+ message.getClass() + " : " + message.toString());
}
});
} catch (PubnubException e) {
System.out.println(e.toString());
}
addListenerOnButton();
}
private void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(com.rickeshjobanputra.snapapp.R.id.snap_something_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pubnub.publish(GroupName, "test", new Callback() {
});
}
});
}
UPDATE
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
pubnub.unsubscribeAllChannels();
try {
pubnub.subscribe("test", new Callback() {
#Override
public void connectCallback(String channel, Object message) {
pubnub.publish("test", "Hello from the PubNub Java SDK", new Callback() {});
}
#Override
public void successCallback(String channel, final Object message) {
System.out.println("SUBSCRIBE : " + channel + " : "
+ message.getClass() + " : " + message.toString());
}
});
} catch (PubnubException e) {
System.out.println(e.toString());
}
}
I'm trying to change the UUID of the estimote beacons and have not found a specific API for this, anyone have any example or help?
Here you have, It's the same for the proximityUUID but you gotta change the writeMajor by writeProximityUuid.
private void setMajorID(final int majorid,final Beacon beacon) {
mMajorsConnection = new BeaconConnection(this, beacon, new BeaconConnection.ConnectionCallback() {
#Override
public void onAuthenticated(BeaconConnection.BeaconCharacteristics chars) {
Log.d(TAG, "Authenticated to beacon: " + chars);
mMajorsConnection.writeMajor(majorid, new BeaconConnection.WriteCallback() {
#Override
public void onSuccess() {
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter.update(beacon);
}
});
Log.d(TAG, "Successfully writted the major id!");
mMajorsConnection.close();
}
#Override
public void onError() {
Log.d(TAG, "Error while writting the major id!");
}
});
}
#Override
public void onAuthenticationError() {
Log.d(TAG, "Authentication Error");
}
#Override
public void onDisconnected() {
Log.d(TAG, "Disconnected");
}
});
mMajorsConnection.authenticate();
}
You can use the writeProximityUuid method of the BeaconConnection class.