Last active
February 20, 2020 09:12
-
-
Save Abdullamhd/d58e36fd4e852de3708b1f693857f5ee to your computer and use it in GitHub Desktop.
sending push notification from java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; | |
import com.google.auth.oauth2.GoogleCredentials; | |
import com.google.firebase.FirebaseApp; | |
import com.google.firebase.FirebaseOptions; | |
import com.google.firebase.messaging.FirebaseMessaging; | |
import com.google.firebase.messaging.FirebaseMessagingException; | |
import com.google.firebase.messaging.Message; | |
import com.google.firebase.messaging.Notification; | |
import org.junit.Before; | |
import org.junit.Test; | |
import java.io.FileInputStream; | |
import java.io.IOException; | |
import java.util.Arrays; | |
public class NotificationService { | |
@Before | |
public void init() throws IOException { | |
} | |
@Test | |
public void sendPushTest() throws IOException, FirebaseMessagingException { | |
initFirebaseApp(); | |
String accessToken = getAccessToken(); | |
//@abdullah please be sure token is up to date | |
String registrationToken = "your token for test"; | |
Notification notification = Notification.builder() | |
.setTitle("from Server") | |
.setBody("Message Body") | |
.build(); | |
Message message = Message.builder() | |
.putData("dataType", "DataValue") | |
.putData("DataType2", "DataValue2") | |
.setToken(registrationToken) | |
.setNotification(notification) | |
.build(); | |
String response = FirebaseMessaging.getInstance().send(message); | |
System.out.println("Successfully sent message: " + response); | |
} | |
void initFirebaseApp() throws IOException{ | |
FileInputStream serviceAccount = | |
new FileInputStream("service/service_account.json"); | |
FirebaseOptions options = new FirebaseOptions.Builder() | |
.setCredentials(GoogleCredentials.fromStream(serviceAccount)) | |
.setDatabaseUrl("https://veemu-33e81.firebaseio.com") | |
.build(); | |
FirebaseApp.initializeApp(options); | |
} | |
private static String getAccessToken() throws IOException { | |
GoogleCredential googleCredential = GoogleCredential | |
.fromStream(new FileInputStream("service/service_account.json")) | |
.createScoped(Arrays.asList( | |
"https://www.googleapis.com/auth/admin.directory.notifications", | |
"https://www.googleapis.com/auth/firebase.messaging" | |
)); | |
googleCredential.refreshToken(); | |
return googleCredential.getAccessToken(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment