Overriding onNewToken and getting tokens from firebase errors - android

I want to retrieve my token and i'm doing exactly as many examples says
On FirebaseMessagingService i have this
#Override
public void onNewToken(String token) {
super.onNewToken(token);
Log.e("Refreshed token:",token);
}
And i got the error
Method does not override method from it's superclass
and of course the super.onNewToken(token) has the error
cannot resolve method
On my mainactivity i have this inside OnCreate()
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( MyActivity.this, new OnSuccessListener<InstanceIdResult>() {
#Override
public void onSuccess(InstanceIdResult instanceIdResult) {
String newToken = instanceIdResult.getToken();
}
});
And the errors i get are:
Cannot resolve getInstanceId()
Cannot resolve InstanceIdResult
cannot
resolve getToken()
and Method does not override method from it's
superclass
Update
Class declaration
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();
private NotificationUtils notificationUtils;
#Override
public void onNewToken(String token) {
super.onNewToken(token);
Log.e("Refreshed token:",token);
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage == null)
return;
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
handleNotification(remoteMessage.getNotification().getBody());
}
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
try {
JSONObject json = new JSONObject(remoteMessage.getData().toString());
handleDataMessage(json);
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
}
Dependencies
implementation 'com.google.firebase:firebase-core:16.0.5'
implementation 'com.google.firebase:firebase-messaging:17.3.4'
Update v2
public class FirebaseMessagingService extends com.google.firebase.iid.zzb {
private static final java.util.Queue<java.lang.String> zzoma;
public FirebaseMessagingService() { /* compiled code */ }
#android.support.annotation.WorkerThread
public void onMessageReceived(com.google.firebase.messaging.RemoteMessage remoteMessage) { /* compiled code */ }
#android.support.annotation.WorkerThread
public void onDeletedMessages() { /* compiled code */ }
#android.support.annotation.WorkerThread
public void onMessageSent(java.lang.String s) { /* compiled code */ }
#android.support.annotation.WorkerThread
public void onSendError(java.lang.String s, java.lang.Exception e) { /* compiled code */ }
#com.google.android.gms.common.internal.Hide
protected final android.content.Intent zzp(android.content.Intent intent) { /* compiled code */ }
#com.google.android.gms.common.internal.Hide
public final boolean zzq(android.content.Intent intent) { /* compiled code */ }
#com.google.android.gms.common.internal.Hide
public final void handleIntent(android.content.Intent intent) { /* compiled code */ }
static void zzr(android.os.Bundle bundle) { /* compiled code */ }
static boolean zzal(android.os.Bundle bundle) { /* compiled code */ }

build.gradle (app):
implementation 'com.google.firebase:firebase-core:16.0.5'
implementation 'com.google.firebase:firebase-messaging:17.3.4'
extend class:
package /*package name*/;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
public class MyFcmListenerService extends FirebaseMessagingService {
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is also called
* when the Instance ID token is initially generated, so this is where
* you retrieve the token.
*/
#Override
public void onNewToken(String token) {
Log.d("TAG", "New token: " + token);
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(token); //As I understand it, you need to implement it yourself.
}
}
in tag in AndroidManifest.xml:
<service
android:name=".MyFcmListenerService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Add to your activity where you want to get a token:
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(MainActivity.this, new OnSuccessListener<InstanceIdResult>() {
#Override
public void onSuccess(InstanceIdResult instanceIdResult) {
String newToken = instanceIdResult.getToken();
}
});

Related

Reviving FCM token, but onMessageRecived is not called

I have add the below code in another app, but not working here
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "<<!!>>";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
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());
}
sendNotification("notication");
}
#Override
public void onNewToken(String token) {
Log.d(TAG, "Refreshed token: " + token);
sendRegistrationToServer(token);
}
private void scheduleJob() {
// [START dispatch_job]
OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(MyWorker.class)
.build();
WorkManager.getInstance().beginWith(work).enqueue();
// [END dispatch_job]
}
private void handleNow() {
Log.d(TAG, "Short lived task is done.");
}
private void sendRegistrationToServer(String token) {
// TODO: Implement this method to send token to your app server.
}
}

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
}

Get old notification from FCM continuesly in my app

I am using FCM to send notification for downloading a file in my android app. When my app is not running and i send FCM then I get all the notifications that I send earlier and new one continuously.
How to overcome this?
Here is my MyFirebaseMessagingService class.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("data", "onMessageReceived: firebase called");
Map<String, String> data = remoteMessage.getData();
String url = data.get("file_url");
Intent broadcast_intent = new Intent();
broadcast_intent.putExtra(MainActivity.FIREBASE_URL, url); broadcast_intent.setAction(MainActivity.FIREBASE_URL_BROADCAST);
sendBroadcast(broadcast_intent);
}
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
#Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
}

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

Categories

Resources