欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android编程之桌面小部件AppWidgetProvider用法示例

程序员文章站 2023-12-12 18:18:46
本文实例讲述了android编程之桌面小部件appwidgetprovider用法。分享给大家供大家参考,具体如下: /** * 桌面小部件 appwidge...

本文实例讲述了android编程之桌面小部件appwidgetprovider用法。分享给大家供大家参考,具体如下:

/**
 * 桌面小部件 appwidget配置
 *
 * @description:
 * @author ldm
 * @date 2016-5-16 下午1:57:16
 */
public class exampleappwidgetconfigure extends activity {
  static final string tag = "exampleappwidgetconfigure";
  // 保存的文件名
  private static final string prefs_name = "com.example.android.apis.appwidget.exampleappwidgetprovider";
  // 保存的字段key
  private static final string pref_prefix_key = "prefix_";
  // 小部件 对应id
  int mappwidgetid = appwidgetmanager.invalid_appwidget_id;
  // 输入框
  edittext mappwidgetprefix;
  public exampleappwidgetconfigure() {
    super();
  }
  @override
  public void oncreate(bundle icicle) {
    super.oncreate(icicle);
    setresult(result_canceled);
    // 设置布局
    setcontentview(r.layout.appwidget_configure);
    mappwidgetprefix = (edittext) findviewbyid(r.id.appwidget_prefix);
    // 设置监听
    findviewbyid(r.id.save_button).setonclicklistener(monclicklistener);
    // 获取intent传递过来的数据
    intent intent = getintent();
    bundle extras = intent.getextras();
    if (extras != null) {
      mappwidgetid = extras.getint(appwidgetmanager.extra_appwidget_id,
          appwidgetmanager.invalid_appwidget_id);
    }
    if (mappwidgetid == appwidgetmanager.invalid_appwidget_id) {
      finish();
    }
    mappwidgetprefix.settext(loadtitlepref(exampleappwidgetconfigure.this,
        mappwidgetid));
  }
  view.onclicklistener monclicklistener = new view.onclicklistener() {
    public void onclick(view v) {
      final context context = exampleappwidgetconfigure.this;
      string titleprefix = mappwidgetprefix.gettext().tostring();
      //保存到sharedpreferences文件
      savetitlepref(context, mappwidgetid, titleprefix);
      appwidgetmanager appwidgetmanager = appwidgetmanager
          .getinstance(context);
      //更新小部件
      exampleappwidgetprovider.updateappwidget(context, appwidgetmanager,
          mappwidgetid, titleprefix);
      intent resultvalue = new intent();
      resultvalue.putextra(appwidgetmanager.extra_appwidget_id,
          mappwidgetid);
      setresult(result_ok, resultvalue);
      finish();
    }
  };
  static void savetitlepref(context context, int appwidgetid, string text) {
    sharedpreferences.editor prefs = context.getsharedpreferences(
        prefs_name, 0).edit();
    prefs.putstring(pref_prefix_key + appwidgetid, text);
    prefs.commit();
  }
  static string loadtitlepref(context context, int appwidgetid) {
    sharedpreferences prefs = context.getsharedpreferences(prefs_name, 0);
    string prefix = prefs.getstring(pref_prefix_key + appwidgetid, null);
    if (prefix != null) {
      return prefix;
    } else {
      return context.getstring(r.string.appwidget_prefix_default);
    }
  }
  static void deletetitlepref(context context, int appwidgetid) {
  }
  static void loadalltitleprefs(context context,
      arraylist<integer> appwidgetids, arraylist<string> texts) {
  }
}

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:orientation="vertical" >
  <textview
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="this text will be shown before the date in our example widget." />
  <edittext
    android:id="@+id/appwidget_prefix"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
  <button
    android:id="@+id/save_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@android:string/ok" />
</linearlayout>

/**
 * appwidgetprovider小部件广播组件使用:
 * 1, 实现appwidgetprovider的子类,并至少override onupdate()方法
 * 2,在androidmanifest.xml中,声明上述的appwidgetprovider的子类是一个receiver,并且:
 * 该receiver的intent-filter的action必须包含“android.appwidget.action.appwidget_update”;
 * 该receiver的meta-data为“android.appwidget.provider”,并用一个xml文件来描述布局属性。
 * 3, 在第2点中的xml文件中描述布局属性的节点名称必须为“appwidget-provider”。
 *
 * @description:
 * @author ldm
 * @date 2016-5-16 下午1:43:31
 */
public class exampleappwidgetprovider extends appwidgetprovider {
  // log打印日志标签
  private static final string tag = "exampleappwidgetprovider";
  /**
   * onupdate() 处理appwidgetmanager.action_appwidget_update广播。
   * 该广播在需要appwidgetprovider提供remoteviews数据时
   * ,由appwidgetservice.sendupdateintentlocked()发出。
   */
  @override
  public void onupdate(context context, appwidgetmanager appwidgetmanager,
      int[] appwidgetids) {
    log.d(tag, "onupdate");
    final int n = appwidgetids.length;
    for (int i = 0; i < n; i++) {
      //获取到id
      int appwidgetid = appwidgetids[i];
      //设置标题
      string titleprefix = exampleappwidgetconfigure.loadtitlepref(
          context, appwidgetid);
      //更新appwidget
      updateappwidget(context, appwidgetmanager, appwidgetid, titleprefix);
    }
  }
  /**
   * ondeleted() 处理appwidgetmanager.action_appwidget_deleted广播。
   * 该广播在有该appwidgetprovider的实例被删除时
   * ,由appwidgetservice.deleteappwidgetlocked()发出。
   */
  @override
  public void ondeleted(context context, int[] appwidgetids) {
    log.d(tag, "ondeleted");
    final int n = appwidgetids.length;
    for (int i = 0; i < n; i++) {
      exampleappwidgetconfigure.deletetitlepref(context, appwidgetids[i]);
    }
  }
  /**
   * onenabled() 处理appwidgetmanager.action_appwidget_enabled广播。
   * 该广播在该appwidgetprovider被实例化时,由appwidgetservice.sendenableintentlocked()发出。
   */
  @override
  public void onenabled(context context) {
    log.d(tag, "onenabled");
    packagemanager pm = context.getpackagemanager();
    pm.setcomponentenabledsetting(new componentname(
        "com.example.android.apis",
        ".appwidget.examplebroadcastreceiver"),
        packagemanager.component_enabled_state_enabled,
        packagemanager.dont_kill_app);
  }
  /**
   * ondisabled() 处理appwidgetmanager.action_appwidget_disabled广播。
   * 该广播在该appwidgetprovider的所有实例中的最后一个实例被删除时
   * ,由appwidgetservice.deleteappwidgetlocked()发出。
   */
  @override
  public void ondisabled(context context) {
    log.d(tag, "ondisabled");
    packagemanager pm = context.getpackagemanager();
    //设置组件可用
    pm.setcomponentenabledsetting(new componentname(
        "com.example.android.apis",
        ".appwidget.examplebroadcastreceiver"),
        packagemanager.component_enabled_state_enabled,
        packagemanager.dont_kill_app);
  }
  static void updateappwidget(context context,
      appwidgetmanager appwidgetmanager, int appwidgetid,
      string titleprefix) {
    log.d(tag, "updateappwidget appwidgetid=" + appwidgetid
        + " titleprefix=" + titleprefix);
    charsequence text = context.getstring(r.string.appwidget_text_format,
        exampleappwidgetconfigure.loadtitlepref(context, appwidgetid),
        "0x" + long.tohexstring(systemclock.elapsedrealtime()));
    // 创建remoteviews 对象
    remoteviews views = new remoteviews(context.getpackagename(),
        r.layout.appwidget_provider);
    // 设置remoteviews 对象的文本
    views.settextviewtext(r.id.appwidget_text, text);
    // 告诉appwidgetmanager 显示 views对象给widget.
    appwidgetmanager.updateappwidget(appwidgetid, views);
  }
}

小部件布局

<?xml version="1.0" encoding="utf-8"?>
<textview xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/appwidget_text"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:background="#ffff00ff"
  android:textcolor="#ff000000"
/>

public class examplebroadcastreceiver extends broadcastreceiver {
  @override
  public void onreceive(context context, intent intent) {
    log.d("exmamplebroadcastreceiver", "intent=" + intent);
    //获取广播的action
    string action = intent.getaction();
    //对action进行判断
    if (action.equals(intent.action_timezone_changed)
        || action.equals(intent.action_time_changed)) {
      appwidgetmanager gm = appwidgetmanager.getinstance(context);
      arraylist<integer> appwidgetids = new arraylist<integer>();
      arraylist<string> texts = new arraylist<string>();
      exampleappwidgetconfigure.loadalltitleprefs(context, appwidgetids, texts);
      final int n = appwidgetids.size();
      for (int i=0; i<n; i++) {
        exampleappwidgetprovider.updateappwidget(context, gm, appwidgetids.get(i), texts.get(i));
      }
    }
  }
}

在androidmanifest.xml中添加相应组件:

exampleappwidgetconfigure

<activity android:name=".appwidget.exampleappwidgetconfigure" >
  <intent-filter>
    <action android:name="android.appwidget.action.appwidget_configure" />
  </intent-filter>
</activity>

exampleappwidgetprovider

<receiver android:name=".appwidget.exampleappwidgetprovider" >
  <meta-data
    android:name="android.appwidget.provider"
    android:resource="@xml/appwidget_provider" />
  <intent-filter>
    <action android:name="android.appwidget.action.appwidget_update" />
  </intent-filter>
</receiver>

examplebroadcastreceiver

 <receiver
  android:name=".appwidget.examplebroadcastreceiver"
  android:enabled="false" >
  <intent-filter>
    <action android:name="android.intent.action_timezone_changed" />
    <action android:name="android.intent.action_time" />
  </intent-filter>
</receiver>

开源代码:https://github.com/ldm520/android_api_demos

更多关于android相关内容感兴趣的读者可查看本站专题:《android基本组件用法总结》、《android开发入门与进阶教程》、《android布局layout技巧总结》、《android视图view技巧总结》、《android编程之activity操作技巧总结》、《android资源操作技巧汇总》及《android控件用法总结

希望本文所述对大家android程序设计有所帮助。

上一篇:

下一篇: