如何在特定时间发送Firebase通知?

时间:2016-09-27 06:30:18

标签: android firebase firebase-cloud-messaging

我正在尝试安排特定时间,并希望使用Firebase发送通知。我正在进行项目,我必须在比赛开始前发送通知。目前我的通知是实时工作,但我找不到任何方式在特定时间安排它。

我实时使用这个特殊代码。

 //Class extending service as it is a service that will run in background
public class NotificationFirebaseListener extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

String test;


@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    Log.e(TAG, "From: " + remoteMessage.getFrom());
    Log.e(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody() + "=====>");

    if (remoteMessage.getData().size() > 0) {
        Log.e(TAG, "Message data payload: " + remoteMessage.getData());
        test = String.valueOf(remoteMessage.getData());

    }


    sendNotification(test);


    }


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, 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("Bus Tracking")
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

    notificationManager.notify(0, notificationBuilder.build());
    }


   }

1 个答案:

答案 0 :(得分:2)

实现此目的的最佳方法是使用Firebase通知编辑器为您的应用安排通知:https://firebase.google.com/docs/notifications/

如果您想通过其他方式通过代码实现这些目标,我建议您使用ScheduledThreadPool安排通知。您可以在oracle文档中阅读更多相关信息:https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html

祝你好运!