Skip to content

Instantly share code, notes, and snippets.

@n1lesh
Created December 18, 2017 08:31
Show Gist options
  • Save n1lesh/07b951e01ffb11b675259fcdfcdc57ed to your computer and use it in GitHub Desktop.
Save n1lesh/07b951e01ffb11b675259fcdfcdc57ed to your computer and use it in GitHub Desktop.
Sample Code for Push Notifications (FCM) on Android - Instance ID Service
package com.mynotificationsapp.android;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by What's That Lambda on 11/6/17.
*/
public class InstanceIdService extends FirebaseInstanceIdService {
public InstanceIdService() {
super();
}
@Override
public void onTokenRefresh() {
super.onTokenRefresh();
String token = FirebaseInstanceId.getInstance().getToken();
//sends this token to the server
sendToServer(token);
}
private void sendToServer(String token) {
try {
URL url = new URL("https://www.whatsthatlambda.com/store");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes("token=" + token);
connection.connect();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// Do whatever you want after the
// token is successfully stored on the server
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@theonlyanil
Copy link

Why whatsthatlambda.com/store?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment