首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 开源软件 >

接收来源于AppWidget的广播并更新控件状态

2012-06-30 
接收来自AppWidget的广播并更新控件状态一 接收来自App Widget的广播?? 1.在AndroidManifest.xml为AppWidg

接收来自AppWidget的广播并更新控件状态

一 接收来自App Widget的广播

?? 1.在AndroidManifest.xml为AppWidgetProvider注册新的intente-filter;

?? 2.使用getBroadcast()创建一个PendingIntent;

?? 3.为App Widget中的控件注册处理器;

?? 4.在onReceive方法中接收广播;

a.布局文件中有个Button

  <Button   android:id="@+id/widgetButtonId"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:text="測試用按鈕"  />

?

b.在extends AppWidgetProvider实现类中定义了一个变量

private static final String state="my_state";

?c.在AndroidManifest.xml注册

<receiver android:name="ExampleAppWidgetProvider"><intent-filter><action android:name="android.appwidget.action.APPWIDGET_UPDATE" /></intent-filter><intent-filter ><action android:name="my_state"/></intent-filter><meta-data android:name="android.appwidget.provider"android:resource="@xml/example_appwidget_info" /></receiver>

?d.复写onUpdate方法发送广播

@Overridepublic void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {Intent intent=new Intent();intent.setAction(state);//发送广播PendingIntent pendingIntent=PendingIntent.getBroadcast(context, 0, intent, 0);RemoteViews remoteViews=new RemoteViews(context.getPackageName(), R.layout.example_appwidget);remoteViews.setOnClickPendingIntent(R.id.widgetButtonId, pendingIntent);appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);super.onUpdate(context, appWidgetManager, appWidgetIds);}

?

d.复写onReceive方法接收广播

@Overridepublic void onReceive(Context context, Intent intent) {String action=intent.getAction();if(state.equals(action)){System.out.println("onReceive--"+action);}else{super.onReceive(context, intent);}}

?

当我们点击button时,后台打印出数据:


接收来源于AppWidget的广播并更新控件状态
?二 更新控件状态

1.代码同上,只是在布局文件中加入一个textview

  <TextView   android:id="@+id/widgetTextId"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:text="firstWidgetText"  android:background="#000000"    />

?2.onUpdate代码同上,只是onReveice方法不同

@Overridepublic void onReceive(Context context, Intent intent) {String action=intent.getAction();if(state.equals(action)){RemoteViews remoteViews=new RemoteViews(context.getPackageName(), R.layout.example_appwidget);remoteViews.setTextViewText(R.id.widgetTextId, "xixi");AppWidgetManager appWidgetManager=AppWidgetManager.getInstance(context);ComponentName componentName=new ComponentName(context,ExampleAppWidgetProvider.class);appWidgetManager.updateAppWidget(componentName, remoteViews);}else{super.onReceive(context, intent);}}

?

程序运行效果就是,点击button文字改变为“xixi”.

?


接收来源于AppWidget的广播并更新控件状态
?

热点排行