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

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) {
}
});
}

Related

How to call Async Task with new Values?

public class BackgroundTasker extends AsyncTask {
int progress;
#Override
protected void onPreExecute() {
result.startAnimation(fadeIn);
result.setTextSize(32);
progressupdator(20);
result.setText("Starting...");
}
#Override
protected Long[] doInBackground(String... address) {
while (true) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(new Long[] {
MainActivity.this.getvalue(address[0]) });
}
}
protected void onProgressUpdate(Long... values){
if(values[0]==Long.valueOf(333)) {
setProgress(100);
result.setText("N/A");
builder.setContentText("N/A");
notificationManager.notify(1,builder.build());
}
else{
setProgress(100);
result.setText(String.valueOf(values[0])+"ms");
builder.setContentText(String.valueOf(values[0])+"ms");
notificationManager.notify(1,builder.build());
}
}
protected void onPostExecute(int d) {
}
#Override
public void onClick(View v) {
DatabaseReference myRef = database.getReference("message");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
BackgroundTasker r = new BackgroundTasker();
r.execute(dataSnapshot.getValue(String.class));
Log.d("Fireabse", "Value is: " + value);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("Firebase", "Failed to read value.", error.toException());
}
});
}
});
I want that whenever the button connected to onClick is pressed, The r.execute take new values from Firebase Realtime Database and perform AsyncTask with the new values.
How do i do that?

result of creation account in firebase is true but it's not added in firebase console

(Application Flow)
sign up -> create account in firebase authentication, sharedpreference.put(email & pw) for automatic login, save user info in database in firebase -> login -> mainActivity
before I released apk and proguard, it works well without any problem.
But after I had problems with proguard, I eliminate proguard rules and change minifyEnabled true to false in gradle.
Then I rebuild and run my app.
result of FirebaseAuth.createUserWithEmailAndPassword is true.
and result of UserData upload is true.
also result of login is true.
After all success, I checked my firebase console.
But new auth data is not added.
And userdata is created but every information is null.
Sharedpreference is empty as well.
I checked my previous code when it works well.
All codes are same.
And I searched all day long, but I haven't gotten any hint for handling it.
==FirebaseAuth Class ===
public void singUp(String userEmail, String userPwd) {
firebaseAuth.createUserWithEmailAndPassword(userEmail,userPwd)
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
firebaseAuthListener.onSignUpComplete(true);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
firebaseAuthListener.onSignUpComplete(false);
if(e instanceof FirebaseAuthUserCollisionException) {
signUpErrorListener.setErrorMessage("이미 사용 중인 이메일입니다. 다시 시도해주세요.");
}
}
});
}
public void login(final String userEmail, String userPwd){
firebaseAuth.signInWithEmailAndPassword(userEmail,userPwd)
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
firebaseLoginListener.onLoginComplete(true);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
firebaseLoginListener.onLoginComplete(false);
}
});
}
public void userDataUpload(final UserData userData){
firestore.collection("User")
.add(userData).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
firebaseAuthListener.onUserDataComplete(true);
String recording_key = documentReference.getId();
recordingKeyListener.onSaveRecordKey(recording_key);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
firebaseAuthListener.onUserDataComplete(false);
}
});
}
==SignUp Class =====
complete_btn.setOnClickListener(this);
#Override
public void onClick(View view) {
int id = view.getId();
switch (id){
case R.id.complete_btn:
boolean check_pw = checkPassword(userPassword_textInput,check_userpw_textInput);
if(check_pw) {
if(isSignUpSuccess) {
isComplete();
}else{
onSignUpComplete(true);
}
}else{
Toast.makeText(this, "비밀번호 일치 오류입니다. 다시 입력해주세요.", Toast.LENGTH_SHORT).show();
}
break;
}
}
private boolean checkPassword(TextInputLayout userPassword_textInput, TextInputLayout check_userpw_textInput) {
return true when passwords are same / return false in the other case
}
private void isComplete() {
userEmail = changeToString(userEmail_textInput);
userPwd = changeToString(userPassword_textInput);
userAge = changeToString(userAge_textInput);
userName = changeToString(userName_textInput);
singUp();
}
}
private void singUp() {
setUserData();
firebaseAuthData.singUp(userEmail, userPwd);
}
private void setUserData(){
userData.setUserName(userName);
userData.setUserEmail(userEmail);
userData.setUserAge(userAge);
userData.setUserGender(userSex);
userData.setUserJob(userJob);
}
#Override
public void onSignUpComplete(boolean isSuccess) {
this.isSignUpSuccess = isSuccess;
if(isSuccess){
firebaseAuthData.userDataUpload(userData);
SharedPreference sharedPreference = new SharedPreference();
sharedPreference.put(this,"email",userEmail);
sharedPreference.put(this,"pwd",userPwd);
}else{
Toast.makeText(this, "회원가입에 실패하였습니다.", Toast.LENGTH_SHORT).show();
LoadingProgress.dismissDialog();
}
}
#Override
public void onUserDataComplete(boolean isSuccess) {
LoadingProgress.dismissDialog();
if(isSuccess){
goNext(MainActivity.class);
}else{
Toast.makeText(this, "회원가입 실패 ", Toast.LENGTH_SHORT).show();
}
}
}
If the result of creation auth data is true, new account info should be added in my firebase console. At the same time, save user's email and pw in user's device using shared preference, plus created userdata with information that user input not null.
=====SignUp Class=======
(Global Variable)
//for checking created user account but not setting userData in Database
Boolean isSignUpSuccess = true;
complete_btn.setOnClickListener(this);
#Override
public void onClick(View view) {
int id = view.getId();
switch (id){
case R.id.complete_btn:
boolean check_pw = checkPassword(userPassword_textInput,check_userpw_textInput);
if(check_pw) {
if(isSignUpSuccess) {
isComplete();
}else{
onSignUpComplete(true);
}
}else{
Toast.makeText(this, "비밀번호 일치 오류입니다. 다시 입력해주세요.", Toast.LENGTH_SHORT).show();
}
break;
}
}

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 )

How to change estimote beacon UUID using AndroidSDK

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.

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