- Android Push Notification Using Firebase and Advanced REST Client
- Notifications Overview
- 1. Notification Message:
- 2. Data Message:
- 3. Messages with both notification and data payload:
- Let’s Code
- Config.java
- MyFirebaseInstanceService.java
- MyFirebaseMessagingService.java
- Advanced REST Client
- Conclusion
- Resources:
- Android Firebase Rest API Authentication
- 2 Answers 2
- REST API
- About Firebase tokens
- Use the Cloud Firestore REST API
- Authentication and authorization
- Working with Firebase ID tokens
- Working with Google Identity OAuth 2.0 tokens
- Authenticating with an access token
- Making REST calls
- Methods
- v1.projects.databases.documents
- v1.projects.databases.collectionGroups.indexes
- Error Codes
Android Push Notification Using Firebase and Advanced REST Client
Dec 14, 2018 · 7 min read
After spending four days juggling between various resources, writing codes and deleting it again and again, I finally learned how to successfully implement Push Notification in android using Firebase and ARC in a not so complex way. Stick along as I walk you through the process.
So, before we get into coding and stuff let us develop a basic understanding of what are notifications and how do they work.
Notifications Overview
A notification is a message tha t Android displays outside your app’s UI to provide the user with reminders, communication from other people, or other timely information from your app. Users can tap the notification to open your app or take an action directly from the notification.
The design of a notification is determined by system templates — your app simply defines the contents for each portion of the template. Some details of the notification appear only in the expanded view.
The most common parts of a notification are indicated in figure 7 as follows:
For more information about how to create a notification with these features and more, read Create a Notification.
Using Firebase Cloud Messaging you can send three types of messages i.e Notification Message, Data Message, and message with both Notification & Data Payload.
1. Notification Message:
Notification messages are handled by firebase SDK itself. Typically the notification message contains a title, message, icon etc., These messages can be sent from firebase console UI. By sending this kind of messages, you won’t get much control over the notification. The notification will be shown automatically when the app is in the background.
2. Data Message:
Data messages have to be handled by the Android app. You can add this kind of messages if you want to send some additional data along with the notification. But sending these messages through firebase console is not possible. You need to have a server-side logic to send the notification using Firebase API. You need to use data key when sending this message.
3. Messages with both notification and data payload:
A message can also contain both notification and data payload. When these kinds of messages are sent, it will be handled in two scenarios depending upon app state (background/foreground). For these messages, we can use both notification and data keys.
When in the background — Apps receive the notification payload in the notification tray and only handle the data payload when the user taps on the notification.
When in the foreground — App receives a message object with both payloads available.
Let’s Code
First things first, create a new project empty activity and add the Firebase dependencies for Cloud Messaging. You can find the latest dependencies in the Cloud Messaging Android Developer Docs over here. Or you can go the easy-peasy way by adding integrating the Firebase and Cloud messaging directly from the Android Studio. Go to Tools>FIrebase, select Cloud Messaging, and set it up.
Once done with the Firebase setup, we’ll get started with the coding part.
Create two packages, Congif, and Services. Now add the following Java classes:
- Config: Config.java
- Services: MyFirebaseInstanceService.java and MyFirebaseMessagingService.java
Config.java
This class is kind of helper class used to store some useful information retrieved from data being received from the server. It’s optional to create this class but I would suggest you create one to improve understandability of the app. This information is further used in the app at various places like displaying the notification title, notification content, image etc.
Setup this class as follow:
MyFirebaseInstanceService.java
On initial startup of your app, the FCM SDK generates a registration token for the client app instance. If you want to target single devices or create device groups, you’ll need to access this token.
You can easily access the token’s value by creating a new class which extends FirebaseInstanceIdService . In that class, call getToken within onTokenRefresh , and log the value as shown:
The onTokenRefress() callback fires whenever a new token is generated.
Also, add the services to your manifest file in the section:
Now let’s get to the real part.
MyFirebaseMessagingService.java
If you wish to do any message handling beyond receiving notifications on apps in the background we need to create this create this service. It extends FirebaseMesasagingService. This service is necessary to receive notifications in foregrounded apps, to receive data payload, to send upstream messages, and so on.
Let me just explain you stepwise what we’re going to do in this
- First of all, we’ll create an onMessageRecieved() method to handle the incoming messages.
- We’ll perform a check if the message contains some data, if yes, we’ll forward it to next method i.e., getImage().
- In this method retrieve some useful information from the message and add it to the Config class variable. Also, we’ll be fetching an image to be displayed in the notification using the Piccaso library.
- Once the image has been fetched it’ll be passed on to the sendNotification() method and we’ll display the notification.
Don’t forget to add the Picasso library dependency:
Code for the class:
Finally, we’re done with the coding part.
Now we’ll move on to the Advanced REST Client part.
Advanced REST Client
Open up Google Chrome and download Advanced REST Client extension from the Chrome Web Store. ARC is a helper program to create and test custom HTTP requests.
Once downloaded setup the ARC as follows:
Once you have set up the headers, move to the Body tab and set it up as follow:
You can copy the JSON part from below:
This JSON contains the data payload that our message from the server to the device is going to contain and will be used to display the notification. All the keys are self-explanatory except the “to” key.
Let’s focus on this last “to” key-value pair for a while. This key-value pair specifies to whom are we going to send the notifications to. We might be targetting a single person, a segment of users of our app or the entire user base of our app.
In case we want to send the notification to a single user we replace the “ to” value by the token generated by the device of the user.
In case we want to send notifications to all the users just leave the “to” value as it is in the code. Also, we need to add the following line to our MyFirebaseInstanceService.java class:
You can always read more about topic messaging from here.
Now press the POST button in order to receive the notifications.
That’s it. Now, let your users know your presence and keep them engaged to your app. Till the next buzz…
Conclusion
Sending notification to a group of people isn’t as tough a task as it may seem at first. Understanding the working behind and reading Google’s Android Developer Docs surely give you an upper hand but at times might not provide you the just solution you’ve been looking for. I hope this article helped you to ease with the task of sending notifications.
Resources:
Do let me know about any mistakes that I made or any concept that I overlooked. Criticism and improvements are always welcomed.
Источник
Android Firebase Rest API Authentication
I’m currently developing an app using Firebase Realtime database, however I’ve opted to omit using the SDK to retrieve data from the db. The reason being I don’t want my code to be so closely tied with FireBase as once the app is built the api itself will be moving to a custom rest based api.
I’ve implemented the api calls using REST with Firebase as per the docs without issue — POST, GET, DELETE etc..
The issue I have is if I enable any kind of authentication on the database, according to the docs I need to send «access_token» with the request however I don’t know where to retrieve this from. firebaseUser.getToken(true) returns what looks to be a JWT token that isn’t recognised if I send it as «access_token» . I get 401 Unauthorized
I also followed the instructions to setup a service account which seems to generate a token that works but then it doesn’t uniquely identify the user.
So my question is can anyone point me in the direction of how to get the required access token that identifies which user is accessing that api? The login options my Firebase project supports are Google, Facebook & Twitter.
2 Answers 2
If you are looking for the different tokens or IDs from each one of the different authentication modes, you should implement differences APIs for each one of them:
REST API
To retrieve an access token you need to use a service account. Please see the guide for using Google Service Accounts. You can create a service account credential in your Firebase project from the Service Accounts section of the Firebase console.
As an example, one way to generate an appropriate oauth2 token is with the Java google-api-client.
A successful request will be indicated by a 200 OK HTTP status code. The response contains the data being retrieved:
The Database REST API accepts access_token= on the query string or header Authorization: Bearer to authenticate a request with a service account.
The following example demonstrates how you might use this with a database containing user names. You would replace [PROJECT_ID] with the identifier of your Firebase project.
You should add the Facebook SDK to your application and implement a LoginButton and LoginManager items asking for some information as public_profile an email. It’s pretty annoying to work with Facebook SDK . An Example code about how to add it is this:
Also, inside the developers console from Facebook you should create an account, configure a new project with your app package name and add the SHA keys for debug and release versions of your app. After do all this things, you will successfully retrieve a token from the LoginResult object using the method getAccessToken()
You can read more about this in the official documentation.
Google is easier because it is already connected to Firebase, you should add to your Gradle google play services and add a google services JSON file already configured to your application. You can get it from your Firebase console.
After this, you will need to configure a GoogleSignInOptions item using the id from your JSON file:
After this you will just need to make a intent to the GoogleSignInApi in your app and wait for the onActivityResult callback:
After this you will be able to retrieve the token from the GoogleSignInAccount item. Remember to configure different SHA keys for debug or release versions of your app or Google Sign in will stop working in release version.
You can read more about this in the official Firebase documentation
About Twitter, I didn’t work with Twitter, so I can’t really help you at the moment, but I suggest you to check the Twitter developer documentation and the firebase Twitter implementation post.
I will try to edit this when I will make some pocs at home checking how it works.
About Firebase tokens
Another good point to have knowledge about is the Firebase id tokens, which are unique per user and connection in your app, allowing you to check if the same account is trying to log from different devices at the same time, or send FCM Cloud Messages to use online notification in your app.
To retrieve it, you should use the FirebaseInstanceId object using the API and the method FirebaseInstanceId.getInstance() . This will retrieve you a FirebaseInstance unique ID for your user when he/she login in your app.
You can retrieve his token with the idInstance.getToken() and store it whenever you want in your application to check it and manage it in the way that you want.
The Firebase documentation about this is not pretty clear, so I recommend you to use the next link, it helped me a lot to implement it in my app.
Источник
Use the Cloud Firestore REST API
While the easiest way to use Cloud Firestore is to use one of the native client libraries, there are some situations when it is useful to call the REST API directly.
The REST API can be helpful for the following use cases:
- Accessing Cloud Firestore from a resource-constrained environment, such as an internet of things (IoT) device, where running a complete client library is not possible.
- Automating database administration or retrieving detailed database metadata.
If you are using a gRPC-supported language, consider using the RPC API rather than the REST API.
Authentication and authorization
For authentication, the Cloud Firestore REST API accepts either a Firebase Authentication ID token or a Google Identity OAuth 2.0 token. The token you provide affects your request’s authorization:
Use Firebase ID tokens to authenticate requests from your application’s users. For these requests, Cloud Firestore uses Cloud Firestore Security Rules to determine if a request is authorized.
Use a Google Identity OAuth 2.0 token and a service account to authenticate requests from your application, such as requests for database administration. For these requests, Cloud Firestore uses Identity and Access Management (IAM) to determine if a request is authorized.
Working with Firebase ID tokens
You can attain a Firebase ID token in two ways:
By retrieving a user’s Firebase ID token, you can make requests on behalf of the user.
For requests authenticated with a Firebase ID token and for unauthenticated requests, Cloud Firestore uses your Cloud Firestore Security Rules to determine if a request is authorized.
Working with Google Identity OAuth 2.0 tokens
You can generate an access token by using a service account with a Google API Client Library or by following the steps in Using OAuth 2.0 for Server to Server Applications. You can also generate a token with the gcloud command-line tool and the command gcloud auth application-default print-access-token .
This token must have the following scope to send requests to the Cloud Firestore REST API:
If you authenticate your requests with a service account and a Google Identity OAuth 2.0 token, Cloud Firestore assumes that your requests act on behalf of your application instead of an individual user. Cloud Firestore allows these requests to ignore your security rules. Instead, Cloud Firestore uses IAM to determine if a request is authorized.
You can control the access permissions of service accounts by assigning Cloud Firestore IAM roles.
Authenticating with an access token
After you obtain either a Firebase ID token or a Google Identity OAuth 2.0 token, pass it to the Cloud Firestore endpoints as an Authorization header set to Bearer
Making REST calls
All REST API endpoints exist under the base URL https://firestore.googleapis.com/v1/ .
To create a path to a document with the ID LA in the collection cities under the project YOUR_PROJECT_ID you would use the following structure.
To interact with this path, combine it with the base API URL.
The best way to begin experimenting with the REST API is to use the API Explorer, which automatically generates Google Identity OAuth 2.0 tokens and allows you to examine the API.
Methods
Below are brief descriptions of the two most important method groups. For a complete list, see the REST API reference or use the API Explorer.
v1.projects.databases.documents
Perform CRUD operations on documents, similar to those outlined in the add data or get data guides.
v1.projects.databases.collectionGroups.indexes
Perform actions on indexes such as creating new indexes, disabling an existing index, or listing all current indexes. Useful for automating data structure migrations or synchronizing indexes between projects.
Also enables retrieval of document metadata, such as the list of all fields and subcollections for a given document.
Error Codes
When a Cloud Firestore request succeeds, the Cloud Firestore API returns an HTTP 200 OK status code and the requested data. When a request fails, the Cloud Firestore API returns an HTTP 4xx or 5xx status code and a response with information about the error.
The following table lists recommended actions for each error code. These codes apply to the Cloud Firestore REST and RPC APIs. The Cloud Firestore SDKs and client libraries may not return these same error codes.
Canonical Error Code | Description | Recommended Action |
---|---|---|
ABORTED | The request conflicted with another request. | For a non-transactional commit: Retry the request or re-structure your data model to reduce contention. For requests in a transaction: |
ALREADY_EXISTS | The request tried to create a document that already exists. | Do not retry without fixing the problem. |
DEADLINE_EXCEEDED | The Cloud Firestore server handling the request exceeded a deadline. | Retry using exponential backoff. |
FAILED_PRECONDITION | The request did not meet one of its preconditions. For example, a query request might require an index not yet defined. See the message field in the error response for the precondition that failed. | Do not retry without fixing the problem. |
INTERNAL | The Cloud Firestore server returned an error. | Do not retry this request more than once. |
INVALID_ARGUMENT | A request parameter includes an invalid value. See the message field in the error response for the invalid value. | Do not retry without fixing the problem. |
NOT_FOUND | The request attempted to update a document that does not exist. | Do not retry without fixing the problem. |
PERMISSION_DENIED | The user is not authorized to make this request. | Do not retry without fixing the problem. |
RESOURCE_EXHAUSTED | The project exceeded either its quota or the region/multi-region capacity. | Verify that you did not exceed your project quota. If you exceeded a project quota, do not retry without fixing the problem. Otherwise, retry with exponential backoff. |
UNAUTHENTICATED | The request did not include valid authentication credentials. | Do not retry without fixing the problem. |
UNAVAILABLE | The Cloud Firestore server returned an error. | Retry using exponential backoff. |
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Источник