1.新建一个类,继承AppWidgetProvider
2.配置manifest文件
<span style="font-size:18px;"><span style="white-space:pre"> </span><!--窗口小部件-->
<receiver android:name=".receiver.MyWidget">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/process_widget_provider"/>
</receiver>
</span>
3.复写方法
public class MyWidget extends AppWidgetProvider{
//接收到广播时调用
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
}
//每次创建都会调用
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
//每次销毁都会调用
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
}
//创建第一个widget时调用
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
}
//最后一个widget被销毁时调用
@Override
public void onDisabled(Context context) {
super.onDisabled(context);
}
}
4.创建xml文件
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:initialLayout="@layout/process_widget"
android:minHeight="72.0dip"
android:minWidth="294.0dip"
android:updatePeriodMillis="0"/>
5.创建布局文件
6.获取窗口小部件管理器
AppWidgetManager mAwm = AppWidgetManager.getInstance(this)
7.
<span style="white-space:pre"> </span>ComponentName provider = new ComponentName(getApplicationContext(), MyWidget.class);
RemoteViews views = new RemoteViews(getPackageName(), R.layout.process_widget);
views.setTextViewText(R.id.process_count,text);
Intent intent = new Intent();
<span style="white-space:pre"> </span>//自定义动作
intent.setAction("com.example.frog.mobilsafe.ACTION_KILL");
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
<span style="white-space:pre"> </span>//设置点击事件
views.setOnClickPendingIntent(R.id.btn_clear,pendingIntent);
<span style="white-space:pre"> </span>//更新窗口小部件UI
mAwm.updateAppWidget(provider, views);