Android Notification使用

Notification也就是通知的意思,它的作用是在手机通知栏显示一条信息,这对于app不在前台的时候用处很大,下面我们来看一下它的使用方法吧。

一、简单使用

废话不多说,直接上代码:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private NotificationManager mManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "msg";
            String channelName = "消息";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            createNotificationChannel(channelId, channelName, importance);
        }

        findViewById(R.id.start_notify).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start_notify:
                startNotify();
                break;
            default:
                break;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        mManager.createNotificationChannel(channel);
    }

    private void startNotify() {
        Notification notification = new NotificationCompat.Builder(this, "msg")
                .setContentTitle("标题")
                .setContentText("内容")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                .setAutoCancel(true)
                .build();
        mManager.notify(1, notification);
    }
}

xml文件比较简单,里面就一个按钮,这里就不展示了,下面来一一介绍上面代码的作用。

第一步:创建NotificationManager对象,这个对象是用来发送通知的;

第二步:创建通知渠道,这个是Android8.0之后新增的,如果你的targetSdkVersion大于26的话这个东西是必须要配置的,如果没有配置的话在8.0以上的手机将无法使用通知;

在这个里面有三个参数,具体作用如下:

1、id:这个属性是用来区分不同的通知,值不能过长。

2、name:这个属性是在设置里面展示给用户看的。

3、importance:通知的重要程度,不同的重要程度展示效果也不同。

第三步:创建通知实例,在构建器里面我们需要配置下通知渠道的id,与创建渠道的时候要一致,随后我们可以配置一些常用参数:

1、setContentTitle:设置通知标题。

2、setContentText:设置通知内容。

3、setWhen:设置时间。

4、setSmallIcon:设置小图标。

5、setLargetIcon:设置大图标。

6、setAutoCancel:设置点击通知后自动清除信息。

最后调用build方法构建。

第四步:调用NotificationManager对象的notify方法发送通知。

最终效果:

这个时候我们发现,哎,怎么小图标是空的,这是由于在Android5.0之后,Google要求所有应用程序的通知栏图标应该只使用alpha图层来进行绘制,而不应该包括RGB图层,简单点来说就是只能使用白底的图标。这里我们为了简单起见,直接使用Android Studio生成一个图标先凑合着用着吧。

方法如下:

在Icon Type中选择Notification Icons选项然后一路确定即可。

然后把setSmallIcon换上我们新增的图片运行:

这个时候我们发现图片变成了灰底的,要改变颜色我们只需要在Notification中加一个setColor这个属性即可:

.setColor(ContextCompat.getColor(this, R.color.colorPrimary))

最终效果:

二、跳转

1、先新建一个Activity用来做跳转的界面。

2、编写跳转代码:

        Intent intent = new Intent(this, SecondActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        Notification notification = new NotificationCompat.Builder(this, "msg")
                ...
                .setContentIntent(pi)
                .build();
        mManager.notify(1, notification);

这里我们首先创建了一个Intent,然后创建了PendingIntent,最后调用setContentIntent把PendingIntent传入即可,

效果如下:

通知的基本使用到这里就基本完成啦。

三、进阶知识

1、长文本

当我们想要在通知里面展现长文本时如果直接使用setContentText就会变成这样:

这个时候我们需要用到一个setStyle方法来设置长文本,这个属性会把setContentText设置的内容给覆盖掉:

.setStyle(new NotificationCompat.BigTextStyle().bigText("很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长的内容"))

这样就可以展示长文本啦

2、大图片

设置大图片也是调用setStyle这个方法,代码如下:

// 构建一个 Style
        NotificationCompat.BigPictureStyle bigPictureStyle =
                new NotificationCompat.BigPictureStyle().bigPicture(BitmapFactory.decodeResource(getResources(),R.drawable.timg));
        // 设置标题
        bigPictureStyle.setBigContentTitle("标题");
        // 设置副标题,简介文字
        bigPictureStyle.setSummaryText("我是内容");

notification.setStyle(bigPictureStyle)

这样设置即可:

3、自定义通知

第一步、创建RemoteViews实例:

RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_custom);

第二步、调用setContent把remoteViews设置进去即可(注:前面的setStyle要去掉,否则自定义视图不会生效):

.setContent(remoteViews)

更新RemoteViews:

remoteViews.setTextViewText(R.id.btn_1, "按钮1");

第一个参数设置想要改变的控件,第二个参数设置想要改变的文本。

这里只是简单的展示一下,其他方法可以自行查阅RemoteViews方法。

点击事件:

remoteViews.setOnClickPendingIntent(R.id.btn_1, pi);

第一个参数设置点击事件作用的控件,第二个参数为PendingIntent。

最终效果:

到这里通知的使用就基本告一段落啦,下面是完整的Activity代码:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private NotificationManager mManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "msg";
            String channelName = "消息";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            createNotificationChannel(channelId, channelName, importance);
        }

        findViewById(R.id.start_notify).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start_notify:
                startNotify();
                break;
            default:
                break;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        mManager.createNotificationChannel(channel);
    }

    private void startNotify() {
        // 构建一个 Style
        NotificationCompat.BigPictureStyle bigPictureStyle =
                new NotificationCompat.BigPictureStyle().bigPicture(BitmapFactory.decodeResource(getResources(),R.drawable.timg));
        // 设置标题
        bigPictureStyle.setBigContentTitle("标题");
        // 设置副标题,简介文字
        bigPictureStyle.setSummaryText("我是内容");

        Intent intent = new Intent(this, SecondActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);

        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_custom);
        remoteViews.setOnClickPendingIntent(R.id.btn_1, pi);
        remoteViews.setTextViewText(R.id.btn_1, "按钮1");
        Notification notification = new NotificationCompat.Builder(this, "msg")
                .setContentTitle("标题")
                .setContentText("很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长的内容")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_stat_name)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                .setAutoCancel(true)
                .setColor(ContextCompat.getColor(this, R.color.colorPrimary))
                .setContentIntent(pi)
//                .setStyle(bigPictureStyle)
                .setContent(remoteViews)
                .build();
        mManager.notify(1, notification);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章