创建Android警报通知

时间:2015-09-20 13:36:17

标签: java android alarmmanager android-notifications android-alarms

如何将通知设为闹钟,此时我只是在应用内部时收到通知。

MainActivity:

public void sendNotificationIfTimeEnd01() {
    Context context = getApplicationContext();
    Intent intent01 = new Intent(context, MainActivity.class);
    PendingIntent pendingIntent01 = PendingIntent.getActivity(this, 1, intent01, 0);
    NotificationCompat.Builder builder01 = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_notification)
            .setContentIntent(pendingIntent01)
            .setAutoCancel(true)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
            .setContentTitle(gamesJuliToStringArray[0])
            .setContentText("ready")
            .setSubText("clkick");
    NotificationManager notificationManager = (NotificationManager) getSystemService(
            NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID_01, builder01.build());
    try {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
        r.play();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

也许你应该在退出应用程序时使用Service在后台运行。当我阅读你的描述时,似乎你把它放在一个活动中。当你回到家时,应用程序处于暂停状态。我建议你运行后台服务。

尝试检查:Service

我只是尝试编辑Google的教程

public class HelloIntentService extends IntentService {

  /**
   * A constructor is required, and must call the super IntentService(String)
   * constructor with a name for the worker thread.
   */
  public HelloIntentService() {
      super("HelloIntentService");
  }


  @Override
  protected void onHandleIntent(Intent intent) {
      //maybe some works you need to do
      //sleep for the time until you want the notification
      //put you notification code here
  }
}

此方法仅在您完成作业之前有工作要做并将通知发送给警报用户。

但是如果你正在做一个使用通知的闹钟。也许你也可以尝试使用一些像AlarmManager,Receiver来实现的东西。我在这个网页上找到了一个例子: http://javapapers.com/android/android-alarm-clock-tutorial/

抱歉我的英语不好,希望这可以帮到你。