Widget桌面小组件实现
1)要更新Widget中的内容,一般都是写在onUpdate方法里面,但是更新的时候,要把Widget当做一个RemoteViews来处理。利用Service更新Widget中的内容。
2)Widget中:在onEnable方法中启动Service,在onDisable方法中停止Service,在onUpdate方法中为按钮绑定一个监听器,但是此时不能利用传统的方式进行绑定。
(传统方式:Button btn = view.findViewById(id); btn.setOnClickListener(listener);)
3)在Widget中绑定监听器必须利用RemoteViews提供的相关API才可以: view.setOnClickPendingIntent(id,pendingIntent);
当id对应的按钮点击的时候,会触发PendingIntent,随着PendingIntent的触发,就会发送广播。 该广播被Service中的广播接收器接收,执行对应的代码逻辑。
Step1 res/layout下面,写Widget的布局文件(一个Button,点击获取一个随机数字,显示到TextView上)
<?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" >
<TextView
android:id="@+id/tv_widget_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:hint="..."
/>
<Button
android:id="@+id/btn_widget_button"
android:layout_width="match_parent"
android:layout_height="wrap_