安卓 PhoneGap 中的状态栏通知

14

我在状态栏通知方面遇到了问题,我已经通过创建插件完成了一次性显示的代码。但是我希望每隔10分钟显示一次它。因此,我使用AlarmManager来生成每隔10分钟通知的代码。但是它没有调用FirstQuoteAlarm类的onReceive(Context ctx, Intent intent)方法。

我有以下关于显示通知和AlarmManager的代码:

public void showNotification( CharSequence contentTitle, CharSequence contentText ) {
    int icon = R.drawable.nofication;
    long when = System.currentTimeMillis();

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

    Intent notificationIntent = new Intent(ctx, ctx.getClass());
    PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

    mNotificationManager.notify(1, notification);

      Date dt = new Date();
      Date newdate = new Date(dt.getYear(), dt.getMonth(), dt.getDate(),10,14,dt.getSeconds());
      long triggerAtTime =  newdate.getTime();
      long repeat_alarm_every = 1000;
      QuotesSetting.ON = 1;

       AlarmManager am = ( AlarmManager )  ctx.getSystemService(Context.ALARM_SERVICE );
       //Intent intent = new Intent( "REFRESH_ALARM" );
       Intent intent1 = new Intent(ctx,FirstQuoteAlarm.class);
       PendingIntent pi = PendingIntent.getBroadcast(ctx, 0, intent1, 0 );
       am.setRepeating(AlarmManager.RTC_WAKEUP, triggerAtTime, repeat_alarm_every, pi);
       Log.i("call2","msg");


}

为什么要每10分钟进行更新?这会消耗很多电量,对电池不友好。 - Dediqated
2个回答

1

你应该使用不同的通知 ID,就像下面你所使用的代码一样

mNotificationManager.notify(i, notification);

同时,可以增加您的时间

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

0

使用ScheduledExecutorService。通常这会得到更好的结果。

它旨在每隔一段时间在后台重复执行操作。从延迟开始等等。请查看:http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html

这里有一个类,其中包含一个方法,用于设置ScheduledExecutorService,在一小时内每十秒钟响一次:

import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
 Executors.newScheduledThreadPool(1);

public void beepForAnHour() {
 final Runnable beeper = new Runnable() {
   public void run() { System.out.println("beep"); 
 };
 final ScheduledFuture beeperHandle =
   scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
 scheduler.schedule(new Runnable() {
   public void run() { beeperHandle.cancel(true); }
 }, 60 * 60, SECONDS);
}
}}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接