第五章理解RemoteViews(Android开发艺术探索)

5.1、remoteViews的应用(主要用于通知栏和桌面小部件)

通知栏和桌面小部件不能直接去更新view,因为2者的页面都运行在其他进程中,确切来说是系统的SystemServer进程,为了跨进程更新页面,RemoteViews提供了一系列的set方法进行更新。

5.1.1、在通知栏的应用:

通知栏除了默认的效果还可以自定义布局,下面分别说明这2种情况:

默认的布局:

Notification notification = new Notification();
//设置图标
notification.icon = R.drawable.ic_launcher;
//设置内容
notification.tickerText = "hello world";
//要显示的时间,一般是当即显示,故填入系统当前时间。
notification.when = System.currentTimeMillis();
//// FLAG_AUTO_CANCEL表明当通知被用户点击时,通知将被自动清除。
notification.flags = Notification.FLAG_AUTO_CANCEL;

Intent intent = new Intent(this, DemoActivity_2.class);
////该语句的作用是定义了一个不是当即显示的activity,
// 只有当用户拉下notify显示列表,并且单击对应的项的时候,才会触发系统跳转到该activity.
PendingIntent pendingIntent = PendingIntent.getActivity(this,
        0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//在此处设置在nority列表里的该norifycation得显示情况。
notification.setLatestEventInfo(this, "chapter_5", "this is notification.", pendingIntent);
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
// 通过通知管理器来发起通知。如果id不同,则每click,在statu那里增加一个提示
manager.notify(sId, notification);

自定义的布局(使用了remoteViews来加载):

Notification notification = new Notification();
notification.icon = R.drawable.ic_launcher;
notification.tickerText = "hello world";
notification.when = System.currentTimeMillis();
notification.flags = Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(this, DemoActivity_1.class);
intent.putExtra("sid", "" + sId);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
        0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
System.out.println(pendingIntent);
//包名和资源ID
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_notification);
remoteViews.setTextViewText(R.id.msg, "chapter_5: " + sId);
remoteViews.setImageViewResource(R.id.icon, R.drawable.icon1);
PendingIntent openActivity2PendingIntent = PendingIntent.getActivity(this,
        0, new Intent(this, DemoActivity_2.class), PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.open_activity2, openActivity2PendingIntent);
notification.contentView = remoteViews;
notification.contentIntent = pendingIntent;
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(sId, notification);

remoteViews使用起来很简单,2个参数即可创建,包名和资源id
更新remoteViews无法直接访问里面的view,必须通过remoteViews提供的方法进行更新

比如:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值