1、基本使用方法
(1)在AndroidManifest.xml中声明:
widget本质是广播接收器,广播是四大组件之一,需要在AndroidManifest中声明:
<receiver android:name=".TestWidget">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@layout/setting_widget"> 此处定义了资源文件
</meta-data>
</receiver>
(2)setting_widget.xml资源文件:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minHeight="140dp"
android:minWidth="140dp"
android:previewImage="@drawable/point64red" 预览图
android:initialLayout="@layout/layout_widget" 这里才是他真正的布局文件
android:updatePeriodMillis="20000" 每隔多久更新一次
android:widgetCategory="home_screen" 可以显示到主屏幕上
>
</appwidget-provider>
(3)layout_widget.xml布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
(4)继承AppWidgetProvider类,复写onReceive和onUpdate方法:
onUpdate方法发送广播,发送给自己,然后自己在onReceive中获取并处理
public class TestWidget extends AppWidgetProvider {
public static final String WIDGET_BUTTON_ACTION = "WIDGET_BUTTON_ACTION";
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if(intent != null && TextUtils.equals(intent.getAction(), WIDGET_BUTTON_ACTION)){
Log.i("djtest", "onReceive: be clicked");
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.layout_widget);
remoteViews.setTextViewText(R.id.widget_textview, "be clicked");
remoteViews.setTextColor(R.id.widget_textview, Color.RED);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
ComponentName componentName = new ComponentName(context, TestWidget.class);
appWidgetManager.updateAppWidget(componentName, remoteViews);
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.layout_widget);
Intent intent = new Intent();
intent.setClass(context, TestWidget.class);
intent.setAction(WIDGET_BUTTON_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent,0);
remoteViews.setOnClickPendingIntent(R.id.widget_button, pendingIntent);
// 告诉控件已经操作响应过了
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
}
2、其他
与service的通信:可以通过广播来通信