[关闭]
@ZeroGeek 2015-10-23T09:10:59.000000Z 字数 1984 阅读 656

为App添加桌面小部件

每周主题


简述

Android弱化了线程和进程等概念,主要表现为组件。这个桌面小部件与App是分离的,可以通过服务或广播来通信。

1.在启动的Activity里加

  1. <intent-filter>
  2. <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
  3. </intent-filter>

2. 定义一个部件组件(改自官网文档)

  1. public class MyAppWidget extends AppWidgetProvider {
  2. public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
  3. final int N = appWidgetIds.length;
  4. // Perform this loop procedure for each App Widget that belongs to this provider
  5. for (int i=0; i<N; i++) {
  6. int appWidgetId = appWidgetIds[i];
  7. // 创建Intent来启动Acitivity
  8. Intent intent = new Intent(context, MainActivity.class);
  9. PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
  10. // Get the layout for the App Widget and attach an on-click listener
  11. // to the button
  12. // 初始化部件布局,设置监听事件
  13. RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget_provider_layout);
  14. views.setOnClickPendingIntent(R.id.button, pendingIntent);
  15. // Tell the AppWidgetManager to perform an update on the current app widget
  16. appWidgetManager.updateAppWidget(appWidgetId, views);
  17. }
  18. }
  19. }

3. 写好布局 R.layout.appwidget_provider_layout

我只加了个按钮

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent">
  6. <Button
  7. android:id="@+id/button"
  8. android:layout_width="match_parent"
  9. android:layout_height="match_parent"
  10. android:text="OK" />
  11. </LinearLayout>

4. res里新建一个xml文件夹,添加配置

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:minWidth="200dip"
  4. android:minHeight="50dip"
  5. android:initialLayout="@layout/appwidget_provider_layout" >
  6. </appwidget-provider>

5. 在AndroidManifest.xml注册

  1. <receiver android:name="MyAppWidget" android:label="测试插件" >
  2. <intent-filter>
  3. <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
  4. </intent-filter>
  5. <meta-data android:name="android.appwidget.provider"
  6. android:resource="@xml/my_provider" />
  7. </receiver>

6. 完成

http://androiddoc.qiniudn.com/guide/topics/appwidgets/index.html

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注