Only me: Android Studio $cd /dev/Android_code/Functions_Firebase
1. Install Firebase CLI and install Node.js
2. $firebase login
3. Create a new directory
$cd /Users/andres/dev/firebase_Learning/functionsDemo/
4. Open terminal and enter command: $firebase init functions
Command installs functions dependencies
$cd /Users/andres/dev/firebase_Learning/functionsDemo/functions
5. Add your function to file index.js
Add this code to index.js
var functions = require('firebase-functions');
var admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/articles/{articleId}')
.onWrite(event => {
// Grab the current value of what was written to the Realtime Database.
var eventSnapshot = event.data;
var str1 = "Author is ";
var str = str1.concat(eventSnapshot.child("author").val());
console.log(str);
var topic = "android";
var payload = {
data: {
title: eventSnapshot.child("title").val(),
author: eventSnapshot.child("author").val()
}
};
// Send a message to devices subscribed to the provided topic.
return admin.messaging().sendToTopic(topic, payload)
.then(function (response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
});
});
To deploy run:
$firebase deploy --only functions
Part 2. Create Android App
1. Install Android Studio
2. Create new empty project
3. Below files that we need to create
Architecture:
Model - Article.java
Presenter - MainActivity.java
- MyFirebaseMessagingService.java
4. Open and add MainActivity.java
public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);FirebaseMessaging.getInstance().subscribeToTopic("android");final FirebaseDatabase database = FirebaseDatabase.getInstance();final EditText titleEditText = (EditText) findViewById(R.id.et_title);final EditText authorEditText = (EditText) findViewById(R.id.et_author);Button submitButton = (Button) findViewById(R.id.btn_submit);submitButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {DatabaseReference myRef = database.getReference("articles").push();Article article = new Article(titleEditText.getText().toString(),authorEditText.getText().toString());myRef.setValue(article);}});}}
4.5 Add this to main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="code.andres.com.functions_firebase.MainActivity"> <EditText android:id="@+id/et_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Title" /> <EditText android:id="@+id/et_author" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Author" /> <Button android:id="@+id/btn_submit" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Submit" /> </LinearLayout>
public class Article { public String title; public String author; public Article() { // Default constructor required for calls to DataSnapshot.getValue(Article.class) } public Article(String title, String author) { this.title = title; this.author = author; } }6. Create new java class Article.java
public class MyFirebaseMessagingService extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { // Check if message contains a data payload. if (remoteMessage.getData().size() > 0) { showNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("author")); } // Check if message contains a notification payload. if (remoteMessage.getNotification() != null) { } } private void showNotification(String title, String author) { Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT); Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setContentTitle("New Article: " + title) .setSmallIcon(R.mipmap.ic_launcher) .setContentText("By " + author) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); } }
7. Add this to AndroidManifext.xml
<service android:name=".MyFirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service>8. Add to build.gradle
compile 'com.google.firebase:firebase-database:10.0.1'compile 'com.google.firebase:firebase-messaging:10.0.1'
refrenence:
https://code.tutsplus.com/tutorials/serverless-apps-with-firebase-cloud-functions--cms-28557