Toast doesn't disapear - android

I have made an application that sends messages from my smartphone to my smartwatch.
This is the class where I create a Message that I can send to smartwatch.
public class Message implements GoogleApiClient.ConnectionCallbacks{
private String message;
private Application app;
public Message(String message, Application app){
this.message=message;
this.app = app;
}
public void sendMessage() {
new Thread( new Runnable() {
#Override
public void run() {
GoogleApiClient clientApi = new GoogleApiClient.Builder(aplicacao.getApplicationContext())
.addApiIfAvailable( Wearable.API )
.build();
clientApi.connect();
NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes( clientApi ).await();
if(nodes.getNodes().isEmpty())
Log.w("No signal!","No signal!");
else {
for (Node node : nodes.getNodes()) {
Wearable.MessageApi.sendMessage(clientApi, node.getId(), message, message.getBytes()).await();
}
}
clientApi.disconnect();
}
}).start();
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
}
When I want to send a Message to smartwatch I use this two lines of code:
Message message = new Message("Message", getApplication());
message.sendMessage();
I made this service on my smartwatch application to receive messages from smartphone.
When I receive a message I show a Toast with the text of that message:
public class ReceiveMessages extends WearableListenerService {
#Override
public void onMessageReceived(MessageEvent event) {
String message = event.getPath();
showMessages(message);
}
private void showMessages(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
The smartwatch is receiving the message and shows the text of the message correctly, it does not disappear after Toast.LENGTH_SHORT.
I want to know whether there is any problem in my code (I don't have any infinite loop).
Thanks.

TOAST IN SERVICE? HAHA THIS IS YOUR SOLUTION:
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Lumos Maxima", Toast.LENGTH_LONG).show();
}
});

Be sure your Thread is terminated cus it seems you are sending many toasts that appear like one.

You use this also:
Toast.makeText(Activityname.this, "message", Toast.LENGTH_SHORT).show();
Or if it is outside the class, you'll need to get your activity context (pass it in the constructor etc.)
How to use Toast when I cant use "this" as context

Try next code:
Toast.makeText(getApplicationContext(), "Your Message", Toast.LENGTH_LONG).show();

You use this also:
Toast.makeText(Activityname.this, "message", Toast.LENGTH_SHORT).show();

Related

Firebase Cloud Messaging FCM Send Notification Message Android

I have two apps that use FCM, Client and Worker app. Client is sending the message:
String jsonLatLng = new Gson().toJson(new LatLng(Common.placeLatLng.latitude, Common.placeLatLng.longitude));
String clientToken = FirebaseInstanceId.getInstance().getToken();
Notification notification = new Notification(clientToken, jsonLatLng);
Sender content = new Sender(tokenId, notification);
mFCMService.sendMessage(content)
.enqueue(new Callback<FCMResponse>() {
#Override
public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) {
if(response.body().success == 1) {
Toast.makeText(HomeActivity.this, "Request sent.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(HomeActivity.this, "Request not sent.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<FCMResponse> call, Throwable t) {
}
});
Wherein Notification.java is
public class Notification {
public String title;
public String body;
...
}
Sender.java is
public class Sender {
public String to;
public Notification notification;
...
}
And with the Worker app, it receives:
public class MyFirebaseMessaging extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Convert lat lng
LatLng clientLocation = new Gson().fromJson(remoteMessage.getNotification().getBody(), LatLng.class);
Intent intent = new Intent(getBaseContext(), NotificationActivity.class);
intent.putExtra("lat", clientLocation.latitude);
intent.putExtra("lng", clientLocation.longitude);
intent.putExtra("client", remoteMessage.getNotification().getTitle());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
These codes work perfectly fine, however, I need to add more details, specifically, I want to send data from 2 String variables, serviceFee & serviceType over to the Worker app. I tried modifying the body of the Notification wherein I created a class called Body with three variables (jsonLatLng, serviceFee, serviceType), but I can't figure out how the worker will be able to get the data of Body or if that's even possible. Please help. Thank you! :)

Add addMessageListener for MultiUserChat Using Smack 4.1

I'm new to android and I tried to create a chat app using Smack 4.1 and Ejabberd.
I have implemented a group chat using MultiUserChat. I have added Messagelistener to listen every new incoming message and add into adapter.
When I enter into chat room and start chat list works very well.
But the problem is when I back to the any other intent and then go back into chat room then when someone messages me, it is received multiple times.
Maybe I set messagelistner multiple times.
Here is my code Activity Class -
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatiing);
user2 = getIntent().getExtras().getString("JID");
msg_edittext = (EditText)findViewById(R.id.messageEditText);
msgListView = (ListView)findViewById(R.id.msgListView);
msgListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
chatlist = new ArrayList<ChatMessage>();
chatlist.clear();
chatAdapter = new ChatAdapter(ChattingGroup.this,chatlist);
msgListView.setAdapter(chatAdapter);
autoJoinRoom(user1,room_name,new View(getApplicationContext()));
ImageButton sendButton = (ImageButton)findViewById(R.id.sendMessageButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendTextMessage(view);
}
});
}
public void autoJoinRoom(String user, String room, View view){
LoginActivity activity = new LoginActivity();
XMPPTCPConnection connection = activity.getmService().xmpp.connection;
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
MultiUserChat multiUserChat = manager.getMultiUserChat(room);
try {
multiUserChat.join(user,"12345");
chatlist.clear();
multiUserChat.addMessageListener(new MessageListener() {
#Override
public void processMessage(Message message) {
if(message.getBody() != null){
Log.d("New Message Received",message.getBody());
chatlist.add(message.getBody());
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
/* Change adapter */
((BaseAdapter) msgListView.getAdapter()).notifyDataSetChanged();
}
});
}
}
});
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
}
}
How can I solve this problem ?

Why is FirebaseInstanceIdService.onTokenRefresh() is never called?

Maybe I am doing a wrong step. I have 3 activities:
Launcher
Login
MainActivity
In the onCreate of my MainActivity, I am calling the service:
void iniciarServicioSendTokenFCM(){
servicioFCM= new Intent(this, IDService.class);
startService(servicioFCM);
}
And this is executed, because it gets to enter in onCreate of Service but onTokenRefresh() is never executed.
I have done these steps too. I have uninstalled and reinstalled the app but it didn't work.
public class IDService extends FirebaseInstanceIdService {
private ConnectionStatusSync ConnSync;//= new ConnectionStatusSync(this);
private DispositivoSync Sync;
private Integer dispositivoId;
private PreferenceUtil preferenceUtil ;
private String tokenDispositivo;
private DispositivoSync.OnFragmentInteractionListener listener;
public IDService() {
}
#Override
public void onCreate() {
super.onCreate();
Listener();
ConnSync = new ConnectionStatusSync(this);
Sync = new DispositivoSync(this);
preferenceUtil= new PreferenceUtil(this);
dispositivoId=preferenceUtil.getInt(getString(R.string.dispositivoID),0,null);
dispositivoId=(dispositivoId==0?null:dispositivoId);
tokenDispositivo= new IDUtil(this).getId();
}
private void Listener(){
listener = new DispositivoSync.OnFragmentInteractionListener() {
#Override
public void onFinished(boolean terminoBien, int dispositivoID) {
if(terminoBien){
preferenceUtil.savePreference(getString(R.string.dispositivoID),dispositivoID,null);
}
}
};
}
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
preferenceUtil.savePreference(getString(R.string.TokenFCM),refreshedToken,null);
//Log.d(TAG, "Refreshed token: " + refreshedToken);
// TODO: Implement this method to send any registration to your app's servers.
if(validaciones())
sendRegistrationToServer(refreshedToken);
}
private boolean validaciones(){
return dispositivoId!=null && MainActivity.mOperador!=null;
}
private void sendRegistrationToServer(final String token){
final Thread registrar = new Thread(new Runnable() {
#Override
public void run() {
Sync.EnviarDispositivo(MainActivity.mOperador.getOperadorIdServidor(),dispositivoId,token,tokenDispositivo,listener );
}
});
Thread hilo = new Thread(new Runnable() {
#Override
public void run() {
Command commandNull= new Command() {
#Override
public void execute() {
}
};
ConnSync.CheckConnection(registrar,commandNull);
}
});
hilo.start();
}
}
In an app that uses Firebase Cloud Messaging, the client immediately starts generating the token when the app starts.
Most likely the initial token has already been generated by the time you start listening for onTokenRefresh(). So you'll want to also immediately request and store the token in your iniciarServicioSendTokenFCM method:
sendRegistrationToServer(FirebaseInstanceId.getInstance().getToken());
I don't think it is very useful to store the token in shared preferences by the way, given that it is readily accessible from FirebaseInstanceId.getInstance().getToken().

Toast in Fragment ( No syntax but no show when running the code)

I am a newbie for android development. Recently, i faced a problem when i want to use toast and alert dialog.
Toast.makeText(getActivity(), " error", Toast.LENGTH_LONG).show();
I have tried getActivity().getApplicationContext() instead of only getActivity
both code have no syntax error but show nothing when i run
More code:
public class RegisterFragment extends Fragment {
...
.... onCreate...
.... GetData();...
..
In GetData()
inputStream = response.getEntity().getContent();
String error = convertInputStreamToString(inputStream);
JSONObject data = new JSONObject(error);
String test123 = data.getJSONObject("error").getString("code");
RegisterFragment register = new RegisterFragment();
register.makeToast(test123);
...
..
}
In makeToast function:
public void makeToast(String error){
Log.v("error",error);
Toast.makeText(getActivity(), "missing input",Toast.LENGTH_LONG).show();
}
}
The toast can only be shown on a UI Thread. Since you are making a network call the response must be running on a background thread. change your method to
public void makeToast(String error) {
Log.v("error", error);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(), "missing input", Toast.LENGTH_LONG).show();
}
});
}
Can you please try below ? Actually I have faced same issue 1 month ago, I have solved by below code:
new CountDownTimer(2000,2000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
makeToast("Your Error Message");
}
}.start();
Hope it will help you.
RegisterFragment register = new RegisterFragment();
register.makeToast(test123);
This is your problem. You have just created an instance of RegisterFragment, but it is not attached to an Activity at this point. Therefore, the getActivity() call within makeToast() will return null.

smack 4.1 processMessage method does not called

i'm using smack 4.1 library where i'm unable to revived message event.
here is my code-
Chat chat = connection.getChatManager().createChat("user2#openfireserver", new MessageListener() {
#Override
public void processMessage(Chat arg0, Message arg1) {
System.out.println(arg1.getBody());
}
});
chat.sendMessage("test message");
debug report-
<message id="WrfOv-14" to="user1#openfireserver/Smack" from="user2#openfireserver/Smack" type="chat"><body>my test application</body><thread>56b1a75c-69a5-4a12-b12a-d24e072a2ce7</thread></message>
receive chat show in debug but not getting event in processMessage method.
(may my question is duplicate but i'm not find relevant answer)
I have used Smack 4.1 library in one of my Android projects. The following code snippet worked for me.
ChatManager.getInstanceFor(connection).addChatListener(new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally) {
chat.addMessageListener(new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
if (message.getType() == Message.Type.chat || message.getType() == Message.Type.normal) {
if(message.getBody()!=null) {
Toast.makeText(this,message.getFrom() + " : " + message.getBody(),Toast.LENGTH_LONG).show();
}
}
}
});
}
});
Here is an example for smack-4.1.0-beta3-SNAPSHOT-2015-02-09:
It works for me, try it.
private void onAutthenticated() {
ChatManager.getInstanceFor(mConnection).addChatListener(ChatConnection.this);
}
#Override
public void chatCreated(Chat chat, boolean b) {
chat.addMessageListener(new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
if (message.getType().equals(Message.Type.chat) || message.getType().equals(Message.Type.normal)) {
Log.d(TAG, message.getFrom());
Log.d(TAG, message.getBody());
}
}
});
}
For Receiving any Type of Message, you can use following code
StanzaTypeFilter message_filter = new StanzaTypeFilter(Message.class);
connection.addSyncStanzaListener(new StanzaListener() {
#Override
public void processPacket(Stanza packet) throws NotConnectedException {
Message message = (Message)packet;
if(message.getType() == Message.Type.chat) {
//single chat message
} else if(message.getType() == Message.Type.groupchat) {
//group chat message
} else if(message.getType() == Message.Type.error) {
//error message
}
}
}, message_filter);
I think the create methord and the add methord are not same. create methord does not register a listener,but the add methord does register.When I see the api doc, I have the same question with you,but the doc does not give me an answer.So i guess this may be where the problem exists.

Categories

Resources