Android中级——RemoteView

RemoteView

  • RemoteView的应用
    • Notification
    • Widget
    • PendingIntent
  • RemoteViews内部机制
  • 模拟RemoteViews

RemoteView的应用

Notification

如下开启一个系统的通知栏,点击后跳转到某网页

public class MainActivity extends AppCompatActivity {private static final String TAG = "MainActivity";protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.baidu.com"));PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);NotificationChannel channel1 = new NotificationChannel("0", "channel1", NotificationManager.IMPORTANCE_LOW);manager.createNotificationChannel(channel1);Notification.Builder builder = new Notification.Builder(this, "0");builder.setSmallIcon(R.drawable.ic_launcher).setLargeIcon(Icon.createWithResource(this, R.drawable.ic_launcher)).setContentTitle("Notification").setContentText("Hello World").setContentIntent(pendingIntent);manager.notify(1, builder.build());}
}

效果如下

在这里插入图片描述

若采用RemoteView,可以自定义通知栏的布局,notification.xml文件如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/root"android:layout_width="match_parent"android:layout_height="match_parent"><ImageViewandroid:id="@+id/iv"android:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="1" /><TextViewandroid:id="@+id/tv"android:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="1"android:gravity="center_vertical" />
</LinearLayout>

代码如下,可通过一系列set方法设置布局

public class MainActivity extends AppCompatActivity {private static final String TAG = "MainActivity";protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.baidu.com"));PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);NotificationChannel channel1 = new NotificationChannel("0", "channel1", NotificationManager.IMPORTANCE_LOW);manager.createNotificationChannel(channel1);RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification);remoteViews.setTextViewText(R.id.tv, "Hello Android");remoteViews.setImageViewResource(R.id.iv, R.drawable.ic_launcher);remoteViews.setOnClickPendingIntent(R.id.root, pendingIntent);Notification.Builder builder = new Notification.Builder(this, "0");builder.setSmallIcon(R.drawable.ic_launcher).setCustomContentView(remoteViews);manager.notify(1, builder.build());}
}

效果如下

在这里插入图片描述

Widget

res/layout下创建widget.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"><ImageViewandroid:id="@+id/iv"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/ic_launcher" />
</LinearLayout>

res/xml下创建appwidget_provider_info.xml,设置最小宽高、自动更新的周期(ms)

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"android:initialLayout="@layout/widget"android:minWidth="84dp"android:minHeight="84dp"android:updatePeriodMillis="86400000"></appwidget-provider>

创建MyAppWidgetProvider,给小组件设置一个点击动画

  • onEnable:第一次添加时调用,可添加多次,但只在第一次调用
  • onUpdate:添加或更新(周期时间到)时调用
  • onDeleted:删除时调用
  • onDisabled:最后一个小组件被删除时调用
  • onReceive :分发上面的事件
public class MyAppWidgetProvider extends AppWidgetProvider {private static final String TAG = "MyAppWidgetProvider";public static final String CLICK_ACTION = "com.demo.demo0.MyAppWidgetProvider.CLICK";public MyAppWidgetProvider() {super();}@Overridepublic void onReceive(Context context, Intent intent) {super.onReceive(context, intent);String action = intent.getAction();Log.d(TAG, "onReceive: action = " + action);if (CLICK_ACTION.equals(action)) {Toast.makeText(context, "click", Toast.LENGTH_SHORT).show();new Thread(new Runnable() {@Overridepublic void run() {Bitmap srcBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);for (int i = 0; i < 37; i++) {float degree = (i * 10) % 360;RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);remoteViews.setImageViewBitmap(R.id.iv, rotateBitmap(context, srcBitmap, degree));/*Intent clickIntent = new Intent();clickIntent.setAction(CLICK_ACTION);clickIntent.setComponent(new ComponentName(context, "com.demo.demo0.MyAppWidgetProvider"));PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, clickIntent, 0);remoteViews.setOnClickPendingIntent(R.id.iv, pendingIntent);*/appWidgetManager.updateAppWidget(new ComponentName(context, MyAppWidgetProvider.class), remoteViews);SystemClock.sleep(30);}}}).start();}}@Overridepublic void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {super.onUpdate(context, appWidgetManager, appWidgetIds);Log.d(TAG, "onUpdate: ");int count = appWidgetIds.length;Log.d(TAG, "onUpdate: count = " + count);for (int appWidgetId : appWidgetIds) {onWidgetUpdate(context, appWidgetManager, appWidgetId);}}private void onWidgetUpdate(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {Log.d(TAG, "onWidgetUpdate: appWidgetId = " + appWidgetId);RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);Intent intentClick = new Intent();intentClick.setAction(CLICK_ACTION);intentClick.setComponent(new ComponentName(context, "com.demo.demo0.MyAppWidgetProvider"));PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intentClick, 0);remoteViews.setOnClickPendingIntent(R.id.iv, pendingIntent);appWidgetManager.updateAppWidget(appWidgetId, remoteViews);}private Bitmap rotateBitmap(Context context, Bitmap srcBitmap, float degree) {Matrix matrix = new Matrix();matrix.reset();matrix.setRotate(degree);return Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true);}
}

AppWidgetProvider本质是一个广播,需要在Manifest中注册,第二个Action是桌面组件的标识必须要加

<receiverandroid:name=".MyAppWidgetProvider"><meta-dataandroid:name="android.appwidget.provider"android:resource="@xml/appwidget_provider_info" /><intent-filter><action android:name="com.demo.demo0.MyAppWidgetProvider.CLICK" /><action android:name="android.appwidget.action.APPWIDGET_UPDATE" /></intent-filter>
</receiver>

PendingIntent

PendingIntent是在将来的某个不确定的时刻发生,而Intent是立刻发生

在这里插入图片描述

PendingIntent通过send和cancel方法发送和取消特定的Intent

  • requesetCode一般情况下设为0
  • 当ComponentName和intent-filter相同时,两个Intent相同
  • 当Intent和requestCode相同时,两个PendingIntent相同

Flag常用的有:

  • FLAG_ONE_SHOT:当前PendingIntent只能被调用一次,随后被自动cancel,后续send会调用失败。对于消息来说,后续通知和第一条通知保持一致,单击任一条通知后,其他无法再打开
  • FLAG_NO_CREATE:当前PendingIntent不会主动创建,若之前不存在,则调用上面方法返回null
  • FLAG_CANCEL_CURRENT:若当前PendingIntent已存在,则会被cancel并创建新的,被cancel的通知再点击无作用。对于消息来说,只有最新的才能打开
  • FLAG_UPDATE_CURRENT:若当前PendingIntent已存在,则更新Intent中的Extra。对于消息来说,前面通知和最后一条通知保持一致,且都可以打开

RemoteViews内部机制

RemoteViews用于在其他进程中显示并更新UI,所支持的类型有

在这里插入图片描述

为避免每次对RemoteViews的操作都通过Binder传输,提供了Action封装对View的操作,如下

在这里插入图片描述

如对于setTextViewText()方法,传入对应操作的方法名

public void setTextViewText(int viewId, CharSequence text) {setCharSequence(viewId, "setText", text);
}

而在setCharSequence()中添加子类ReflectionAction

public void setCharSequence(int viewId, String methodName, CharSequence value) {addAction(new ReflectionAction(viewId, methodName, ReflectionAction.CHAR_SEQUENCE, value));
}

并将Action添加到ArrayList

private void addAction(Action a) {......if (mActions == null) {mActions = new ArrayList<>();}mActions.add(a);
}

每当调用setxxx()方法时,并不会立即更新界面,而必须要通过NotificationManager的notify()或AppWidgetManager的updateAppWidget(),其内部会调用RemoteViews的

  • apply():加载布局并更新界面
  • reApply():只会更新界面

如下为AppWidgetHostView的updateAppWidget()方法

public void updateAppWidget(RemoteViews remoteViews) {applyRemoteViews(remoteViews, true);
}protected void applyRemoteViews(RemoteViews remoteViews, boolean useAsyncIfPossible) {......if (content == null && layoutId == mLayoutId) {try {remoteViews.reapply(mContext, mView, mOnClickHandler);content = mView;recycled = true;if (LOGD) Log.d(TAG, "was able to recycle existing layout");} catch (RuntimeException e) {exception = e;}}if (content == null) {try {content = remoteViews.apply(mContext, this, mOnClickHandler);if (LOGD) Log.d(TAG, "had to inflate new layout");} catch (RuntimeException e) {exception = e;}}......
}

apply()方法通过inflateView()获取View返回

public View apply(Context context, ViewGroup parent, OnClickHandler handler) {RemoteViews rvToApply = getRemoteViewsToApply(context);View result = inflateView(context, rvToApply, parent);rvToApply.performApply(result, parent, handler);return result;
}

performApply()则是遍历调用Action的apply()方法

private void performApply(View v, ViewGroup parent, OnClickHandler handler) {if (mActions != null) {handler = handler == null ? DEFAULT_ON_CLICK_HANDLER : handler;final int count = mActions.size();for (int i = 0; i < count; i++) {Action a = mActions.get(i);a.apply(v, parent, handler);}}
}

再看子类ReflectionAction中apply()具体实现,可知其通过反射调用

@Override
public void apply(View root, ViewGroup rootParent, OnClickHandler handler) {final View view = root.findViewById(viewId);if (view == null) return;Class<?> param = getParameterType();if (param == null) {throw new ActionException("bad type: " + this.type);}try {getMethod(view, this.methodName, param, false /* async */).invoke(view, this.value);} catch (Throwable ex) {throw new ActionException(ex);}
}

模拟RemoteViews

如下模拟在MainActivity中通过广播传递RemoteViews,修改SecondActivity中的布局,manifest如下

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"package="com.demo.demo0"><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activityandroid:name=".SecondActivity"android:process=":remote"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><activity android:name=".MainActivity"></activity></application></manifest>

MainActivity创建RemoteViews并发送广播

public class MainActivity extends AppCompatActivity {private static final String TAG = "MainActivity";protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification);remoteViews.setTextViewText(R.id.tv, "Hello RemoteViews");remoteViews.setImageViewResource(R.id.iv, R.drawable.ic_launcher);Intent remoteViewsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.baidu.com"));PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, remoteViewsIntent, PendingIntent.FLAG_UPDATE_CURRENT);remoteViews.setOnClickPendingIntent(R.id.root, pendingIntent);Intent broadcastIntent = new Intent(SecondActivity.ACTION_REMOTE_VIEWS);broadcastIntent.putExtra(SecondActivity.EXTRA_REMOTE_VIEWS, remoteViews);sendBroadcast(broadcastIntent);finish();}
}

布局notification.xml如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/root"android:layout_width="match_parent"android:layout_height="match_parent"><ImageViewandroid:id="@+id/iv"android:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="1" /><TextViewandroid:id="@+id/tv"android:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="1"android:gravity="center_vertical" />
</LinearLayout>

SecondActivity接收广播获取RemoteViews,调用apply方法并把View添加到自身布局

public class SecondActivity extends AppCompatActivity {private static final String TAG = "SecondActivity";private LinearLayout mRemoteViesContainer;public static final String ACTION_REMOTE_VIEWS = "ACTION_REMOTE_VIEWS";public static final String EXTRA_REMOTE_VIEWS = "EXTRA_REMOTE_VIEWS";private BroadcastReceiver mRemoteViewsReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {RemoteViews remoteViews = intent.getParcelableExtra(EXTRA_REMOTE_VIEWS);if (remoteViews != null) {updateUI(remoteViews);}}};private void updateUI(RemoteViews remoteViews) {View view = remoteViews.apply(getApplicationContext(), mRemoteViesContainer);mRemoteViesContainer.addView(view);}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_second);initView();startActivity(new Intent(this, MainActivity.class));}private void initView() {mRemoteViesContainer = findViewById(R.id.remote_views_container);IntentFilter intentFilter = new IntentFilter(ACTION_REMOTE_VIEWS);registerReceiver(mRemoteViewsReceiver, intentFilter);}@Overrideprotected void onDestroy() {super.onDestroy();unregisterReceiver(mRemoteViewsReceiver);}
}

SecondActivity布局为一个空的LinearLayout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/remote_views_container"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"></LinearLayout>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/53817.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

屏幕取色器Mac版_苹果屏幕取色工具_屏幕取色器工具

Sip for Mac 是Mac系统平台上的一款老牌的颜色拾取工具&#xff0c;是设计师和前端开发工作者必不可少的屏幕取色软件&#xff0c;你只需要用鼠标点一下即可轻松地对屏幕上的任何颜色进行采样和编码&#xff0c;并将颜色数据自动存到剪切板&#xff0c;方便随时粘贴出来。 Sip…

Aligning Large Language Models with Human: A Survey

本文也是LLM相关的综述文章&#xff0c;针对《Aligning Large Language Models with Human: A Survey》的翻译。 对齐人类与大语言模型&#xff1a;综述 摘要1 引言2 对齐数据收集2.1 来自人类的指令2.1.1 NLP基准2.1.2 人工构造指令 2.2 来自强大LLM的指令2.2.1 自指令2.2.2 …

# 关于Linux下的parted分区工具显示起始点为1049kB的问题解释

关于Linux下的parted分区工具显示起始点为1049kB的问题解释 文章目录 关于Linux下的parted分区工具显示起始点为1049kB的问题解释1 问题展示&#xff1a;2 原因3 修改为KiB方式显示4 最后 1 问题展示&#xff1a; kevinTM1701-b38cbc23:~$ sudo parted /dev/nvme1n1 GNU Part…

分治法、回溯法与动态规划

算法思想比较 回溯法&#xff1a;有“通用解题法”之称&#xff0c;用它可以系统地搜索问题的所有解。回溯法是按照深度优先搜索(DFS)的策略&#xff0c;从根结点出发深度探索解空间树分治法&#xff1a;将一个难以直接解决的大问题&#xff0c;分割成一些规模较小的相同问题&…

测试平台——项目模块模型类设计

这里写目录标题 一、项目应用1、项目包含接口&#xff1a;2、创建子应用3、项目模块设计a、模型类设计b、序列化器类设计c、视图类设计 4、接口模块设计a、模型类设计b、序列化器类设计c、视图类设计 5、环境模块设计6、DRF中的通用过滤6.1、设置过滤器后端 一、项目应用 1、项…

程序环境和预处理(含C语言程序的编译+链接)--1

&#x1f389;个人名片&#xff1a; &#x1f43c;作者简介&#xff1a;一名乐于分享在学习道路上收获的大二在校生 &#x1f43b;‍❄个人主页&#x1f389;&#xff1a;GOTXX &#x1f43c;个人WeChat&#xff1a;ILXOXVJE &#x1f43c;本文由GOTXX原创&#xff0c;首发CSDN…

Palo Alto Networks® PA-220R 下一代防火墙 确保恶劣工况下的网络安全

一、主要安全功能 1、每时每刻在各端口对全部应用进行分类 • 将 App-ID 用于工业协议和应用&#xff0c;例如 Modbus、 DNP3、IEC 60870-5-104、Siemens S7、OSIsoft PI 等。 • 不论采用何种端口、SSL/SSH 加密或者其他规避技术&#xff0c;都会识别应用。 • 使用…

树的层次遍历

层次遍历简介 广度优先在面试里出现的频率非常高&#xff0c;整体属于简单题。而广度优先遍历又叫做层次遍历&#xff0c;基本过程如下&#xff1a; 层次遍历就是从根节点开始&#xff0c;先访问根节点下面一层全部元素&#xff0c;再访问之后的层次&#xff0c;类似金字塔一样…

Python 开发工具 Pycharm —— 使用技巧Lv.3

单步执行调试 1&#xff1a; 鼠标左键单击红点是断点行 2&#xff1a;甲虫样式是进行调试方式运行&#xff0c;鼠标左键单击点击 3&#xff1a; 单步运行图标&#xff0c;点击让程序运行一行 4&#xff1a; 步入步出&#xff0c;可以进入当前代码行函数内 5&#xff1a;重新运行…

C语言笔试训练【第三天】

大家好&#xff0c;我是纪宁。 今天是C语言笔试训练的第三天&#xff0c;大家加油&#xff01; 第一题 1、已知函数的原型是&#xff1a; int fun(char b[10], int *a) &#xff0c;设定义&#xff1a; char c[10];int d; &#xff0c;正确的调用语句是&#xff08; &#xf…

Java分布式微服务1——注册中心(Eureka/Nacos)

文章目录 基础知识注册中心Eureka注册中心与Ribbon负载均衡1、Eureka注册中心2、Eureka的搭建3、Eureka服务注册4、复制服务实例5、拉取服务6、Ribbon负载均衡的流程及Eureka规则调整&#xff1a;7、Ribbon负载均衡饥饿加载 Nacos注册中心1、服务端Nacos安装与启动2、客户端Nac…

iOS 搭建组件化私有库

一、创建私有库索引 步骤1是在没有索引库的情况下或者是新增索引的时候才需要用到&#xff08;创建基础组件库&#xff09; 首先在码云上建立一个私有库索引&#xff0c;起名为SYComponentSpec 二、本地添加私有库索引 添加私有库索引 pod repo add SYComponentSpec https:/…