报警管理器 - 调度多个非重复事件 [英] Alarm Manager - Scheduling multiple Non-repeating events

查看:114
本文介绍了报警管理器 - 调度多个非重复事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android的报警管理,我们怎么能安排多个报警它们是不重复的,但没有固定的时间间隔重复?我不能使用setRepeating'函数作为警报不具有任何重复的图案。

予有存储在SQLite数据库表中的警报时间和活动应该选择从该表中的日期和时间,并设置报警。

如果在一个循环中,我们设置不同的警报,然后只保留最后一个。 我从后阅读:如何创建多个报警

它告诉附加的唯一ID的意图,然后设置单独的报警事件。但是,这并不为我工作。

有没有需要我们在清单文件添加到照顾这唯一的id什么?

在code在活动RegularSchedule'是,它只创建一个报警事件:

 而(notifCursor.moveToNext()){
            意向意图=新的意图(RegularSchedule.this,
                    RepeatingAlarm.class);

            //光标返回第一列作为唯一的ID
            intent.setData(Uri.parse(计时器:+ notifCursor.getInt(0)));

            PendingIntent发送= PendingIntent.getBroadcast(
                    RegularSchedule.this,0,意图,0);

            //以毫秒为单位设置时间取自数据库表
            cal.setTimeInMillis(notifCursor.getLong(1));

            AlarmManager AM =(AlarmManager)getSystemService(ALARM_SERVICE);
            am.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),发送方);
        }
 

请让我知道更多详情或code段是必需的。

清单文件(这里RepeatingAlarm延伸BroadcastReceiver的):

 <接收机器人:user_alerts.RepeatingAlarm名称=安卓程序=:远程/>

    <活动机器人:user_alerts.RegularScheduleNAME =
        机器人:标签=@字符串/ reg_schedule_title安卓主题=@安卓风格/ Theme.Light>
    < /活性GT;
 

RepeatingAlarm:

 公共类RepeatingAlarm扩展的BroadcastReceiver {
@覆盖
公共无效的onReceive(上下文的背景下,意图意图){
    NotificationManager mNotificationManager =(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
.......
    //该PendingIntent来,如果用户选择此通知发布我们的活动
    意图notificationIntent =新的意图(背景下,DisplayReminder.class);
    PendingIntent contentIntent = PendingIntent.getActivity(上下文,0,notificationIntent,0);

    //设置为显示在通知面板的意见信息。
    notification.setLatestEventInfo(背景下,contentTitle,contentText,contentIntent);
    notification.defaults | = Notification.DEFAULT_SOUND;
    notification.defaults | = Notification.DEFAULT_VIBRATE;
    notification.defaults | = Notification.DEFAULT_LIGHTS;

    mNotificationManager.notify(2425,通知);
 

解决方案

这是为我工作。我共享的解决方案,以便其他人可以受益,并找到快速的解决这个问题。

我欢迎任何其他投入,以投入更多的光线在该解决方案的技术细节,以及为什么某些事情的工作和别人不一样:)

(1)首先,清单文件: 请确保您有接收器类具有的BroadcastReceiver。

 <接收机器人:RepeatingAlarm名称=安卓程序=:远程>
        <意向滤光器>
            <数据机器人:计划=计时器/>
        &所述; /意图滤光器>
    < /接收器>
 

请注意,类是主软件包的一部分。如果它是在一些子包,请移动到主包。主要的包就是你的'清单'的标签定义。

意图滤波器用于定义操作和数据。你可以把类的活动在这里,这是会从您的待处理的意图调用。但我发现,如果在清单中定义'动作',它并没有在活动显示动态值。它只是显示静态值。很奇怪。如果在同一个问题搞定,不要把行动清单中,而把它的BroadcastReceiver类悬而未决的意图的一部分。

数据标签是你要放什么独特的意图动态URI,同时调度使用AlarmManager不同的警报。请参考下面的步骤的更多细节。

(2)活动课中,你要使用AlarmManager调度报警: 我使用数据库来存储我的闹钟时间值,然后调度使用这些值。我的光标取出由表和报警时间的独特_ID(以秒为单位自1/1/1970)。看到URI把这里是一样的你有什么清单文件。

 日历CAL = Calendar.getInstance();
    INT notifIterator = 0;

    如果(notifCursor.getCount()大于0){
        而(notifCursor.moveToNext()){
            意向意图=新的意图(MySchedule.this,
                    RepeatingAlarm.class);

            //由于同样的意图取消具有previously设置闹钟
            //目的相同
            //改变原意为每个闹钟事件让每一个报警
            //获取
            //计划正常。
            intent.setData(Uri.parse(计时器:+ notifCursor.getInt(0)));

            PendingIntent发送= PendingIntent.getBroadcast(
                    MySchedule.this,0,意图,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION);

            cal.setTimeInMillis(notifCursor.getLong(1)* 1000);

            AlarmManager AM =(AlarmManager)getSystemService(ALARM_SERVICE);
            am.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),发送方);

            notifIterator ++;

            吐司mToast = Toast.makeText(
                    RegularSchedule.this,
                    提醒添加到日历成功地为
                            + android.text.format.DateFormat.format(
                                    MM / DD / YY H:MMAA
                                    cal.getTimeInMillis()),
                    Toast.LENGTH_LONG);
            mToast.show();
        }
    }
 

如果你连这样做后,没有看到报警器,检查时区该模拟器需要。有时候,我们安排了当地时区,但模拟器时间表GMT时区。如果你看一下敬酒的消息,这将帮助你弄清楚这个问题。

(3)最后一个是BroadcastReceiver的类。请注意,打开数据库,则需要使用语境:

 公共无效的onReceive(上下文的背景下,意图意图){

    //更新通知数据库表中的地位
    INT notificationId =的Integer.parseInt(intent.getData()getSchemeSpecificPart());

    DB = context.openOrCreateDatabase(DATABASE_NAME,
            SQLiteDatabase.CREATE_IF_NECESSARY,NULL);

    <<<<做数据库的东西,如获取或更新的东西>>>>

    //提起通知,使用户可以检查细节
    NotificationManager mNotificationManager =(NotificationManager)上下文
            .getSystemService(Context.NOTIFICATION_SERVICE);

    INT图标= R.drawable.icon;
    CharSequence的tickerText =文本;
    时长= System.currentTimeMillis的();

    通知通知=新的通知(图标,tickerText时);

    //计数的通知数
    notification.number = notifCount;

    CharSequence的contentTitle =你的称号;
    CharSequence的contentText =您的通知文本;

    //该PendingIntent来,如果用户选择此推出我们的活动
    // 通知
    意图notificationIntent =新的意图(背景下,DisplayReminder.class);
    PendingIntent contentIntent = PendingIntent.getActivity(上下文,0,
            notificationIntent,0);


    //设置为显示在通知面板的意见信息。
    notification.setLatestEventInfo(背景下,contentTitle,contentText,
            contentIntent);
    notification.defaults | = Notification.DEFAULT_SOUND;
    notification.defaults | = Notification.DEFAULT_VIBRATE;
    notification.defaults | = Notification.DEFAULT_LIGHTS;

    //而不是1234或任何其它号码,使用下面EX pression有独特的通知
    //的Integer.parseInt(intent.getData()。getSchemeSpecificPart())
    mNotificationManager.notify(1234,通知);
}
 

请注意,如果你想创建单独的通知,请求ID可以通过独特的调用通知()的时候。

最后,您可以创建你想要当用户点击通知调用DisplayReminder类。

In Android Alarm Manager, how can we schedule multiple alarms which are non-repeating and do not have fixed intervals to repeat? I cannot use 'setRepeating' function as the alarms don't have any repeating pattern.

I have the alarm times stored in Sqlite database table and the activity should pick the date and time from this table and set the alarms.

If we setup different alarms in a loop, then it retains only the last one. I read from the post: How can create more than one alarm?

It tells to attach the unique Id to the intent and then setting up individual alarm events. But it didn't work for me.

Is there something we need to add in Manifest file to take care of this unique id?

The code in the activity 'RegularSchedule' is and it creates only one alarm event:

        while (notifCursor.moveToNext()) {
            Intent intent = new Intent(RegularSchedule.this,
                    RepeatingAlarm.class);

            // The cursor returns first column as unique ID             
            intent.setData(Uri.parse("timer:" + notifCursor.getInt(0)));

            PendingIntent sender = PendingIntent.getBroadcast(
                    RegularSchedule.this, 0, intent, 0);

            // Setting time in milliseconds taken from database table 
            cal.setTimeInMillis(notifCursor.getLong(1));

            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
            am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
        }

Please let me know if further details or code snippets are required.

Manifest file (here RepeatingAlarm extends BroadcastReceiver):

    <receiver android:name=".user_alerts.RepeatingAlarm" android:process=":remote" />

    <activity android:name=".user_alerts.RegularSchedule"
        android:label="@string/reg_schedule_title" android:theme="@android:style/Theme.Light">
    </activity>

RepeatingAlarm:

public class RepeatingAlarm extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
.......
    // The PendingIntent to launch our activity if the user selects this notification
    Intent notificationIntent = new Intent (context, DisplayReminder.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    // Set the info for the views that show in the notification panel.
    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notification.defaults |= Notification.DEFAULT_LIGHTS;

    mNotificationManager.notify(2425, notification);

解决方案

This is what worked for me. I'm sharing the solution so that others can benefit and find quick solution to this problem.

I welcome any other inputs to throw more light on the technicality of the solution and why certain things work and others don't :)

(1) First of all, Manifest file: Make sure that you have receiver for your class having BroadcastReceiver.

    <receiver android:name=".RepeatingAlarm" android:process=":remote">
        <intent-filter>
            <data android:scheme="timer:" />
        </intent-filter>
    </receiver>

Please note that the class is part of main package. If it is in some sub-package, please move to the main package. The main package is what you define in 'manifest' tag.

'intent-filter' is used to define 'action' and 'data'. You can put the Activity class here which is going to be called from your pending intent. But I found that if you define 'action' in manifest, it doesn't display dynamic values on the activity. It just shows static values. Quite strange. If you get in same issue, don't put 'action' in manifest, rather put it in BroadcastReceiver class as part of pending intent.

'data' tag is what you are going to put dynamic URI of unique intents while scheduling different alarms using AlarmManager. Please refer next steps for more details.

(2) Activity Class in which you are going to use AlarmManager to schedule alarms: I'm using the database to store my alarm time values and then scheduling using those values. My cursor fetches the unique _ID from the table and alarm time (in seconds since 1/1/1970). See that the URI put here is same as what you have in manifest file.

    Calendar cal = Calendar.getInstance();
    int notifIterator = 0;

    if (notifCursor.getCount() > 0) {
        while (notifCursor.moveToNext()) {
            Intent intent = new Intent(MySchedule.this,
                    RepeatingAlarm.class);

            // As the same intent cancels the previously set alarm having
            // same intent
            // changing the intent for every alarm event so that every alarm
            // gets
            // scheduled properly.
            intent.setData(Uri.parse("timer:" + notifCursor.getInt(0)));

            PendingIntent sender = PendingIntent.getBroadcast(
                    MySchedule.this, 0, intent,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION);

            cal.setTimeInMillis(notifCursor.getLong(1) * 1000);

            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
            am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);

            notifIterator++;

            Toast mToast = Toast.makeText(
                    RegularSchedule.this,
                    "Reminders added to the calendar successfully for "
                            + android.text.format.DateFormat.format(
                                    "MM/dd/yy h:mmaa",
                                    cal.getTimeInMillis()),
                    Toast.LENGTH_LONG);
            mToast.show();
        }
    }

If you don't see alarms even after doing this, check the timezone which emulator takes. Sometimes, we schedule for Local Timezone, but emulator schedules for GMT timezone. If you look at toast message, that will help you figure out this problem.

(3) Last one is BroadcastReceiver class. Please note that to open database, you will require to use the 'context':

public void onReceive(Context context, Intent intent) {

    // Update the status in the notification database table
    int notificationId = Integer.parseInt(intent.getData().getSchemeSpecificPart());

    db = context.openOrCreateDatabase(DATABASE_NAME,
            SQLiteDatabase.CREATE_IF_NECESSARY, null);

    <<<< Do DB stuff like fetching or updating something>>>>

    // Raise the notification so that user can check the details
    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    int icon = R.drawable.icon;
    CharSequence tickerText = "your text";
    long when = System.currentTimeMillis();

    Notification notification = new Notification(icon, tickerText, when);

    // Count of number of notifications
    notification.number = notifCount;

    CharSequence contentTitle = "your title ";
    CharSequence contentText = "your notification text";

    // The PendingIntent to launch our activity if the user selects this
    // notification
    Intent notificationIntent = new Intent(context, DisplayReminder.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
            notificationIntent, 0);


    // Set the info for the views that show in the notification panel.
    notification.setLatestEventInfo(context, contentTitle, contentText,
            contentIntent);
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notification.defaults |= Notification.DEFAULT_LIGHTS;

    // Instead of 1234 or any other number, use below expression to have unique notifications
    // Integer.parseInt(intent.getData().getSchemeSpecificPart())
    mNotificationManager.notify(1234, notification);
}

Note that if you want to create separate notification, the request id can be passed as unique when calling notify().

Finally, you can create DisplayReminder class which you want to call when user clicks on notification.

这篇关于报警管理器 - 调度多个非重复事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆