【问题标题】:Android Widget With Buttons, Remove Update带有按钮的 Android 小部件,删除更新
【发布时间】:2014-01-09 14:38:42
【问题描述】:

我正在创建一个简单的 Android 小部件,它具有在应用程序中打开不同活动的按钮。

public class ExampleAppWidgetProvider extends AppWidgetProvider {

  public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    final int N = appWidgetIds.length;

    Log.i("ExampleWidget",  "Updating widgets " + Arrays.asList(appWidgetIds));

    // Perform this loop procedure for each App Widget that belongs to this
    // provider
    for (int i = 0; i < N; i++) {
      int appWidgetId = appWidgetIds[i];

      // Create an Intent to launch ExampleActivity
      Intent intentForHome = new Intent(context, WidgetExampleActivity.class);
      PendingIntent pendingIntentForHome = PendingIntent.getActivity(context, 0, intentForHome, 0);
      // Get the layout for the App Widget and attach an on-click listener
      // to the button
      RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget1);
      views.setOnClickPendingIntent(R.id.button, pendingIntentForHome);

      // Create an Intent to launch Second Activity
      Intent intentForSecond = new Intent(context, SecondActivity.class);
      PendingIntent pendingIntentForSecond = PendingIntent.getActivity(context, 0, intentForSecond, 0);
      // Get the layout for the App Widget and attach an on-click listener
      // to the button
      views.setOnClickPendingIntent(R.id.button2, pendingIntentForSecond);


      // Tell the AppWidgetManager to perform an update on the current app
      // widget
      appWidgetManager.updateAppWidget(appWidgetId, views);
    }
  }
}

这可以通过每个按钮打开正确的活动。 但我只是想知道, updatePeriodMillis 是干什么用的。我不需要小部件中的任何内容来更新,只希望按钮打开应用程序。我可以摆脱更新部分吗?我不希望我的应用程序不断更新小部件。

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="294dp"
    android:minHeight="72dp"
    android:updatePeriodMillis="10000"
    android:initialLayout="@layout/widget1">
</appwidget-provider>

这也是从 Widget 执行按钮单击的正确方法。我在一些教程中看到它的做法有所不同? 谢谢。

【问题讨论】:

标签: android android-widget


【解决方案1】:

updatePeriod 用于在某个时间间隔内刷新小部件。如果您不需要这个,请将您的 updatePeriodMillis 设置为 0

【讨论】:

  • 谢谢。我也可以删除这行代码 appWidgetManager.updateAppWidget(appWidgetId, views);这也是从小部件执行按钮单击的正确方法。我在一些教程中看到它的完成方式不同?
【解决方案2】:

This page 描述了如何使用按钮创建小部件。如果您不需要刷新您的小部件,请将updatePeriodMillis 修复为 0。请注意,您不能使用频率小于 15 分钟的updatePeriodMillis,并且无法保证刷新频率(可能会有一些延迟)。如果您想以固定频率刷新,请使用警报或注册到 Intent.ACTION_TIME_TICK 并自行管理

对于处理按钮事件,这是正确的方法,因为它是 Android 页面(上图)提到的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2020-06-22
    相关资源
    最近更新 更多