Android 中自定义通知的确切时间

2024-04-30

我正在开发一个用于咨询服务的 Android 应用程序。客户可以在应用程序中查看他们的预约。例如,

下次预约:2016 年 12 月 31 日 上午 10:00

现在我需要做的是,用户将收到 2 条通知——有关预约的提醒。 7 天前一次,3 天前一次。我将此日期(2016 年 12 月 31 日上午 10:00)保存为String这样我就可以提取年份、月份等。 我发现我需要编写某种服务来发送这些通知。这是我尝试过的(未完成):

public class NotificationService extends Service {
    @Override
    public void onCreate() {
        Intent resultIntent=new Intent(this, MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, resultIntent, 0);
        Notification nBuilder = new Notification.Builder(this)
                .setContentTitle("Don't miss! ")
                .setTicker("Notification!")
                .setContentIntent(pIntent)
                .setDefaults(Notification.DEFAULT_SOUND)
                .setAutoCancel(true)
                .setSmallIcon(R.drawable.my_logo)
                .setContentText("7 days left till your appointment...")
                //.setWhen(System.currentTimeMillis())
                .build();
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nBuilder.flags |=Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(1,nBuilder);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

以及我不知道从哪里调用的方法:

public void reminder() {
    Intent intent  = new Intent(getActivity(), MainActivity.class);

    AlarmManager manager =(AlarmManager) getActivity().getSystemService(Activity.ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getService(getActivity().getApplicationContext(),
            0,intent, 0);
    Calendar cal=Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 8); 
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    manager.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),24*60*60*1000,pendingIntent);
}

出于测试目的,我手动设置了小时/分钟/秒,但显然我需要从日期中提取它String.


你需要写一个IntentService第一的。这是一个示例,您可以编写代码来显示通知processNotification功能。

public class NotificationIntentService extends IntentService {

    private static final String ACTION_START = "ACTION_START";

    public NotificationIntentService() {
        super(NotificationIntentService.class.getSimpleName());
    }

    public static Intent createIntentStartNotificationService(Context context) {
        Intent intent = new Intent(context, NotificationIntentService.class);
        intent.setAction(ACTION_START);
        return intent;
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        try {
            String action = intent.getAction();
            if (ACTION_START.equals(action))
                processNotification();

        } finally {
            WakefulBroadcastReceiver.completeWakefulIntent(intent);
        }
    }

    private void processNotification() {
        Intent resultIntent=new Intent(this, MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, resultIntent, 0);
        Notification nBuilder = new Notification.Builder(this)
                .setContentTitle("Don't miss! ")
                .setTicker("Notification!")
                .setContentIntent(pIntent)
                .setDefaults(Notification.DEFAULT_SOUND)
                .setAutoCancel(true)
                .setSmallIcon(R.drawable.my_logo)
                .setContentText("7 days left till your appointment...")
                .build();
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nBuilder.flags |=Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(1, nBuilder);
    }
}

然后创建一个NotificationEventReceiver

public class NotificationEventReceiver extends WakefulBroadcastReceiver {

    private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";

    public static void setupAlarm(Context context, long interval) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        PendingIntent alarmIntent = getStartPendingIntent(context);

        alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), interval, alarmIntent);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Intent serviceIntent = null;
        if (ACTION_START_NOTIFICATION_SERVICE.equals(action)) {
            serviceIntent = NotificationIntentService.createIntentStartNotificationService(context);
        }

        if (serviceIntent != null) {
            startWakefulService(context, serviceIntent);
        }
    }

    private static PendingIntent getStartPendingIntent(Context context) {
        Intent intent = new Intent(context, NotificationEventReceiver.class);
        intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
        return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }
}

And the NotificationServiceStarterReceiver

public final class NotificationServiceStarterReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        long interval = getIntent().getLongExtra("alarm_interval", 0);
        NotificationEventReceiver.setupAlarm(context, interval);
    }
}

将这些添加到您的AndroidManifest.xml inside <application> tag

<service
    android:name="YourPackage.NotificationIntentService"
    android:enabled="true"
    android:exported="false" />

<receiver android:name="YourPackage.BroadcastReceiver.NotificationEventReceiver" />
<receiver android:name="YourPackage.BroadcastReceiver.NotificationServiceStarterReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.action.TIMEZONE_CHANGED" />
        <action android:name="android.intent.action.TIME_SET" />
    </intent-filter>
</receiver>

现在从你的Activity您可以致电setupAlarm() inside onCreate功能。

NotificationEventReceiver.setupAlarm(getApplicationContext(), interval);

你需要添加WAKE_LOCK您的清单中的许可。

<uses-permission android:name="android.permission.WAKE_LOCK" />

在这里你看到你可以通过interval要显示的下一个通知。使用interval明智地。您可以考虑将约会的当前状态保存在数据库中,然后在必要时通过传递下一个警报的适当间隔来触发警报。就是这个想法。

Update

因此,就您而言,您不想在用户注销时显示通知。所以在这种情况下,你可以考虑保留一个SharedPreference存储登录状态。您可以致电processNotification基于存储值的函数。

所以伪代码可能看起来像这样。

if(pref.getBoolean("login_status", false)) {
    // If the login status is true, process the notification
    processNotification();
} else {
    // Do nothing
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android 中自定义通知的确切时间 的相关文章

  • 将roottools.jar导入Android Studio

    我正在尝试从这里导入 roottools https code google com p roottools https code google com p roottools jar 文件 到 Android Studio 项目 到目前为
  • Android STFP 库 [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我想在我的 Android 项目中使用 SFTP 安卓已经有了吗 SFTP 库 还是我必须实现它 I
  • Android:如何从输入流创建 9patch 图像?

    我使用下面的代码实例化 9patch 图像并将其设置为按钮的背景 下图显示了不理想的结果 InputStream MyClass class getResourceAsStream images btn default normal 9 p
  • IntentService、Service 或 AsyncTask

    实现这一点的最佳方法是什么 我有一个 Android 应用程序 它将使用我的 python 服务器来允许两部手机之间进行轮流通信 回合意味着他们在一轮开始之前不能互相交谈 一旦他们发送一条消息 他们就不能发送另一条消息 直到对方做出回应 然
  • NumberPicker 的格式化值在单击时消失

    我的 NumberPicker 在setDescendantFocusability FOCUS BLOCK DESCENDANTS 模式和setWrapSelectorWheel false 已关闭 我用一个简单的格式化程序格式化了我的
  • Android中如何将文件写入raw文件夹?

    我认为这是一个非常基本的问题 我目前正在编写这样的文件 File output new File exampleout mid 现在 我想将文件写入 myproject res raw 我读到我可以通过将完整的网址放在 中来做到这一点 但
  • 如何更改对话框的默认黑色暗淡背景“颜色”(而不是暗淡量)?

    这是随机显示的图像Dialog在网上找到的 我一直在实施一个自定义Dialog 我可以处理对话框上的几乎所有内容 除了对话框本身下方的默认黑色昏暗背景之外 但在其后面的整个屏幕上 基本上我想改变它color和阿尔法值 我一直在 StackO
  • 调试 Java InterruptedException,即查找原因

    在调试Android应用程序时 有时中断异常发生并使应用程序崩溃 我已经能够在默认异常处理程序上设置断点 但调用堆栈不提供信息 at java util concurrent locks AbstractQueuedSynchronizer
  • AOSP 中 android.Build.SERIAL 何时何地生成?

    我知道android Build SERIAL是在第一次设备启动时生成的 但我无法准确定位位置和时间 我正在建造AOSP Jelly Bean Android平板电脑 nosdcard 第二个问题 这个是序列号吗 really对所有人来说都
  • 仅在 Android 应用程序中使用 XHDPI 可绘制对象?

    如果您计划在不久的将来支持 LDPI MDPI HPDI 或许还有 XHDPI 那么是否可以在项目中仅包含 XHDPI 可绘制对象并让设备将其缩放到所需的分辨率 我已经测试过在 Photoshop 中将可绘制对象的大小调整为 MDPI 和
  • Flutter Spotify Api 身份验证

    我需要在使用 Spotify api 的 Flutter 应用程序中对用户进行身份验证 我使用 flutter web auth 打开 WebView 并让用户在那里登录 我无法返回应用程序 在 Spotify 仪表板中 我将回调 Uri
  • twitter4j => AndroidRuntime(446): java.lang.NoClassDefFoundError: twitter4j.http.AccessToken

    我正在尝试使用 twitter4j 我的应用程序来连接并发布到 Twitter 我正在关注本教程 http blog doityourselfandroid com 2011 02 13 guide to integrating twitt
  • cordova插件条码扫描仪打不开扫描

    我的条形码扫描仪插件有问题 我不是天才 我不太了解如何编写网络应用程序 我使用phonegap和cordova 并且尝试制作一个网络应用程序 在单击链接后扫描条形码 我之前已经使用此命令行安装了该插件 cordova plugin add
  • Proguard - 找不到任何超级类

    我收到此错误 Unexpected error while performing partial evaluation Class org apache log4j chainsaw Main Method
  • 如何从webkit浏览器中检测Android版本和品牌?

    如何通过webkit浏览器检测Android版本和品牌 可靠吗 我相信你可以检查用户代理 但是 我认为它不安全 因为有很多方法可以用来欺骗用户代理 在谷歌上搜索这个问题给了我们很多答案 它甚至可以在默认浏览器上运行 您只需输入 about
  • 在尝试使用 GPS 之前如何检查 GPS 是否已启用

    我有以下代码 但效果不好 因为有时 GPS 需要很长时间 我该如何执行以下操作 检查GPS是否启用 如果启用了 GPS 请使用 GPS 否则请使用网络提供商 如果 GPS 时间超过 30 秒 请使用网络 我可以使用时间或 Thread sl
  • 在 Android ADT Eclipse 插件中滚动布局编辑器

    有谁知道当布局编辑器的内容溢出一个 屏幕 时如何滚动这些内容 我说的是在设计时使用 ADT 布局编辑器 而不是在物理设备上运行时滚动 效果很好 关闭 Android 布局编辑器中的剪辑 切换剪辑 按钮位于 Android 布局编辑器的右上角
  • 如何在 Android 中保存 Edittext 中的文本而不丢失文本的粗体、斜体等功能

    我想做的就是从 Edittext 中获取文本 该文本具有粗体和斜体等功能 并将其保存在文本文件中 但是当我读回并显示它时 这些功能丢失了 它们不显示 如何通过将文本保存在文本文件或任何文件中来保持丰富的功能 您可以使用Html toHtml
  • BadPaddingException:无效的密文

    我需要一些帮助 因为这是我第一次编写加密代码 加密代码似乎工作正常 但解密会引发错误 我得到的错误是 de flexiprovider api exceptions BadPaddingException 无效的密文 in the 解密函数
  • 进程被杀死后不会调用 onActivityResult

    我有一个主要活动 Main 和另一个活动 Sub 由 Main 调用 startActivityForResult new Intent this SubActivity class 25 当我在 Sub 时 我终止该进程 使用任务管理器或

随机推荐