实现通知服务的技术

时间:2011-08-18 18:08:22

标签: android architecture service notifications

我有一个主要活动,用户可以启用/禁用通知,设置通知间隔,并设置通知间隔将使用的基准时间。通知通常会相互触发约2小时。在一段时间后,累加器将达到最大值,并且将不再需要通知。

实施此类通知方案的标准方法是什么?我尝试使用postAtTime在服务中使用处理程序,但似乎有很多条件可能导致它永远不会运行。我查看了服务中的一个计时器,但是将手机置于待机状态会停止任何计时器,而且这似乎是一个坏主意。

我遇到的唯一其他选项我尚未探索,但它涉及使用AlarmManagerBroadcastReceiver。我应该放弃服务并安排重复警报吗?我的累加器达到最大值后,我需要能够禁用所有剩余的警报。

感谢您的任何意见。

2 个答案:

答案 0 :(得分:0)

如果你启动一个产生这样一个线程的服务怎么办:

thread t = new thread(new Runnable(){
    public void Run(){
       boolean notified = false;
       while( !notified ){
          if( notify_time - time > 1000 ){
              Thread.sleep(999);
          else if( notify_time - time <= 0 ){
              // START NOTIFICATION ACTIVITY
              notified = true;
          }
       }
    }
}

t.start();

我个人没有做过这样的事情,所以我不确定哪些服务可以通知用户或开始活动,但它确实有一整套可用于活动的选项,所以是的。

哦,但它只是发生在我身上,你需要使用一个处理程序,因为这里有多线程方面。

答案 1 :(得分:0)

由于我总是会有有限数量的通知,而且我可以提前计算经过的时间,AlarmManagerBroadcastReceiver的组合似乎很有效。以下是我实现此方法的方法:

我首先创建了一个BroadcastReceiver

public class NotificationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        //Get handle to system notification manager
        NotificationManager mNM = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);

        //Get message from intent
        Bundle bundle = intent.getExtras();
        CharSequence text = bundle.getString("notification_message");

        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(R.drawable.notification_icon, text, System.currentTimeMillis());

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

        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(context, context.getText(R.string.app_name),text, contentIntent);

        // Set Flags
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        // Send the notification.
        mNM.notify(R.string.notification, notification);

    }

}

然后我创建了一个使用AlarmManager创建/取消警报的类,该消息向BroadcastReceiver发送消息

public class NotificationSender {

    private AlarmManager mAlarmManager;
    private Context mContext;
    private Intent mIntent;

    public NotificationSender(Context context){

        this.mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        this.mIntent = new Intent(context, NotificationReceiver.class);
        this.mContext = context;
    }

    public void setAlarm(Long etaMillis, int accumulator){

        //Create intent to send to Receiver
        this.mIntent.putExtra("notification_message","Message");

        //Use accumulator as requestCode so we can cancel later
        PendingIntent sender = PendingIntent.getBroadcast(this.mContext, accumulator, this.mIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        //Set Alarm
        mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, etaMillis, sender);

    }

    public void cancelAlarms(){

        //requestCode (accumulator) will always be a multiple of 10 and less than 100
        for (int x = 10; x <= 100; x += 10){
            PendingIntent operation = PendingIntent.getBroadcast(this.mContext, x, this.mIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            mAlarmManager.cancel(operation);
        }

    }

    public void createAlarms(PreferenceHelper prefs){

        //Calculate time notifications are due and set an alarm for each one
        //PreferenceHelper is a class to help pull values from shared preferences
        Date currentTime = new Date();

        for (int i = prefs.getNotificationInterval(); i <= 100; i += prefs.getNotificationInterval()) {

            if (i > prefs.getAccumulator()) {

                this.setAlarm(SystemClock.elapsedRealtime() + calculateETA(i, prefs).getTime() - currentTime.getTime(), i);

            }

        }

    }

    public void refreshAlarms(PreferenceHelper prefs){

        this.cancelAlarms();
        if (prefs.isNotificationsEnabled()) this.createAlarms(prefs);

    }

}

重要的是将累加器用作requestCode,以便我们以后取消所有报警。

最后,我通过调用NotificationSender中的refreshAlarms()以及用户修改与计划通知相关的首选项,在我的活动中使用了onCreate()类。重新启动手机将清除所有警报,因此必须重新启动应用程序才能开始通知。如果系统碰巧导致进程终止,则警报仍将在适当的时间触发。