RemoteViews(一):应用

笔者当初在学习Notification和AppWidgetProvider时接触过RemoteViews,但是当时并不知道RemoteViews的作用及其原理,本主题将分两章介绍RemoteViews的应用场景和原理,这章介绍应用场景.
RemoteViews主要的应用场景有两个,一个是通知栏上的应用,一个是桌面小组件的应用
一、RemoteViews在通知栏上的应用
在通知栏上,RemoteViews的作用是用来改变通知栏的ui,首先我们来看一下定义通知栏时系统默认的ui
Notification notification = new Notification();
notification.icon = R.drawable.ic_launcher;
notification.tickerText = “hello”;
notification.when = System.currentTimeMillis();
notification.flags = Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(this,FirstActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(this,”hai”,”this is notification”,pIntent);
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1,notification);
我们现在定义一个布局文件(R.layout.notification),让RemoteViews加载这个自定义文件
Notification notification = new Notification();
notification.icon = R.drawable.ic_launcher;
notification.tickerText = “hello”;
notification.when = System.currentTimeMillis();
notification.flags = Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(this,FirstActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews remoticviews = new RemoteViews(getPackageName(),R.layout.notification);
remoticviews.setTextViewText(R.id.tv,”ni hao “);
remoticviews.setImageViewResource(R.id.image,R.drawable.icon);
PendingIntent openActivity = PendingIntent.getActivity(this,0,new Intent(this,SecondActivity.class),PendingIntent.FLAG_UPDATE_CURRENT);
remoticviews.setOnClickPendingIntent(R.id.openActivity,openActivity);
notification.contentView = remoticviews;
notification.contentIntent = pIntent;
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1,notification);
这样,我们就可以在通知栏上看到自定义的布局了.从上面的代码来看,比如remoticviews.setTextViewText(R.id.tv,”ni hao “);就是给id为tv的TextView控件赋值,类似于view.setText()
而remoticviews.setImageViewResource(R.id.image,R.drawable.icon);类似于imageView.setImageResource(),如果要给某个view设置点击事件,remoticviews.setOnClickPendingIntent(R.id.openActivity,openActivity);我们看到这个函数里面传入了两个参数,一个是设置点击事件view的id,一个是PendingIntent,而PendingIntent的作用是用来跳转到另外一个Activity
二、RemoteViews在桌面小部件的应用
实现一个桌面小部件需要4步:
1、定义小部件界面:
在res/layout/下新建一个XML文件,可以命名为widget.xml

你可能感兴趣的:(学习心得)