java - 尝试在 android 中构建一个简单的通知

标签 java android android-notifications

我正在尝试在我的 Android 应用程序中设置一个通知,它只会说“它有效”,但我需要我的应用程序一直兼容 API 1。我真的很困惑如何做到这一点尽管。有些旧教程已弃用,有些新教程不支持旧 API 级别。根据这个SO问题,我应该使用NotificationCompat.Builder .我正在使用一个示例,但我不完全理解代码。

超出这段代码:

Intent notificationIntent = new Intent(ctx, YourClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(ctx,
        YOUR_PI_REQ_CODE, notificationIntent,
        PendingIntent.FLAG_CANCEL_CURRENT);

NotificationManager nm = (NotificationManager) ctx
        .getSystemService(Context.NOTIFICATION_SERVICE);

Resources res = ctx.getResources();
Notification.Builder builder = new Notification.Builder(ctx);

builder.setContentIntent(contentIntent)
            .setSmallIcon(R.drawable.some_img)
            .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.some_big_img))
            .setTicker(res.getString(R.string.your_ticker))
            .setWhen(System.currentTimeMillis())
            .setAutoCancel(true)
            .setContentTitle(res.getString(R.string.your_notif_title))
            .setContentText(res.getString(R.string.your_notif_text));
Notification n = builder.build();

nm.notify(YOUR_NOTIF_ID, n);

我在下面看到红线:ctxYOUR_PI_REQ_CODEYOUR_NOTIF_ID

最佳答案

ctx 变量旨在成为一个 Android 上下文——通常是一个 Activity(或者实际上是一个扩展 Activity 的类)。

您应该对 PendingIntent 类做一些研究以了解 YOUR_PI_REQ_CODE 但您需要确定放在这里的内容;这是您的待处理的意向请求代码。

您还应该研究 NotificationManager notify() 方法以确定您想要用作您的通知 ID。

关于java - 尝试在 android 中构建一个简单的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12850033/

相关文章:

java - 查找字符串中模式的计数(包括重叠)

android - 无法在 Android 内部存储中写入文件

android - 如何在我的应用程序 fragment 应用程序中调用 crouton.makeText?

android - 比较字符串时间和当前时间android

java - 热衷于使用 Jersey 和 Netbeans 编辑 JSON 对象输出?

java - 为什么父类和子类都实现相同的接口(interface)?

java - 基于 SSL 的 XML RPC 服务,具有来自 Spring 应用程序的基本身份验证

android - 根据 Cordova webview 应用程序中的操作系统语言将用户重定向到特定语言 url

java - Android - 如何使编辑文本中的所有行都带有下划线?

Android更新通知文本导致内存占用