通知Notification

简单Notification

  • 创建Builder
NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("My notification")
                .setContentText("Hello World!");
  • 添加Active
// 2. 创建点击回调动作
Intent resultIntent = new Intent(this, ResultActivity.class);
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
        PendingIntent.getActivity(
                this,
                0,
                resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT
        );
mBuilder.setContentIntent(resultPendingIntent);
  • 通知
// Builds the notification and issues it.
mNotifyMgr.notify(101, mBuilder.build());
  • 后台调用
// Creates an Intent for the Activity
Intent resultIntent = new Intent(this, ResultActivity.class);
// Sets the Activity to start in a new, empty task
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
        Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Creates the PendingIntent
notifyIntent = PendingIntent.getActivity(
        this,
        0,
        resultIntent,
        PendingIntent.FLAG_UPDATE_CURRENT
);

移除Notification

  1. 调用后自动清除
builder.setAutoCancel(true);
  1. 指定的 notification ID调用了cancel()
  2. 指定的 notification ID调用了cancelAll()

接下来的几个样式就不说了,简单,先贴图再看代码

BigView之Text

  • 调用bigTextNotification

BigView之Picture

  • 调用bigPictureNotification

BigView之Inbox

  • 调用bigInboxNotification

BigView之Custom

  • 调用customNotification
    • 大图
    • 小图

Code

代码部分

package com.xuie.notificationdemo;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;

public class MyService extends Service {
    PendingIntent notifyIntent;
    NotificationManager mNotificationManager;

    @Override
    public void onCreate() {
        super.onCreate();
        // Creates an Intent for the Activity
        Intent resultIntent = new Intent(this, ResultActivity.class);
        // Sets the Activity to start in a new, empty task
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                Intent.FLAG_ACTIVITY_CLEAR_TASK);
        // Creates the PendingIntent
        notifyIntent = PendingIntent.getActivity(
                this,
                0,
                resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT
        );

        // Notifications are issued by sending them to the
        // NotificationManager system service.
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // Builds an anonymous Notification object from the builder, and
        // passes it to the NotificationManager


        IntentFilter filter = new IntentFilter();
        filter.addAction(REMOTE_PLAY);
        filter.addAction(REMOTE_NEXT);
        filter.addAction(REMOTE_PREVIOUS);
        registerReceiver(receiver, filter);
    }

    public void startNotification() {
        // Instantiate a Builder object.
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

        // Puts the PendingIntent into the notification builder
        builder.setContentIntent(notifyIntent);

        builder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Service Notification")
                .setContentText("Hello World!");

        // 设置自动清除Notification。其它方法:指定的 notification ID调用了cancel(),或cancelAll()
        builder.setAutoCancel(true);

        mNotificationManager.notify(101, builder.build());
    }

    public void bigTextNotification() {
        NotificationCompat.BigTextStyle textStyle = new NotificationCompat.BigTextStyle()
                .setBigContentTitle("BigTextContentTitle")
                .setSummaryText("SummaryText")
                .bigText("I am Big Text!");

        Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setTicker("show big view text") // 第一次提示消息的时候显示在通知栏上
                .setContentInfo("content info")
                .setContentTitle("ContentTitle").setContentText("ContentText")
                .setStyle(textStyle)
                .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
                .setContentIntent(notifyIntent)
                .setAutoCancel(true)
                .build();
        mNotificationManager.notify(101, notification);
    }

    public void bigPictureNotification() {
        NotificationCompat.BigPictureStyle pictureStyle = new NotificationCompat.BigPictureStyle()
                .setBigContentTitle("BigPictureContentTitle")
                .setSummaryText("SummaryText")
                .bigPicture(resource2Bitmap(this, R.mipmap.ic_big_view));

        Notification notification = new NotificationCompat.Builder(this)
                .setLargeIcon(resource2Bitmap(this, R.mipmap.ic_big_view))// 这个与setSmallIcon相冲? - 测试手机Nexus5
                .setSmallIcon(R.mipmap.ic_launcher)
                .setTicker("show big view picture")
                .setContentInfo("content info")
                .setContentTitle("ContentTitle")
                .setContentText("ContentText")
                .setStyle(pictureStyle)
                .setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .build();
        mNotificationManager.notify(101, notification);
    }

    public void bigInboxNotification() {
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        inboxStyle.setBigContentTitle("BigInboxContentTitle").setSummaryText("SummaryText");
        for (int i = 0; i < 5; i++) {
            inboxStyle.addLine("news" + i);
        }

        Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setTicker("show big inbox picture")
                .setContentInfo("content info")
                .setContentTitle("ContentTitle")
                .setContentText("ContentText")
                .setStyle(inboxStyle)
                .setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .build();
        mNotificationManager.notify(101, notification);
    }

    public void customNotification() {
        PendingIntent playIntent = PendingIntent.getBroadcast(this, 0, new Intent(REMOTE_PLAY), PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent nextIntent = PendingIntent.getBroadcast(this, 0, new Intent(REMOTE_NEXT), PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent previousIntent = PendingIntent.getBroadcast(this, 0, new Intent(REMOTE_PREVIOUS), PendingIntent.FLAG_UPDATE_CURRENT);

        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.custom_notification);
        remoteViews.setOnClickPendingIntent(R.id.play_pause, playIntent);
        remoteViews.setImageViewResource(R.id.play_pause, R.mipmap.pause);
        remoteViews.setOnClickPendingIntent(R.id.next, nextIntent);
        remoteViews.setOnClickPendingIntent(R.id.previous, previousIntent);

        RemoteViews remoteViews_expand = new RemoteViews(getPackageName(), R.layout.custom_expanded_notification);
        remoteViews_expand.setOnClickPendingIntent(R.id.play_pause, playIntent);
        remoteViews_expand.setOnClickPendingIntent(R.id.next, nextIntent);
        remoteViews_expand.setOnClickPendingIntent(R.id.previous, previousIntent);
        remoteViews_expand.setTextViewText(R.id.new_text, "New Add Layout");

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
//                .setContentIntent(notifyIntent)
//                .setOngoing(true)
                .setAutoCancel(true)
                .setTicker("music is playing");

        Notification notification = builder.build();
        notification.contentView = remoteViews;
        notification.bigContentView = remoteViews_expand;

        mNotificationManager.notify(102, notification);
    }


    public static final String REMOTE_PLAY = "remote play";
    public static final String REMOTE_PREVIOUS = "remote previous";
    public static final String REMOTE_NEXT = "remote next";

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(REMOTE_PLAY)) {
                System.out.println("REMOTE_PLAY");
            } else if (action.equals(REMOTE_NEXT)) {
                System.out.println("REMOTE_NEXT");
            } else if (action.equals(REMOTE_PREVIOUS)) {
                System.out.println("REMOTE_PREVIOUS");
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    class MyBinder extends Binder {
        MyService getService() {
            return MyService.this;
        }
    }

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


    public static Bitmap resource2Bitmap(Context context, int drawId) {
        return BitmapFactory.decodeResource(context.getResources(), drawId);
    }

}

下载

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android常驻通知(Notification)是指在用户状态栏中一直显示的通知图标和文本内容,不会因为用户操作或应用进程被销毁而消失。常驻通知通常用于实时监测、后台服务、音乐播放等需要持续提醒用户的场景。 常驻通知的实现步骤如下: 1. 首先,需要创建一个Notification对象,包括通知图标、标题、内容等信息。 2. 然后,创建一个PendingIntent,用于定义用户点击通知后的操作,比如打开应用的某个Activity或执行某个Service。 3. 创建一个NotificationChannel(通知渠道),用于定义通知的重要程度,包括声音、震动等设置。 4. 将Notification对象与PendingIntent关联,并将其设置为常驻通知的优先级。 5. 最后,调用NotificationManager的notify方法,将通知显示在用户的状态栏上。 需要注意的是,常驻通知存在一些使用限制和最佳实践: 1. 用户可以通过设置中的通知管理来关闭或打开特定应用的常驻通知。 2. 常驻通知不适合用于广告或频繁推送的内容,以免打扰用户。 3. 为了避免误导用户,常驻通知的图标和文本内容应与应用的实际情况相符。 4. 如果需要更新通知的内容或操作,可以使用NotificationManager的notify方法进行更新,并保持通知的id不变。 总之,常驻通知是Android提供的一个重要功能,可以实现持续提醒用户和后台监测的需求。但应用开发者需要注意使用场景和用户体验,遵循Android的最佳实践,以确保用户对常驻通知的接受和理解。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值