Firebase Cloud Messaging FCM Send Notification Message Android - 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! :)

Related

response.body is null even after passing data

I am trying to send a notification from one app to another using Firebase Cloud Messaging. I have spent a couple of days now trying to figure out what the problem is. I have passed a notification body to specific token id. When i debug my app it says 'mService is not available' and when i run the app it throws a NullPointerException.
The content i am trying to send is ok as per my analysis.
I have checked the interface IFCMService,FCMClient and the Main class, they all seem to be ok but i still don't understand why i am getting a null response.body. I have also checked my server key and it is well. I have seen a few similar questions but none have been able to specify why this issue may occur. Kindly anyone, i would really appreciate your help.
Below is my IFCMService code
public interface IFCMService {
#Headers({"Authorization:key=" + "<YOUR SERVER KEY>",
"Content-Type:application/json"})
#POST("fcm/send")
Call<FCMResponse> sendMessage(#Body Sender body);
}
FCMClient class
public class FCMClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseURL)
{
if (retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(baseURL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
This is the declaration and specific code where i get the error. The 'mService.sendMessage(content)' section is where the NullPointerException is thrown.
protected void sendRequestDriver(String driverId){
Toast.makeText(MainActivity.this,"send driver",Toast.LENGTH_SHORT).show();
DatabaseReference tokens = FirebaseDatabase.getInstance().getReference(Common.token_tbl);
tokens.orderByKey().equalTo(driverId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postsnapshot:dataSnapshot.getChildren())
{
Token token = postsnapshot.getValue(Token.class);
String json_lat_lng = new Gson().toJson(new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude()));
Notification notification = new Notification("X", json_lat_lng);
Sender content = new Sender(notification,token.getToken());
mService.sendMessage(content)
.enqueue(new Callback<FCMResponse>() {
#Override
public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) {
if (response.body().success == 1)
{
Toast.makeText(MainActivity.this,"Request sent",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this,"Failed",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<FCMResponse> call, Throwable t) {
Log.e("ERROR",t.getMessage());
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
try this one please:
public interface IFCMService {
#Headers({"Content-Type:application/json",
"Authorization:key=" + "<YOUR SERVER KEY>"
})
#POST("fcm/send")
Call<FCMResponse> sendMessage(#Body Sender body);
}

Send FCM to user subscribed to a topic programmatically

I am creating a BloodBank app in which, when the user requests for the blood, It takes the requested Blood group and search the same in the database. It displays list of all the users who can donate to that blood group.
In the list, I have already implemented an option to message and call the user. Additionally, I want the App to send a notification to all users who have the same blood group.
For achieving this I have subscribed the user to a topic at successful login and sent him a notification but I have done this through the console.
What I want to achieve is, as a user requests the blood and while showing him the list of all users who can donate, App should also send a notification to all the users who have subscribed to that topic.
So is there any possible way I can programmatically send FCM to all the users subscribed to the same topic.
Here I'm subscribing user to a topic at successful Login:
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
progressDialog.dismiss();
topicSubscription();
} else {
progressDialog.dismiss();
String exception = task.getException().getMessage();
HelperClass.showSnakbarMsg(rootView, exception);
}
}
});
}
private void topicSubscription() {
FirebaseMessaging.getInstance().subscribeToTopic("Blood")
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
String msg = getString(R.string.msg_subscribed);
if (!task.isSuccessful()) {
msg = getString(R.string.msg_subscribe_failed);
} else {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
Log.d("log", msg);
Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
This is my Firebase messaging class:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
Log.d(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
I have read about it and many have said to hit an API for this to send FCM programmatically. But I am creating the whole app in firebase so my DataBase is also in firebase and as my database is in firebase I can't use API for one notification only like I have to manage some table in DB for that notification and for only one table I have to manage a separate DB.
So is there any way that I can send FCM programmatically to all users who have subscribed to the same topic, on successful loading of the donor list which shows the user who can donate to the requested blood group.
Thanks
You can directly send push notification directly from android, to all the devices subscribed to the topic, check out the following link how to send msgs directly from android, but in this example user is sending message one to one, to send fcm message to user subscribed to a topic, you need to change the message format as specified by fcm documentation
User App
private void latLngNotification() {
Location loc1 = new Location("");
loc1.setLatitude(Double.parseDouble(userLat));
//loc1.setLongitude();
Location loc2 = new Location("");
loc2.setLatitude(Double.parseDouble(attendanceLat));
//loc2.setLongitude();
float distanceInMeters = loc1.distanceTo(loc2);
if (distanceInMeters > 50) {
//Toast.makeText(this, "distance: " + distanceInMeters, Toast.LENGTH_SHORT).show();
sendNotification();
} else {
//Toast.makeText(this, "distance: " + distanceInMeters, Toast.LENGTH_SHORT).show();
Toast.makeText(this, "You are in home...", Toast.LENGTH_SHORT).show();
}
}
private void sendNotification() {
String TOPIC = "/topics/admin_app"; //topic has to match what the receiver subscribed to
JSONObject notification = new JSONObject();
JSONObject notifcationBody = new JSONObject();
String title = "Quarantine outside";
String message = mobileno + " User is out of his area";
try {
notifcationBody.put("title", title);
notifcationBody.put("message", message);
notification.put("to", TOPIC);
notification.put("priority", "high");
notification.put("data", notifcationBody);
} catch (JSONException e) {
Log.e(TAG, "onCreate: " + e.getMessage());
}
Notification(notification);
}
private void Notification(JSONObject notification) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://fcm.googleapis.com/fcm/send", notification,
response -> Log.i(TAG, "onResponse: " + response.toString()),
error -> {
Toast.makeText(GetLocationActivity.this, "Request error", Toast.LENGTH_LONG).show();
Log.i(TAG, "onErrorResponse: Didn't work");
}) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<>();
params.put("Authorization", "key=AAAAwxBqu5A:APA91bERpf-1rh02jLciILt1rsLv7HRrFVulMTEAJXJ5l_JGrSHf96qXvLQV0bIROob9e3xLK4VN8tWo-zBPUL39HjxyW4MsX5nKW_NiQlZGgLDCySVwHXADlg16mpLUjgASj--bk-_W");
params.put("Content-Type", "application/json");
return params;
}
};
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
}
Admin App
FirebaseMessaging.getInstance().subscribeToTopic("admin_app");
Intent intent = getIntent();
if (intent != null) {
String userPhone = intent.getStringExtra("message");
//Toast.makeText(this, userPhone, Toast.LENGTH_SHORT).show();
message_txt.setVisibility(View.VISIBLE);
message_txt.setText(userPhone);
} else {
message_txt.setVisibility(View.GONE);
//Toast.makeText(this, "no data", Toast.LENGTH_SHORT).show();
}

Sending Notification from android to other android devices

I am always getting an error on sending notification from android device in logcat I have tried so many times but nothing getting:
{"multicast_id":5162718122421221171,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
Here is my android code for sending message I am sending userABC topic in the topic section.
public void SendNotification(String Title, String Message){
NOTIFICATION_TITLE = Title;
NOTIFICATION_MESSAGE = Message;
JSONObject notification = new JSONObject();
JSONObject notifcationBody = new JSONObject();
try {
notifcationBody.put("title", NOTIFICATION_TITLE);
notifcationBody.put("message", NOTIFICATION_MESSAGE);
notification.put("to", TOPIC);
notification.put("data", notifcationBody);
} catch (JSONException e) {
Log.e(TAG, "onCreate: " + e.getMessage() );
}
sendNotification(notification);
}
private void sendNotification(JSONObject notification) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(FCM_API, notification,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "onResponse: " + response.toString());
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Request error", Toast.LENGTH_LONG).show();
Log.i(TAG, "onErrorResponse: Didn't work");
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Authorization", serverKey);
params.put("Content-Type", contentType);
return params;
}
};
MySingleton.getInstance(getActivity().getApplicationContext()).addToRequestQueue(jsonObjectRequest);
}
Here is my FirebaseInstanceIDService.java class
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "mFirebaseIIDService";
private static final String SUBSCRIBE_TO = "userABC";
#Override
public void onTokenRefresh() {
/*
This method is invoked whenever the token refreshes
OPTIONAL: If you want to send messages to this application instance
or manage this apps subscriptions on the server side,
you can send this token to your server.
*/
String token = FirebaseInstanceId.getInstance().getToken();
// Once the token is generated, subscribe to topic with the userId
FirebaseMessaging.getInstance().subscribeToTopic(SUBSCRIBE_TO);
Log.i(TAG, "onTokenRefresh completed with token: " + token);
sendRegistrationToServer(token);
}
private void sendRegistrationToServer(String token) {
// send token to web service ??
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("server/saving-data/IDs");
// then store your token ID
ref.push().setValue(token);
}
}
Here is my FirebaseMessagingService.java class
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
private final String ADMIN_CHANNEL_ID ="admin_channel";
#Override
public void onNewToken(String token) {
Log.d("TAG", "Refreshed token: " + token);
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d("THIS", "Refreshed token: " + refreshedToken);
FirebaseMessaging.getInstance().subscribeToTopic("userABC");
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
// send token to web service ??
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("server/saving-data/IDs");
// then store your token ID
ref.push().setValue(token);
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
final Intent intent = new Intent(this, MainActivity.class);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
int notificationID = new Random().nextInt(3000);
/*
Apps targeting SDK 26 or above (Android O) must implement notification channels and add its notifications
to at least one of them. Therefore, confirm if version is Oreo or higher, then setup notification channel
*/
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
setupChannels(notificationManager);
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this , 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher);
Uri notificationSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(largeIcon)
.setContentTitle(remoteMessage.getData().get("title"))
.setContentText(remoteMessage.getData().get("message"))
.setAutoCancel(true)
.setSound(notificationSoundUri)
.setContentIntent(pendingIntent);
//Set notification color to match your app color template
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
notificationBuilder.setColor(getResources().getColor(R.color.colorPrimaryDark));
}
notificationManager.notify(notificationID, notificationBuilder.build());
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void setupChannels(NotificationManager notificationManager){
CharSequence adminChannelName = "New notification";
String adminChannelDescription = "Device to devie notification";
NotificationChannel adminChannel;
adminChannel = new NotificationChannel(ADMIN_CHANNEL_ID, adminChannelName, NotificationManager.IMPORTANCE_HIGH);
adminChannel.setDescription(adminChannelDescription);
adminChannel.enableLights(true);
adminChannel.setLightColor(Color.RED);
adminChannel.enableVibration(true);
if (notificationManager != null) {
notificationManager.createNotificationChannel(adminChannel);
}
}
}
FirebaseInstanceIdService is deprecated now.
So you can change your registration logic as below
FcmRegistrationManager.java
public class FcmRegistrationManager {
private static final String TAG = "FcmRegistrationManager"
/*This is async call*/
public void registerWithFcm(){
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "getInstanceId failed", task.getException());
return;
}
// Get new Instance ID token
String token = task.getResult().getToken();
Log.d(TAG, msg);
sendRegistrationToServer(token)
}
});
}
private void sendRegistrationToServer(String token) {
// send token to web service ??
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("server/saving-data/IDs");
// then store your token ID
ref.push().setValue(token);
}
}
No change for sendNotification() and FirebaseMessagingService class.
More reference : https://firebase.google.com/docs/cloud-messaging/android/client
Let me still not working, I will share you working code.

Getting error in Firebase one to one chat app Notifications

I have made a one to one chat app and I have implemented chat notifications but when I am sending notifications from the user app to the doctor app but my doctor app crashes as soon as I am clicking on the chat notification
This is my Java class where I am handling the notification if my app is in foreground so this class will handle notifications so now in this class I am calling firebase database and taking some data from there and passing that data as an extra data with the resulting intent but when that resulting intent directs the app to the particular chat view that database data is not there
This is the Log of my app
E/MyFirebaseMessaging: From:408315985482
07-05 16:19:33.803 4399-6278/com.tech.pritz.bemoprovider D/MyFirebaseMessaging: in between Firebase and auth
07-05 16:19:33.805 4399-6278/com.tech.pritz.bemoprovider D/MyFirebaseMessaging: Message data payload: {idRe, username=komal , message=hi}
07-05 16:19:33.805 4399-6278/com.tech.pritz.bemoprovider D/MyFirebaseMessaging: app in background
07-05 16:19:33.813 4399-6278/com.tech.pritz.bemoprovider E/MyFirebaseMessaging: image not found
07-05 16:19:33.825 4399-6278/com.tech.pritz.bemoprovider D/NotificationUtil: New Message
D/MyFirebaseMessaging: Entered into the database
07-05 16:19:34.359 4399-4399/com.tech.pritz.bemoprovider D/MyFirebaseMessaging: HKNi1sezUpbwJSeEGos44FtfUw43
You can see here it is showing entered in the database also and it is getting that data also but when I pass it as an intent it is not found in another activity.
Crash log
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'java.lang.String
com.tech.pritz.bemoprovider.model.Provider.getId()' on a null object
reference at
com.tech.pritz.bemoprovider.bemo.ChatView.ini(ChatView.java:‌​350) at
com.tech.pritz.bemoprovider.bemo.ChatView.onCreate(ChatView.‌​java:150)
public class MyFirebaseMessaging extends FirebaseMessagingService
{
private static final String TAG=MyFirebaseMessaging.class.getSimpleName();
private NotificationUtil notificationUtil;
private DatabaseReference pathFirebase;
private FirebaseAuth auth;
private Provider mprovider;
#Override
public void onMessageReceived(RemoteMessage remoteMessage)
{
Log.e(TAG,"From:"+ remoteMessage.getFrom());
pathFirebase = FirebaseDatabase.getInstance().getReference();
Log.d(TAG,"in between Firebase and auth");
auth = FirebaseAuth.getInstance();
if(remoteMessage ==null )
{
return;
}
//check if message contains a notification payload
if(remoteMessage.getNotification()!=null)
{
String tittle = remoteMessage.getNotification().getTitle();
Log.e(TAG,"Notification Body:" + remoteMessage.getNotification().getBody());
handleNotification(remoteMessage.getNotification().getBody(),tittle,null, mprovider);
}
//checks to see if message contains a data payload
if(remoteMessage.getData().size() > 0)
{
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
String imageUrl = remoteMessage.getData().get("image");
// String message = remoteMessage.getData().get("message");
// String title = remoteMessage.getData().get("title");
// String name = remoteMessage.getData().get("username");
String message= remoteMessage.getData().get("message");
String name= remoteMessage.getData().get("username");
String title= "New Message";
String iduser= remoteMessage.getData().get("iduser");
String email= remoteMessage.getData().get("email");
String gcm_id= remoteMessage.getData().get("idGCM");
String conversation_id=remoteMessage.getData().get("conversation_id");
Log.d(TAG,"app in background");
pathFirebase.child("users").child(auth.getCurrentUser().getUid())
.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.d(TAG,"Entered into the database");
mprovider = dataSnapshot.getValue(Provider.class);
UserDataHolder.getInstance().setmName(mprovider.getName());
// Intent intent = new Intent(MyFirebaseMessaging.this, ListPatients.class);
mprovider.setId(auth.getCurrentUser().getUid());
UserDataHolder.getInstance().setmUserId(mprovider.getId());
// intent.putExtra("user", provider);
//startActivity(intent);
//finish();
Log.d(TAG,mprovider.getId());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MyFirebaseMessaging.this, "Failed", Toast.LENGTH_SHORT).show();
}
});
// Log.d(TAG,mprovider.getId());
// app is in background, show the notification in notification tray
Intent resultIntent = new Intent(getApplicationContext(),ChatView.class);
resultIntent.putExtra("user_id", iduser);
resultIntent.putExtra("email", email);
resultIntent.putExtra("User_display_name",name);
resultIntent.putExtra("user_gcm_id",gcm_id);
resultIntent.putExtra("conversation_id",conversation_id);
// resultIntent.putExtra("providerLocal",mprovider);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// resultIntent.putExtra("message", message);
// check for image attachment
if (TextUtils.isEmpty(imageUrl))
{
Log.e(TAG,"image not found");
showNotificationMessage(getApplicationContext(), title, message,name,resultIntent,mprovider);
}
else
{
// image is present, show notification with image
Log.e(TAG,"image found");
showNotificationMessageWithBigImage(getApplicationContext(), title, message, resultIntent, imageUrl);
}
}
}
private void handleNotification(String message,String title,String name,Provider provider)
{
if(!NotificationUtil.isAppInBackground(getApplicationContext()))
{
Intent resultIntent = new Intent(getApplicationContext(), ChatView.class);
showNotificationMessage(getApplicationContext(), title, message,null,resultIntent, provider);
}
else
{
Intent resultIntent = new Intent(getApplicationContext(), ChatView.class);
showNotificationMessage(getApplicationContext(), title, message,null,resultIntent, mprovider);
}
}
private void showNotificationMessageWithBigImage(Context applicationContext, String title, String message, Intent resultIntent, String imageUrl)
{
notificationUtil = new NotificationUtil(applicationContext);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtil.showNotificationMessage(title, message,null,resultIntent,imageUrl);
}
private void showNotificationMessage(Context applicationContext, String title, String message,String name, Intent resultIntent,Provider mprovider)
{
// Log.d(TAG,mprovider.getId());
notificationUtil = new NotificationUtil(applicationContext);
resultIntent.putExtra("providerLocal",mprovider);
// resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtil.showNotificationMessage(title, message,name,resultIntent);
}
}
the problem is in this line :
UserDataHolder.getInstance().setmUserId(mprovider.getId());
the mprovider object is null

Toast doesn't disapear

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();

Categories

Resources