Android RemoteViews

Android RemoteViews

RemoteViews 不是用在应用自身的进程中,它用在其他进程(SystemServer 进程)中显示视图界面,但它不是真正的 View,也没有继承自 View 类。RemoteViews 的使用场景有两种,通知栏和桌面小部件(Widget)。

RemoteViews 在通知栏的应用

发送通知时可以使用 RemoteViews 完成自定义通知栏 View 的效果。

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.remote_views_activity);
        mNotificationManager = (NotificationManager) getApplication().getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("remote_views_chan", "remote views", NotificationManager.IMPORTANCE_HIGH);
            mNotificationManager.createNotificationChannel(channel);
        }
    }

    private Notification buildNotification() {
        Notification.Builder builder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder = new Notification.Builder(this, "remote_views_chan");

        } else {
            builder = new Notification.Builder(this);
        }
        builder.setContentTitle("this is title")
                .setContentText("this is text")
                .setSmallIcon(R.mipmap.ic_launcher);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification_layout);
            contentView.setTextViewText(R.id.text, "this is remote view text");
            contentView.setImageViewResource(R.id.icon, R.mipmap.ic_launcher);
            builder.setCustomContentView(contentView);
        } else {
            builder.setContent(new RemoteViews(getPackageName(), R.layout.notification_layout));
        }
        return builder.build();
    }

    private void sendNotification() {
        mNotificationManager.notify(1, buildNotification());
    }

在 Android SDK 24 以上时,需要使用通知通道( Notification Channel )来发送通知。同时使用 setCustomContentView 来自定义通知栏视图。

和普通 View 不一样,RemoteViews 没有 findViewById 方法,它使用 setTextViewText 方法和 setImageViewResource 方法来更新文字和图片。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值