java - 安卓通知

标签 java android

好吧,我正在尝试使用通知,但这段代码不起作用。我已经在 4.4 和 5.0 上测试过了。我不明白,怎么了。

public void onClick(View view) {
    Context context = getApplicationContext();

    Intent notificationIntent = new Intent(context, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0,notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

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

    builder.setContentIntent(contentIntent)
            .setWhen(System.currentTimeMillis())
            .setAutoCancel(true)
            .setContentTitle("Title")
            .setContentText("Text");

    Notification notification = builder.build();
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);        
    notificationManager.notify(NOTIFY_ID, notification);
}

我将不胜感激。

最佳答案

这可能是因为 Google 在每个 Android 版本中对其通知 API 进行了大量更改。所以你使用的 API 不兼容多 Android 版本。但是 Google 发布了 appcompat-v7\appcompat-v4 来解决这个问题。

试试下面的代码:

public void send(View v) {
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Context context = getApplicationContext();
    Intent notificationIntent = new Intent(context, TestNotificationActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    Notification notification = builder
            .setContentIntent(contentIntent)
            .setContentTitle("this is title")
            .setContentText("this is content")
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
            .build();
    manager.notify(NOTIFY_ID, notification);
}

记得导入android.support.v7.app.NotificationCompat。

关于java - 安卓通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38236576/

相关文章:

java - 如何将监听 hibernate 事件的模块与实体本身分离?

java - 如何使用java调用内部类中的方法?

java - 映射异常: Unable to find column with logical name

android - Google+ 登录在 Android fragment 上无法正常工作

android - 从手机和 sim Android 读取所有联系人

android - 在垂直 ListView 中同步水平 RecyclerView

java - 最大化给定股票报价的利润,我在 Java 中的解决方案

java - Google Protobuf 反序列化重复对象上 get 操作的时间复杂度

java - 当我们打开 Android 应用程序时,主 UI 线程会执行哪些操作

android - 使用 Ruby 向 Firebase 发送通知