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 中自定义通知的确切时间 的相关文章

  • Android 12:如何防止更改手机壁纸时重新启动活动?

    在 Android 12 上 如果我们开启一个活动 进入手机主屏幕更换壁纸 切换回我们的 Activity 该 Activity 重新启动 看起来它与 Material You 主题有关 我想在我的应用程序进入前台时禁用活动的重新启动 有办
  • ACTION_VIEW 的 Intent.createChooser 仅显示默认浏览器

    我正在尝试使用 Intent createChooser 显示应用程序选择器对话框 该对话框将列出用户手机中所有可用的网络浏览器 我正在使用下面的代码 Intent browserIntent new Intent Intent ACTIO
  • 合并两个位图图像(并排)

    任何人都可以帮助将两个位图图像合并为单个位图 在android中 并排 谢谢 尤瓦拉吉 您可以使用Canvas 查看这篇文章 http www jondev net articles Combining 2 Images in Androi
  • 如何改变android中menuItem的背景颜色?

    我正在以编程方式将菜单项添加到菜单中 我想在选择特定项目时添加背景颜色 如何为 menuItem 添加背景 您的回答将不胜感激 虽然其他答案提供了更改样式 这会影响all菜单项 据我了解 需要更改一个菜单项 我建议你使用android ac
  • 更改工具栏中汉堡图标的大小?

    我有两个问题 可能很奇怪 但无论如何 我有带有应用程序标题的工具栏 如何将其更改为非徽标的图片 下一个问题 是否可以设置 更改工具栏中汉堡图标的大小 我在下面的下一个代码的帮助下制作了经典的导航抽屉 我也使用了 ActionBarDrawe
  • 启动 Twitter 应用程序 [重复]

    这个问题在这里已经有答案了 可能的重复 Twitter 应用程序的 Android Intent https stackoverflow com questions 2077008 android intent for twitter ap
  • 无法合并 Dex - Android Studio 3.0

    当我在稳定频道中将 Android Studio 更新到 3 0 并运行该项目时 我开始收到以下错误 Error Execution failed for task app transformDexArchiveWithExternalLi
  • layout.xml 的用途是什么?

    人们为什么使用layout xml在他们的resources like
  • 如何在 Android 清单文件中设置文本外观?

    是否可以做相当于 setTextAppearance context android R style TextAppearance Medium 在 Android 应用程序的清单文件中 android textAppearance and
  • Locale.getDefault().getCountry() 返回空字符串

    我正在尝试使用国家 地区代码获取用户语言 例如en US es es 但是当我使用Locale getDefault getCountry 它返回空字符串 虽然它给了我正确的语言Locale getDefault getLanguage N
  • Android 在启动时启动服务,如何在设备重启后重新启动服务类?

    我需要在启动时启动一项服务 我搜索了很多 他们正在谈论广播接收器 由于我是 Android 开发新手 所以我对 Android 上的服务并没有清楚的了解 请提供一些源代码 您的接收者 public class MyReceiver exte
  • Python Kivy - 在本机网络浏览器中打开 url 的应用程序

    我尝试制作一个简单的应用程序 在单击 Screen One 上的按钮后 在 Kivy 中打开一个网页 我使用了这个主题 Python 在应用程序中直接显示网络浏览器 iframe https stackoverflow com questi
  • 点击监听器的公共类

    我的所有 6 项活动中有 7 个按钮 所有 6 个按钮在所有活动中都具有相同的功能 如何为这 6 个按钮执行通用的单击事件侦听器 您可以创建一个实现 View OnClickListener 的新类 如下所示 public class My
  • Android开发:未定义方法

    大家好 我是 Android 和 Eclipse 的新手 我刚刚遵循了developer android com 上的教程 现在我在添加操作栏 http developer android com training basics actio
  • 如何更改锁屏自定义文本(所有者信息)?

    我写了程序代码 String message This is test Settings System putString context getContentResolver Settings Secure LOCK PATTERN EN
  • Jetpack Compose 部分或开放侧边框

    我正在尝试绘制部分或一侧开放的矩形圆形边框以实现此效果 玩了一下之后我得到了这个 这是通过以下方式完成的 RoundedCornerShape topStartPercent 50 bottomStartPercent 50 start R
  • OpenGL ES 2.0 屏幕闪烁

    我面临着一个大问题 我正在使用带有 Android 4 0 3 的 Transformer tf101 选项卡 我的应用程序使用自定义 OpenGL ES 2 0 表面 我正在用纹理渲染多个平面 该纹理大约发生变化 每秒 20 次 并通过传
  • Amazon IAP 不会调用 onPurchaseResponse

    我有一个 Android 应用程序 它使用 IAP 我正在发送PurchasingManager initiateGetUserIdRequest 并得到用户识别成功 in onGetUserIdResponse 得到回复后Purchasi
  • 在 Android 中更新到 API 26 时,清单合并失败并出现多个错误

    我尝试使用 API 26 更新我的 gradle 安卓工作室2 3 3 但我在编译项目时遇到以下错误 这是我收到的错误的屏幕截图 应用级别build gradle Top level build file where you can add
  • 修改 ADW Android 启动器?

    我想更改和修改开源 ADW 启动器 启动器可在此处获取 https github com AnderWeb android packages apps Launcher https github com AnderWeb android p

随机推荐