java - 创建 Android 警报通知

标签 java android alarmmanager android-notifications android-alarms

如何将通知设置为闹钟,目前我只有在应用程序内时才会收到通知。

主要 Activity :

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();
    }
}

最佳答案

也许您应该在退出应用程序时使用在后台运行的服务。当我阅读您的描述时,似乎您将其放入了一项 Activity 中。当您回到家时,应用程序处于暂停状态。我建议您运行后台服务。

尝试检查: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/

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

关于java - 创建 Android 警报通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32679991/

相关文章:

java - 如何以编程方式计算 Android 上的实时移动数据速度?

android - 如何使用警报管理器删除短信

java - 在控制台中打印多行 ASCII 动画

java - 什么是生命周期观察器以及如何正确使用它?

java - 存储 jtree 的状态/扩展节点以恢复状态

android - SimpleDateFormat 在不同的平板电脑上表现不同

JavaScript/Jsoup - 从 "i class"获取背景图像 url

java - 为什么我的程序不能正确处理字符编码?

android - 在哪里/如何设置 AlarmManager 警报以避免重复

c# - 为 AlarmManager 设置 Intent