How to change estimote beacon UUID using AndroidSDK - android

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.

Related

How to connect 3+ devices using Google-Nearby Connection APIs

I am building an app that should connect at least 4 devices using nearby connection api. I am able to connect them intermittently, other wise only two devices are getting connected.
I am using P2P-CLUSTER Topology and sending data as file payloads which are successfully sent.
I have two questions:
Any suggestion on how to have a stable connection among 2+ devices.
While sending data as file payloads, a folder is created in the download folder. Is there any way to discard this step and be able to send data directly as file payloads without having to save them locally.
Here is my code regarding the connection part only.
private final EndpointDiscoveryCallback endpointDiscoveryCallback =
new EndpointDiscoveryCallback() {
#Override
public void onEndpointFound(String endpointId, final DiscoveredEndpointInfo info) {
arrlist.add(endpointId);
for (int i = 0; i< arrlist.size(); i++) {
connectionsClient
.requestConnection(Build.MODEL, arrlist.get(i), connectionLifecycleCallback)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
}
#Override
public void onEndpointLost(#NonNull String endpointId) {
}
};
private final ConnectionLifecycleCallback connectionLifecycleCallback =
new ConnectionLifecycleCallback() {
#Override
public void onConnectionInitiated(#NonNull String endpointId, #NonNull ConnectionInfo connectionInfo) {
// Automatically accept the connection on both sides.
connectionsClient.acceptConnection(endpointId, new PayloadCallback() {
#Override
public void onPayloadReceived(#NonNull String s, #NonNull Payload payload) {
}
}
#Override
public void onPayloadTransferUpdate(#NonNull String s, #NonNull PayloadTransferUpdate payloadTransferUpdate) {
}
#Override
public void onConnectionResult(#NonNull String endpointId, ConnectionResolution result) {
switch (result.getStatus().getStatusCode()) {
case ConnectionsStatusCodes.STATUS_OK:
if(arrlist != null && arrlist.contains(endpointId)){
System.out.println(TAG+ " End Point Found");
} else {
arrlist.add(endpointId);
}
connectionsClient.stopDiscovery();
connectionsClient.stopAdvertising();
break;
case ConnectionsStatusCodes.STATUS_CONNECTION_REJECTED:
// Some code
break;
case ConnectionsStatusCodes.STATUS_ERROR:
// Some code
break;
default:
}
}
#Override
public void onDisconnected(#NonNull String endpointId) {
// some code
}
};
private void startAdvertising() {
AdvertisingOptions advertisingOptions =
new AdvertisingOptions.Builder().setStrategy(STRATEGY).build();
Nearby.getConnectionsClient(context)
.startAdvertising(
android.os.Build.MODEL, getPackageName(), connectionLifecycleCallback, advertisingOptions)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
private void startDiscovery() {
DiscoveryOptions discoveryOptions =
new DiscoveryOptions.Builder().setStrategy(STRATEGY).build();
Nearby.getConnectionsClient(context)
.startDiscovery(getPackageName(), endpointDiscoveryCallback, discoveryOptions)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}

Using mqtt to send push notification , not working when swiped from recent apps

using mqtt for push notification in android with following libs :
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
i followed this tutorial , the problem is it works properly when app is open , but when it is swiped from recent apps , it stops working and I can't receive push notifications anymore
any help is appreciated
solutions i tried :
first solution : created a service and simply created a mqttclient in it , but after swiping from recent apps didn't work anymore
public class MqttService extends Service {
public MqttService(Context context) {
super();
}
public MqttService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
PahoDemo paho = new Paho(getApplicationContext(), "myTopic");
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Intent intent = new Intent("com.example.restart");
sendBroadcast(intent);
}
#Override
public void onDestroy() {
super.onDestroy();
Intent intent = new Intent("com.example.restart");
sendBroadcast(intent);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
PahoDemo :
public class Paho implements MqttCallback {
String topic;
MqttClient client;
Context context;
public Paho(Context context, String topic) {
this.context = context;
this.topic = topic;
try {
client = new MqttClient(StaticValue.getBROKER(), MqttClient.generateClientId(), persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
client.connect(connOpts);
client.setCallback(this);
if (topic != null) {
client.subscribe(topic);
}
} catch (MqttException e) {
System.out.println("error: " + e);
e.printStackTrace();
}
}
#Override
public void connectionLost(Throwable cause) {
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.i("mqtt", "messageArrived ");
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
Log.i("mqtt", token + "");
}
}
second solution:
added the below line to manifest :
<service android:name="org.eclipse.paho.android.service.MqttService" />
called this helper class from mainactivty's Oncreate :
public class MqttHelper {
public MqttAndroidClient mqttAndroidClient;
final String serverUri = "myBrokerUri";
final String clientId = MqttClient.generateClientId();
final String subscriptionTopic = "myTopic";
public MqttHelper(Context context){
mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
mqttAndroidClient.setCallback(new MqttCallbackExtended() {
#Override
public void connectComplete(boolean b, String s) {
Log.w("mqtt", s);
}
#Override
public void connectionLost(Throwable throwable) {
}
#Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Mqtt", mqttMessage.toString());
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
connect();
}
public void setCallback(MqttCallbackExtended callback) {
mqttAndroidClient.setCallback(callback);
}
private void connect(){
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setCleanSession(true);
try {
mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
subscribeToTopic();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.w("Mqtt", "Failed to connect to: " + serverUri + exception.toString());
}
});
} catch (MqttException ex){
ex.printStackTrace();
}
}
private void subscribeToTopic() {
try {
mqttAndroidClient.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.w("Mqtt","Subscribed!");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.w("Mqtt", "Subscribed fail!");
}
});
} catch (MqttException ex) {
System.err.println("Exceptionst subscribing");
ex.printStackTrace();
}
}
}
that's all i did since tow days ago . if someone has any ideas , please mention .
when messageArrived is called , you shouldn't use something you don't access to . for example if you wanna check app is in foreground , you may use context , this way your logic may doesn't work properly , so make sure you do what you can do in messageArrived and if you aren't sure the objects you use are available do it another way (also be careful about connectinLost )

Twilio Android: Issue in joining a channel : "Member already exists"

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
}

MqttAndroidClient - onFailure

Question
Why I am able to connect to my server over my mainActivity , but not over a fragment?
Setup
Program 1 - works...
Right now, I have two programs.
The first one is called mqtt_test which includes a MainActivity, a Button and the connection-class Mqtt. So there are no fragments.
With that program I am able to connect to my Server, subscribe and receive messages.
Code of first programm
public class mqtt {
private Context context;
private String broker = "tcp://10.34.5.134:1883";
private String clientId= "DefaultName";
private MqttAndroidClient client;
private ConnectionListener connectionListener;
private static final String TAG_MQTT= "MQTT";
public mqtt(Context context)
{
this.context = context;
}
public void connect()
{
final String clientId = MqttClient.generateClientId();
//set options
MqttConnectOptions options = new MqttConnectOptions();
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
client =
new MqttAndroidClient(context, broker,
clientId);
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Log.d(TAG_MQTT, "onSuccess");
connectionListener.connected(true);
client.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable cause) {
Log.d(TAG_MQTT, "connectionLost: ");
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.d(TAG_MQTT, "messageArrived: Message: " + message.toString() + " with topic: " + topic);
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
Log.d(TAG_MQTT, "deliveryComplete: ");
}
});
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.d(TAG_MQTT, "onFailure");
connectionListener.connected(false);
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
public void subscribe(final String topic, int qos)
{
if(client.isConnected())
{
try {
IMqttToken subToken = client.subscribe(topic, qos);
subToken.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// The message was published
Log.d(TAG_MQTT, "onSuccess: Subscripted with topic: " + topic);
}
#Override
public void onFailure(IMqttToken asyncActionToken,
Throwable exception) {
// The subscription could not be performed, maybe the user was not
// authorized to subscribe on the specified topic e.g. using wildcards
Log.d(TAG_MQTT, "onFailure: The subscription failed");
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
}
public void publish(String topic, String payload, int qos)
{
byte[] encodedPayload = new byte[0];
try {
encodedPayload = payload.getBytes("UTF-8");
MqttMessage message = new MqttMessage(encodedPayload);
client.publish(topic, message);
Log.d(TAG_MQTT, "publish: Published message:" + payload + " to topic: " + topic);
} catch (UnsupportedEncodingException | MqttException e) {
e.printStackTrace();
Log.d(TAG_MQTT, "publish: Error");
}
}
public void setConnectionListener(ConnectionListener connectionListener) {
this.connectionListener = connectionListener;
}
}
Program 2 - doesn't work
In my second program I am using nearly the same code. However, I am using fragments for future business. In some fragments are buttons, which are calling the right method.
If I press the button, then the right method gets called, like in the first program.
But the program jumps over the async task. OnSucces or onFailure never gets called.
IMqttToken token = client.connect(null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// connected
Log.d(TAG_CONNECTION, "onSuccess");
connectionListener.connected(true);
client.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable cause) {
Log.d(TAG_CONNECTION, "connectionLost: ");
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.d(TAG_CONNECTION, "messageArrived: Message: " + message.toString() + " with topic: " + topic);
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
Log.d(TAG_CONNECTION, "deliveryComplete: ");
}
});
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d(TAG_CONNECTION, "onFailure");
connectionListener.connected(false);
Log.d(TAG_CONNECTION, exception.getMessage());
}
});
Then I called the connect-method over a new thread:
#Override
public void doSmth() {
new Thread(new Runnable() {
public void run() {
// a potentially time consuming task
mqttConnection.connect();
}
}).start();
}
Finally I got an answer:
D/CONNECTION: cannot start service org.eclipse.paho.android.service.MqttService
I don't understand why this doesn't work. Maybe you have some input.
To be clear: Both programs do have the same permissions:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Assumption
I think, I have to use more asycTasks to solve this problem.
Input/links
It would be awesome, if you could share some links. In the best case with some examples. I only found examples wich are running in a single MainActivity.
The error
D/CONNECTION: cannot start service org.eclipse.paho.android.service.MqttService
possibly indicates that the entry
<service android:name="org.eclipse.paho.android.service.MqttService">
</service>
in AndroidManifest.xml is missing

How to create new notebook in evernote from android application?

I have referred this, I have integrated successfully, now I want to create Notebook from app for that I tried below code but I am getting every time exception.
Note myNote = new Note();
myNote.setTitle("My Test Notebook");
createNoteInAppLinkedNotebook(myNote, new OnClientCallback<Note>() {
#Override
public void onSuccess(Note data) {
}
#Override
public void onException(Exception exception) {
Log.e(TAG, exception.toString());
}
});
#SuppressWarnings("deprecation")
protected void createNoteInAppLinkedNotebook(final Note note,final OnClientCallback<Note> createNoteCallback) {
showDialog(DIALOG_PROGRESS);
invokeOnAppLinkedNotebook(new OnClientCallback<Pair<AsyncLinkedNoteStoreClient, LinkedNotebook>>() {
#Override
public void onSuccess(
final Pair<AsyncLinkedNoteStoreClient, LinkedNotebook> pair) {
pair.first.createNoteAsync(note, pair.second,
createNoteCallback);
}
#Override
public void onException(Exception exception) {
Log.e(LOGTAG, "Error creating linked notestore", exception);
Toast.makeText(getApplicationContext(),R.string.error_creating_notestore, Toast.LENGTH_LONG).show();
removeDialog(DIALOG_PROGRESS);
}
});
}
I am getting Error creating linked notestore exception everytime.
Is there any solution for the same ?
Finally I found my own question's solution:
Notebook nb = new Notebook();
nb.setName("My Test Notebook");
try {
AsyncNoteStoreClient asyncNoteStoreClient = mEvernoteSession.getClientFactory().createNoteStoreClient();
asyncNoteStoreClient.createNotebook(nb, new OnClientCallback<Notebook>() {
#Override
public void onSuccess(Notebook data) {
Log.i(TAG, "onSucceess");
}
#Override
public void onException(Exception exception) {
Log.i(TAG, "onException");
}
});
} catch (TTransportException e) {
e.printStackTrace();
}

Categories

Resources