Reputation: 114
i am trying to implement notification in android app. i implement the code and receiving notification into my android device from Firebase panel directly. and when i trying to use node js method its not working . i am using third party web services in android device please
below code is my node js function code. please help me i already check and search on many site but this type of problem not founded , thanks in advance
this same code i already implement in my old application and work fine but those application fully connected with firebase . but this current app i am using web services.
const functions = require('firebase-functions');
var admin = require("firebase-admin");
var serviceAccount = require("./xxxxxxx-xxxxx-firebase-adminsdk-xxxxx-xxxxxxxxxx.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://xxxxxxx-xxxxx.firebaseio.com"
});
//Notification Method
exports.sendNotification = functions.database.ref("/Notifications/{first_id}")
.onCreate((snapshot,context)=>{
const id=context.params.first_id;
const data2=snapshot.val()
var token=data2.Token
var text= data2.Name
// Send a message to the device corresponding to the provided
// registration token.
return Promise.all([token,text]).then(results =>{
var payload = {
data:{
username: "name",
usertoken: token,
notificationTitle: "name1",
notificationMessage: "ntest"
}
};
return admin.messaging().sendToDevice(token, payload)
})
})
<!-- Notification Services Manifest file-->
<service
android:name=".FCM_Serivces.MyFirebaseNotificationService" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/> <!-- Get Notification -->
</intent-filter>
</service>
<service
android:name=".FCM_Serivces.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> <!-- Get Token Id -->
</intent-filter>
</service>
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
String token = FirebaseInstanceId.getInstance().getToken();
registerToken(token);
}
private void registerToken(String token) {
}
}
//Java Class
public class MyFirebaseNotificationService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getNotification() != null) {
SendNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
}
}
private void SendNotification(String title,String msg){
Intent intent=new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
Uri defaultSound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder=new NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(msg);
notificationBuilder.setAutoCancel(false);
notificationBuilder.setSound(defaultSound);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notificationBuilder.build());
}
}
//Gradle
implementation 'com.google.firebase:firebase-database:16.0.4'
implementation 'com.google.firebase:firebase-functions:16.1.3'
implementation 'com.google.firebase:firebase-messaging:17.3.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'org.apache.httpcomponents:httpclient:4.5.8'
//i use this code in click lister for send data with token for notification
DatabaseReference referenceNotification =FirebaseDatabase.getInstance().getReference().child("Notifications").push();
Map<String,String> mMap=new HashMap<>();
mMap.put("Name","01");
mMap.put("Token", FirebaseInstanceId.getInstance().getToken());
mMap.put("Title","Test");
mMap.put("Message","1234");
referenceNotification.setValue(mMap)
i receive on log this result of function
"Function execution took 501 ms, finished with status: 'ok'"
Upvotes: 3
Views: 190
Reputation: 3576
The method getToken() is deprecated. You can use getInstanceId() instead.
For getting device token and saving it for further use:
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(this, instanceIdResult -> {
String newToken = instanceIdResult.getToken();
Log.e("newToken", newToken);
getActivity().getPreferences(Context.MODE_PRIVATE).edit().putString("myToken", newToken).apply();
});
On saving to database:
mMap.put("Token",
getActivity().getPreferences(Context.MODE_PRIVATE).getString("myToken", "empty :("));
Now use the token send a notification using node server:
//Notification Method
exports.sendNotification = functions.database.ref("/Notifications/{first_id}")
.onCreate((snapshot,context)=>{
const id=context.params.first_id;
const data2=snapshot.val()
var token=data2.Token
var text= data2.Name
var payload = {
data:{
username: "name",
usertoken: token,
notificationTitle: "name1",
notificationMessage: "ntest"
},
token: deviceRegistrationToken
};
admin.messaging().send(payload)
.then(() => {
console.log("success");
return null;
})
.catch(error => {
console.log(error);
});
}
Upvotes: 1