写firebase函数和调度时间发送通知android

时间:2017-07-08 18:53:12

标签: android firebase firebase-realtime-database cron google-cloud-functions

我有一个函数触发firebase数据库节点的日期,并在用户向Android设备输入数据时发送通知。我想安排计时器使用外部cron作业发送此通知。我有下面的代码,一旦用户输入日期成功发送通知。任何人都可以帮助我,因为我发现它真的很难理解。我需要修改哪些才能使它工作?

这是index.js

    var functions = require('firebase-functions');
var admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/Users/{userId}/description/{descId}')
        .onWrite(event => {

        // Grab the current value of what was written to the Realtime Database.
        var eventSnapshot = event.data;
        var str1 = "Your profile title is ";
        var str2 = "Date is ";
        var strProfile = str1.concat(eventSnapshot.child("title").val());
        var strStatus = str2.concat(eventSnapshot.child("date").val());
        console.log(strProfile);
        console.log(strStatus)

        var topic = "android";
        var payload = {
            data: {
                title: eventSnapshot.child("title").val(),
                date: eventSnapshot.child("date").val()
            }
        };

        // Send a message to devices subscribed to the provided topic.
        return admin.messaging().sendToTopic(topic, payload)
            .then(function (response) {
                // See the MessagingTopicResponse reference documentation for the
                // contents of response.
                console.log("Successfully sent message:", response);
            })
            .catch(function (error) {
                console.log("Error sending message:", error);
            });
        });

MyFirebaseMessagingService活动

    public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            showNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("date"));
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {

        }
    }

    private void showNotification(String title, String date) {
        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)
                .setContentTitle("title  is " + title)
                .setSmallIcon(R.drawable.alex)
                .setContentText("your deadline date is " + date)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

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

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

}

1 个答案:

答案 0 :(得分:0)

您可以在AlarmManager的帮助下轻松实现这一目标。当用户输入日期时,获取该日期并为该特定日期和时间设置警报,如下所示:

Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar

Calendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR));
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 32);
cal.set(Calendar.SECOND, cur_cal.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND));
cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE));
cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));
Intent intent = new Intent(ProfileList.this, 
IntentBroadcastedReceiver.class);
PendingIntent pintent = PendingIntent.getService(ProfileList.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pintent);

然后你必须设置一个广播接收器来处理这个事件。在广播接收器的onReceive()方法中,您将调用您的Web服务将请求发送到您的服务器。

public class MyBroadcastReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {

    // Call your web-service here.

}
}

别忘了在清单中定义接收器:

<receiver android:name=".MyBroadcastReceiver" >