如何通过android端编码使用firebase发送notifucation?

时间:2017-03-05 10:53:25

标签: android

我尝试使用android底码使用firebase发送通知。 请建议我怎么办。

请帮帮我。 提前致谢

3 个答案:

答案 0 :(得分:1)

首先确保你有一个firebase项目,如果没有创建一个。 之后,使用此代码注册设备时存储设备ID(firebase令牌)。

class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";

/**
 * Called if InstanceID token is updated. This may occur if the security of
 * the previous token had been compromised. Note that this is called when the InstanceID token
 * is initially generated so this is where you would retrieve the token.
 */
// [START refresh_token]
@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);

    // If you want to send messages to this application instance or
    // manage this apps subscriptions on the server side, send the
    // Instance ID token to your app server.
    sendRegistrationToServer(refreshedToken);
}
// [END refresh_token]

/**
 * Persist token to third-party servers.
 * <p>
 * Modify this method to associate the user's FCM InstanceID token with any server-side account
 * maintained by your application.
 *
 * @param token The new token.
 */
private void sendRegistrationToServer(final String token) {
    new SharedPrefUtil(getApplicationContext()).saveString(Constants.ARG_FIREBASE_TOKEN, token);

    if (FirebaseAuth.getInstance().getCurrentUser() != null) {
        FirebaseDatabase.getInstance()
                .getReference()
                .child(Constants.ARG_USERS)
                .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                .child(Constants.ARG_FIREBASE_TOKEN)
                .setValue(token);
    }
}}

之后,使用以下代码向用户发送通知 -

 void sendPushNotificationToReceiver(String username,
                                            String message,
                                            String uid,
                                            String firebaseToken,
                                            String receiverFirebaseToken) {
  Log.d(":asdfasd",username+"  "+message);
    FcmNotificationBuilder.initialize()
            .title(username)
            .message(message)
            .username(username)
            .uid(uid)
            .firebaseToken(firebaseToken)
            .receiverFirebaseToken(receiverFirebaseToken)
            .send();
}

这是FCMNotificationBuilder类 -

class FcmNotificationBuilder {
public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
private static final String TAG = "FcmNotificationBuilder";
private static final String SERVER_API_KEY = "YOUR SERVER API KEY";
private static final String CONTENT_TYPE = "Content-Type";
private static final String APPLICATION_JSON = "application/json";
private static final String AUTHORIZATION = "Authorization";
private static final String AUTH_KEY = "key=" + SERVER_API_KEY;
private static final String FCM_URL = "https://fcm.googleapis.com/fcm/send";
// json related keys
private static final String KEY_TO = "to";
private static final String KEY_NOTIFICATION = "notification";
private static final String KEY_TITLE = "title";
private static final String KEY_TEXT = "text";
private static final String KEY_DATA = "data";
private static final String KEY_USERNAME = "username";
private static final String KEY_UID = "uid";
private static final String KEY_FCM_TOKEN = "fcm_token";

private String mTitle;
private String mMessage;
private String mUsername;
private String mUid;
private String mFirebaseToken;
private String mReceiverFirebaseToken;

private FcmNotificationBuilder() {

}

public static FcmNotificationBuilder initialize() {
    return new FcmNotificationBuilder();
}

public FcmNotificationBuilder title(String title) {
    mTitle = title;
    return this;
}

public FcmNotificationBuilder message(String message) {
    mMessage = message;
    return this;
}

public FcmNotificationBuilder username(String username) {
    mUsername = username;
    return this;
}

public FcmNotificationBuilder uid(String uid) {
    mUid = uid;
    return this;
}

public FcmNotificationBuilder firebaseToken(String firebaseToken) {
    mFirebaseToken = firebaseToken;
    return this;
}

public FcmNotificationBuilder receiverFirebaseToken(String receiverFirebaseToken) {
    mReceiverFirebaseToken = receiverFirebaseToken;
    return this;
}

public void send() {
    RequestBody requestBody = null;
    try {
        requestBody = RequestBody.create(MEDIA_TYPE_JSON, getValidJsonBody().toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }

    Request request = new Request.Builder()
            .addHeader(CONTENT_TYPE, APPLICATION_JSON)
            .addHeader(AUTHORIZATION, AUTH_KEY)
            .url(FCM_URL)
            .post(requestBody)
            .build();

    Call call = new OkHttpClient().newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.e(TAG, "onGetAllUsersFailure: " + e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.e(TAG, "onResponse: " + response.body().string());
        }
    });
}

private JSONObject getValidJsonBody() throws JSONException {
    JSONObject jsonObjectBody = new JSONObject();
    jsonObjectBody.put(KEY_TO, mReceiverFirebaseToken);

    JSONObject jsonObjectData = new JSONObject();
    jsonObjectData.put(KEY_TITLE, mTitle);
    jsonObjectData.put(KEY_TEXT, mMessage);
    jsonObjectData.put(KEY_USERNAME, mUsername);
    jsonObjectData.put(KEY_UID, mUid);
    jsonObjectData.put(KEY_FCM_TOKEN, mFirebaseToken);
    jsonObjectBody.put(KEY_DATA, jsonObjectData);

    return jsonObjectBody;
}}

并通常我们使用服务接收通知。 这在我的聊天应用程序中对我有用,希望它也能帮到你。

答案 1 :(得分:0)

首先要获取要向其发送通知的用户的令牌。 然后我在AsyncTask中使用此代码

protected String doInBackground(String... strings) {
        try{
            JSONObject jo = new JSONObject();
            jo.put("message", "<Message>"));
            jo.put("title", "<Message Title>");

            JSONObject mainObj = new JSONObject();
            mainObj.put("to",<TOKEN_OF_DEVICE>);
            mainObj.put("data", jo);

            URL url = new URL("https://android.googleapis.com/gcm/send");
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", "key=<API_KEY>");
            connection.setDoOutput(true);

            //Log.e("sent",mainObj.toString());
            DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
            dStream.writeBytes(mainObj.toString());
            dStream.flush();
            dStream.close();

            String line;
            int responseCode = connection.getResponseCode();
            //Log.e("code", responseCode+" hi");
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder responseOutput = new StringBuilder();
            while((line = br.readLine()) != null ){
                responseOutput.append(line);
            }
            br.close();
            //Log.e("output", responseOutput.toString());
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

答案 2 :(得分:0)

首先,从Android Studio将Firebase连接到您的项目。 生成令牌 点击链接Firebase Notification

示例github代码链接是Github code

 public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

/**
 * Called when message is received.
 *
 * remoteMessage Object representing the message received from Firebase Cloud Messaging.
 */
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // [START_EXCLUDE]
    // There are two types of messages data messages and notification messages. Data messages are handled
    // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
    // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
    // is in the foreground. When the app is in the background an automatically generated notification is displayed.
    // When the user taps on the notification they are returned to the app. Messages containing both notification
    // and data payloads are treated as notification messages. The Firebase console always sends notification
    // messages. 
    // [END_EXCLUDE]

    // TODO(developer): Handle FCM messages here.
    // Not getting messages here?  
   // Log.d(TAG, "From: " + remoteMessage.getFrom());
    sendNotification(remoteMessage.getNotification().getBody());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
     //   Log.d(TAG, "Message data payload: " + remoteMessage.getData());
    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
       // Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
}
// [END receive_message]

/**
 * Create and show a simple notification containing the received FCM message.
 *
 * @param messageBody FCM message body received.
 */
private void sendNotification(String messageBody) {
    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)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Title")
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

}