RemoteViews是什么?
翻译过来,顾名思义就是远程的View,先看下官方文档的说明
/**
* A class that describes a view hierarchy that can be displayed in
* another process. The hierarchy is inflated from a layout resource
* file, and this class provides some basic operations for modifying
* the content of the inflated hierarchy.
public class RemoteViews implements Parcelable, Filter {
意思是这个类是一个描述视图结构的类、以及提供了一些基本的修改操作,注意这个RemoteViews并没有继承于View,不是一个View,只是提供方法,并且继承了Parcelable,为实现跨进程提供了条件。
RemoteViews常用的就是自定义通知栏界面、桌面小控件、当然也可以更新两个不同应用的界面、或者用于闹钟功能(闹钟功能这里不讲)这些接下来会讲到。
一、RemoteViews和Notification
public final String CHANNEL_ID_SERVICE_HANDLE = "com.xsx.Channel_id";
private void setNotification() {
//判断版本
setChannel();
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID_SERVICE_HANDLE);
builder.setSmallIcon(R.mipmap.ic_launcher_round);
builder.setContentTitle("我去也");
builder.setContentText("我來也");
builder.setSound(null);
//点击消失
//builder.setAutoCancel(true);
//默认高度256 超出则显示不全
//builder.setCustomBigContentView(remoteViews);
Notification notification = builder.build();
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent();
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.contentIntent = pendingIntent;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// 高度256 超出则显示不全 可以更大的显示通知栏高度
// 通知栏默认高度是64
// notification.bigContentView = remoteViews;
// }
manager.notify(1, notification);
}
private void setChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "CHANNEL_NAME";
String description = "CHANNEL_DESCRIPTION";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID_SERVICE_HANDLE, name, importance);
channel.setDescription(description);
channel.setSound(null, null);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
效果图如下:
1.1、自定义通知栏界面
上面是简单的实现系统通知栏的效果,但是无法自定义通知栏界面,并且无法实现通知栏里特定控件的点击事件,这就可以用到RemoteViews,先初始化RemoteViews,通过setOnClickPendingIntent(注意不是setOnClickListener)来设置点击事件,再写一个广播来监听点击事件,
如下:
private void setNotification() {
//判断版本
setChannel();
//初始化RemoteViews
RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.remote_view);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID_SERVICE_HANDLE);
builder.setSmallIcon(R.mipmap.ic_launcher_round);
builder.setContentTitle("我去也");
builder.setContentText("我來也");
builder.setSound(null);
Notification notification = builder.build();
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//设置头部图片
remoteViews.setImageViewResource(R.id.head_imageVie, R.drawable.zip1);
//头部图片点击