什么是RemoteViews
RemoteViews表示的是一个View结构,它可以在其他进程中显示,由于它在其他进程中显示,为了能够及时更新它的界面,RemoteViews提供了一组基础的操作来跨进程更新它的界面。源码中对于它的解释如下:
/**
* 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.
*/
RemoteViews
相信很多人跟我一样觉得这可能是一个View或是layout。真的是这样吗?其实不然上面描述中说到它是描述一个View结构,并不是一个View,下面我们来通过源码看看RemoteViews
public class RemoteViews implements Parcelable, Filter {
......
}
从它的继承方式来看,它跟View和Layout并没有什么关系。下面我们来看看RemoteViews
如何使用。
RemoteViews的应用场景
1、应用于通知栏
2、应用于桌面小部件
RemoteViews的使用
前面说了RemoteViews
用于通知栏和桌面小部件,下面我们一个个来看RemoteViews
是怎么使用的。
RemoteViews在通知栏中使用
RemoteViews
在通知栏中的应用还是比较简单的,话不多说我们直接撸代码
Notification notification = new Notification();
notification.icon = R.mipmap.ic_launcher;
notification.tickerText = "hello notification";
notification.when = System.currentTimeMillis();
notification.flags = Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(this, RemoteViewsActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_notification);//RemoveViews所加载的布局文件
remoteViews.setTextViewText(R.id.tv, "RemoteViews应用于通知栏");//设置文本内容
remoteViews.setTextColor(R.id.tv, Color.parseColor("#abcdef"));//设置文本颜色
remoteViews.setImageViewResource(R.id.iv, R.mipmap.ic_launcher);//设置图片
PendingIntent openActivity2Pending = PendingIntent.getActivity
(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);//设置RemoveViews点击后启动界面
remoteViews.setOnClickPendingIntent(R.id.tv, openActivity2Pending);
notification.contentView = remoteViews;
notification.contentIntent = pendingIntent;
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(2, notification);
RemoteViews在桌面小部件中的应用
桌面小部件是通过AppWidgetProVider
来实现的,而AppWidgetProVider
继承自BroadcastReceiver,所以可以说AppWidgetProVider
是个广播。
1、定义小部件的界面
首先,我们需要在xml文件中定义好桌面小部件的界面。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/iv"
android:layout_width="360dp"
android:layout_height=