Android appWidget 多个实例

2024-03-27

这个问题几乎是重复的Android - 多个appWidgets播放不同的声音 https://stackoverflow.com/questions/4225197/android-multiple-appwidgets-playing-diferent-sounds,但我的代码不起作用。我添加了一个带有小部件 ID 的额外意图,并用日志语句来证明这一点,但是每当我单击其中一个小部件(当有多个实例时)时,我只会获得最后一个 appWidgetId。看起来第一个小部件的意图在添加第二个小部件后发生了变化。如果另一篇文章中的代码应该可以工作,那么我一定忽略了一些东西,因为我相信我的代码的设置方式几乎相同。

 public class PhcaAppWidgetProvider extends AppWidgetProvider {
     private static final String ACTION_CLICK = "com.skipmorrow.phca.PhcaAppWidgetProvider.WIDGET_CLICKED";
     private final String widgetPageName = "_widget";
     private static final String PREFS_NAME = "PHCA";
     private static final String PREF_PREFIX_KEY = "prefix_";
     private static String MY_DEBUG = "PhcaAppWidget";

     @Override
     public void onUpdate(Context context, AppWidgetManager appWidgetManager,
             int[] appWidgetIds) {
        Log.d(MY_DEBUG, "Provider.onUpdate");
     }

     @Override
     public void onReceive(Context context, Intent intent) {
        String intentAction = intent.getAction();
        Log.d(MY_DEBUG, "Provider.onReceive(); action = " + intentAction);
        Bundle extras = intent.getExtras();

        // make a list of all extras, just so I can see what is in there...
        if (extras!=null) {
            Set<String> ks = extras.keySet();
            Iterator<String> iterator = ks.iterator();
            while (iterator.hasNext()) {
                String s = iterator.next();
                Log.d(MY_DEBUG, "Provider.Key found: " + s);
            }
        }
        else {
          Log.d(MY_DEBUG, "Provider.extras was null");
        }

            int[] appWidgetIds1 = intent.getIntArrayExtra("appWidgetIds");

            if (extras!=null && extras.containsKey("appWidgetIds")){
                // sometimes the intent comes back with an array of appWidgetIds, and sometimes the appWidgetId is stored
                // in the one extra "appWidgetId" Clicks never come with the array of appWidgetIds. They always come by
                // themselves
                Log.d(MY_DEBUG, "Provider.Intent extras does contain a key appWidgetIds");
                if (appWidgetIds1!=null) Log.d(MY_DEBUG, "Provider.Intent int array appWidgetIds1 size is " + appWidgetIds1.length);
                for (int i = 0; i<appWidgetIds1.length; i++) {
                    int appWidgetId = appWidgetIds1[i];
                    Log.d(MY_DEBUG, "Provider.Intent appWidgetIds1[" + i + "] = " + appWidgetId);
                    if (intentAction.equals("android.appwidget.action.APPWIDGET_UPDATE")) {
                        Log.d(MY_DEBUG, "Provider.APPWIDGET UPDATE");
                        updateWidgetState(context, intentAction, appWidgetId);
                    } else if (intentAction.equals("android.appwidget.action.APPWIDGET_DELETED")) {
                        // do nothing
                    }
                    else {
                        super.onReceive(context, intent);
                    }
                }
            } else {

            String intentData = intent.getDataString();
            Log.d(MY_DEBUG, "Provider.intent data = " + intentData);


            Integer appWidgetId = intent.getIntExtra("appWidgetId", -1);
            Log.d(MY_DEBUG, "Provider.appWidgetId = " + appWidgetId);

            if (intentAction.equals(ACTION_CLICK)) {
                Log.d(MY_DEBUG, "Provider.Clicked");
                SharedPreferences myPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_WORLD_WRITEABLE);
                Integer objNum = myPrefs.getInt(PREF_PREFIX_KEY + appWidgetId, -1);
                Log.d(MY_DEBUG, "Provider.ObjNum = " + objNum);
                if (objNum > -1) {
                    Log.d(MY_DEBUG, "Provider.Executing...");
                    PageAction pa = (PageAction) CommonActivity.GetPageObjectAtIndex(context, widgetPageName, objNum);
                    pa.ExecuteActionFromWidgetClick(context);
                }
            }
            else {
                super.onReceive(context, intent);
            } 
            }
     }

     public static void updateWidgetState(Context paramContext, String paramString, Integer appWidgetId)
     {
        Log.d(MY_DEBUG, "Provider.updateWidgetState; appWidgetId = " + appWidgetId + "; paramString = " + paramString);
        RemoteViews localRemoteViews = buildUpdate(paramContext, paramString, appWidgetId);
        ComponentName localComponentName = new ComponentName(paramContext, PhcaAppWidgetProvider.class);
        AppWidgetManager.getInstance(paramContext).updateAppWidget(localComponentName, localRemoteViews);
     }



     private static RemoteViews buildUpdate(Context ctx, String paramString, Integer appWidgetId)
     {
        Log.d(MY_DEBUG, "Provider.buildUpdate(); appWidgetId = " + appWidgetId + "; paramString = " + paramString);
        RemoteViews views = new RemoteViews(ctx.getPackageName(), R.layout.phca_appwidget);
        if (paramString.equals("android.appwidget.action.APPWIDGET_UPDATE")) {
            Log.d(MY_DEBUG, "Provider.buildUpdate().. APPWIDGET_UPDATE");
            Intent intent = new Intent(ctx, PhcaAppWidgetProvider.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(ACTION_CLICK);
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
            Uri data = Uri.withAppendedPath(
                Uri.parse("ABCD" + "://widget/id/")
                ,String.valueOf(appWidgetId));
            intent.setData(data);
            Log.d(MY_DEBUG, "Provider.Added intent extra \"" +  AppWidgetManager.EXTRA_APPWIDGET_ID + "\" = " + appWidgetId);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, appWidgetId, intent , PendingIntent.FLAG_UPDATE_CURRENT);
            views.setOnClickPendingIntent(R.id.phca_appwidget_layout, pendingIntent);
        }
        if(paramString.equals(ACTION_CLICK))
        {
            Log.d(MY_DEBUG, "Provider.buildUpdate().. CLICKED");
            Toast.makeText(ctx, "ACTION_CLICK", Toast.LENGTH_LONG).show();
        }
        return views; 
    }
 }

我确实有一个配置活动(ListActivity)这是我的 onListItemClick:

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    Toast.makeText(getApplicationContext(), "onListItemClick", Toast.LENGTH_SHORT);
    Log.d(MY_DEBUG, "Configurator.onListItemClick");
    SharedPreferences.Editor prefs = getSharedPreferences(PREFS_NAME, 0).edit();
    prefs.putInt(PREF_PREFIX_KEY + mAppWidgetId, position);
    prefs.commit();
    Log.d(MY_DEBUG, "Configurator.Prefs.commit()");

    // Push widget update to surface with newly set prefix
    Log.d(MY_DEBUG, "Configurator.calling updateWidgetState with appWidgetId = " + mAppWidgetId);
    PhcaAppWidgetProvider.updateWidgetState(getApplicationContext(), "android.appwidget.action.APPWIDGET_UPDATE", mAppWidgetId);
    Log.d(MY_DEBUG, "Configurator.updateWidgetState complete");
    Intent resultValue = new Intent();
    Uri data = Uri.withAppendedPath(
            Uri.parse("ABCD" + "://widget/id/")
            ,String.valueOf(mAppWidgetId));
    resultValue.setData(data);
    resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
    Log.d(MY_DEBUG, "Configurator.Creating widget with id = " + mAppWidgetId);
    setResult(RESULT_OK, resultValue);
    finish();
}

我已经为此工作了两天,我确实希望有人能指出我的方法的错误。虚拟电子啤酒等待着能够解决这个问题的人:)


我试图查看您的代码,但没有找到为什么它对您不起作用,除了我在您的代码中发现了一些其他错误。无论如何,我已经构建了一个快速工作的代码,您可以尝试一下。

WidgetProvider.java

package com.example.helloclickablewidget;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.Toast;

public class WidgetProvider extends AppWidgetProvider {

    public static final String WIDGET_CLICKED = "com.example.helloclickablewidget.WIDGET_CLICKED";

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action != null && action.equals(WIDGET_CLICKED)) {
            int widgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
            Toast.makeText(context, "Widget clicked. ID: " + widgetId, Toast.LENGTH_LONG).show();
        } else {
            super.onReceive(context, intent);
        }
    }

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

        // 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 intent = new Intent(context, WidgetProvider.class);
            intent.setAction(WIDGET_CLICKED);
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, appWidgetId, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            // Get the layout for the App Widget and attach an on-click listener
            // to the button
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
            views.setOnClickPendingIntent(R.id.text, pendingIntent);
            // Tell the AppWidgetManager to perform an update on the current app widget
            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }

}

布局/widget.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="@string/app_name" >
</TextView>

xml/小部件.xml

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

AndroidManifest.xml

<manifest package="com.example.helloclickablewidget"
    android:versionCode="1"
    android:versionName="1.0" xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <receiver android:name="WidgetProvider" android:exported="false">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
                <action android:name="com.example.helloclickablewidget.WIDGET_CLICKED"/>
            </intent-filter>
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget" />
        </receiver>
    </application>

</manifest>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android appWidget 多个实例 的相关文章

  • 如何在 Flutter 中为 Button 添加渐变?

    有没有办法改变ElevatedButton背景颜色渐变 如果没有一些小瑕疵或问题 例如缺少涟漪效应 不需要的边框 不尊重主题的内容 上述所有解决方案都无法真正发挥作用minWidth对于按钮 The 下面的解决方案没有上述问题 关键部分是使
  • GCM 通知的自定义 UI

    In GCM Docs http developer android com google gcm gcm html其给定 它不提供任何内置用户界面或其他处理 消息数据 GCM 只是将收到的原始消息数据直接传递给 Android 应用程序
  • Android 的 GCM 推送通知[关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 最近 我尝试学习 GCM 并制作一个测试应用程序 该应用程序将通过 androids 官方网站获取 an
  • 关于android Sqlite在多进程情况下的安全性

    在我的应用程序中 存在多个进程 并且在每个进程中 我需要访问同一个SQLite数据库 当然 这意味着超过2个线程 所以我不仅担心SQLite的线程安全性 还担心SQLite的线程安全性 还有过程安全 这种情况的一种解决方案是使用内容提供者
  • Android 视图展开动画

    我正在尝试编辑这些来源 https github com gabrielemariotti androiddev tree master AnimationTest创建一个适用于我所有视图的简单函数 Override public void
  • 以编程方式启用/禁用广播接收器

    我们有一个可以扫描蓝牙设备的应用程序 负责扫描的代码应仅在启用蓝牙时运行 此外 我们希望随时禁用 启用此功能 我们选择实现一个注册BluetoothAdapter ACTION STATE CHANGED广播的BroadcastReceiv
  • 卡片视图工具栏

    我有一个包含 CardView 的 RecyclerView 我想向每个 CardView 添加一个工具栏 其外观和行为类似于主工具栏 图标 标题 按钮 按钮 菜单 我从这里看到了 http blog grafixartist com cr
  • API 31 上是否有官方方法来提供文件关联,可能使用 pathSuffix/pathAdvancedPattern?

    背景 现代桌面操作系统上的一个众所周知的功能是能够处理文件 允许用户从文件管理器和其他应用程序中打开它们 作为 文件关联 配置 问题 到目前为止 对于用户和开发人员来说 在 Android 上设置文件类型关联并不是一件很方便的事情 在 An
  • 如何从另一个应用程序向一个应用程序添加视图

    我的应用程序叫做我的好应用 MyNiceApp 主要只是一个加载视图的核心coreView在主活动中onCreate coreView由用户根据需要下载的其他插件的视图填充 我定义了核心视图上的各个区域 这些区域可以通过 MyNiceApp
  • 无法解析配置“:app:debugRuntimeClasspath”的所有文件。问题

    我的 android studio 遇到了下一个问题 导致 org gradle api internal artifacts ivyservice DefaultLenientConfiguration ArtifactResolveEx
  • Droid 3 上的列表视图背景为灰色

    我有一个带有自定义背景的列表框 它在黑色背景的两侧显示一条细白线 在我所有的测试手机 Galaxy Captivate Vibrant Nexus 1 G Tablet Archos 32 Droid 上运行良好 我刚买了一台 Droid
  • 如何使用RecyclerView.State保存RecyclerView滚动位置?

    我有一个关于 Android 的问题RecyclerView State http developer android com reference android support v7 widget RecyclerView State h
  • Android:每秒更新蓝牙 RSSI

    我试图每秒显示蓝牙信号强度 RSSI Timer 来自检测到的设备 但我无法调用onRecive 多次因为接收器生命周期 http developer android com reference android content Broadc
  • SDK 管理器中缺少 Google Play 服务

    我想在我的应用程序中使用 Google 地图 我想在 SDK 管理器中安装 Google Play 服务 但是当我转到 SDK 管理器时 我没有看到 Google Play 服务 为什么 我该如何安装这个 我可以独立于 SDK Manage
  • Android 连接有时会被拒绝(并非所有时候)

    我编写了一个 WiFi Direct 代码连接并在它们之间创建了一个连接 然后我创建了一个ServerSocket在第一面和一个Socket在客户端并开始在它们之间发送数据 第一次启动应用程序时它工作成功 但是当我关闭应用程序并再次启动它时
  • 如何在Webview中保存用户名和密码

    目前 我还在学习Android开发的过程中 所以如果我的这个问题对你来说不太容易理解 请原谅 我创建了一个 Android 应用程序 它使用 RecyclerView 显示一组列表 当用户单击列表中的每个名称时 它会将它们重定向到一组不同的
  • Activity 上的 OnTouchListener 从不调用

    我使用了这段代码 但是当我在运行时单击活动时 它永远不会在 OnTouch 方法中命中 有人可以指导我我做错了什么吗 我需要设置此活动的内容视图吗 实际上我想要用户在执行过程中触摸的活动的坐标 public class TouchTestA
  • 如何为背景图像添加内边距

    我有一个LinearLayout其中有一个背景图像 一个 9 修补的 png 文件 如何向左和右添加填充 以使背景图像不占据整个宽度 我努力了android paddingLeft and android paddingRight 但这并没
  • Android VideoView 中纵向视频方向错误

    我在 Android 设备上以肖像方向拍摄新视频 如下所示 Intent intent new Intent android provider MediaStore ACTION VIDEO CAPTURE startActivityFor
  • Android 使用非公历

    我正在创建一个DatePickerDialogFragment用户将在其中选择出生日期 我想确保我可以处理非公历日期 我无法更改在我的设备上使用的日历类型 Android 是否允许用户切换日历类型 如果是的话 步骤是什么 到目前为止我还没有

随机推荐

  • 按月和日分组的事件直方图

    我正在尝试根据多年但按月和日分组的一组数据制作每个事件发生次数的直方图 或其他图 基本上 我想要从 3 月 1 日开始的一年长的 x 轴 显示每个日期出现的次数 并根据分类值对这些日期进行着色 以下是数据集中前 20 名的条目 goose
  • ValueError:参数 scipy rv_continuous 中的域错误

    我试图使用 scipy stats rv continuous 对给定概率密度函数 pdf 的随机变量进行采样 class Distribution stats rv continuous def pdf self x a c return
  • 在 Stata 的 do-file 中将命令分成几行

    我想运行keepStata 12 中 do 文件中的命令 keep a1 a2 a3 a4 a5 b1 b2 b3 b4 b5 c1 c2 c3 c4 我想要的是执行以下操作 keep a1 a2 a3 a4 a5 b1 b2 b3 b4
  • C++ 和 OpenCV:白色像素聚类算法

    我有一个二值图像 黑色和白色像素 我想根据彼此之间的距离将白色像素聚类成组 对象 并检索每个聚类的质心 这是我必须处理的示例图像 框架为紫色 我想检查聚类方法是否可以提供我正在寻找的结果 这意味着我试图避免在知道它值得之前自己实现算法 Op
  • 带有我的应用程序图标的安全中心符号盾

    我开发了一个需要管理员权限才能执行的应用程序 在 Windows 7 上运行应用程序 用户始终必须以 以管理员身份运行 启动应用程序 否则我的应用程序会提示用户 您没有管理权限等 这是可以理解的 因为 Windows 7 中有 UAC 要摆
  • 设置模拟位置时 GPS 提供商未知错误?

    我正在尝试设置我的模拟位置 但是 我收到以下错误 提供商 gps 未知 并且不确定出了什么问题 我已经获得了在manifest xml 中声明的所有权限以及所有参数 模拟定位法 Initiates the method to set the
  • 翻转 OpenGL 纹理

    当我正常从图像加载纹理时 由于 OpenGL 的坐标系统 它们是颠倒的 翻转它们的最佳方法是什么 glScalef 1 0f 1 0f 1 0f 反向映射纹理的 y 坐标 手动垂直翻转图像文件 在 Photoshop 中 加载后以编程方式翻
  • 检查元素在溢出滚动 DIV 中是否完全可见[关闭]

    这个问题不太可能对任何未来的访客有帮助 它只与一个较小的地理区域 一个特定的时间点或一个非常狭窄的情况相关 通常不适用于全世界的互联网受众 为了帮助使这个问题更广泛地适用 访问帮助中心 help reopen questions 我已经为元
  • 简单的 schdule Nodejs 脚本在连接到远程数据库时插入记录两次

    我有一个时间表nodejs脚本 基本上 它有时间表和命令表 调度表有很多命令行 Nodejs 脚本每 5 秒检查一次调度表 如果预定时间与当前时间匹配 我将命令行 从计划表 插入到命令表中 错误是 我在笔记本电脑上运行脚本并进行测试数据库的
  • iOS:使用全屏图像构建幻灯片

    我想构建一个幻灯片 您可以在其中滑动图像 以全屏模式显示 我打算使用 UIViews 并添加手势识别器 但我想知道是否有一些已经完成的事情我可以重用 或者任何提示 我希望获得与您在 iPad 上滑动打开的应用程序时相同的效果 您可以滑动它们
  • 如何在 Python 中使用 OpenCV 跟踪运动?

    我可以使用我的网络摄像头获取帧OpenCV http opencv willowgarage com wiki 在Python中 camshift 示例接近我想要的 但我不希望人为干预来定义对象 我想获得在几帧的过程中变化的总像素的中心点
  • VS2017 在源代码中出现大量“无法解析符号”错误,但一切都构建完成

    我在 VB Net 源代码文件中收到大量 无法解析符号 错误 解决方案中的所有内容都可以毫无问题地构建 Peek Definition 和 Goto Implement 工作正常 到目前为止 我已经尝试过以下操作 进行过构建吗 清理 关闭
  • 理解 find 中转义的括号

    我已经拼凑了下面的内容 它似乎可以工作 但 空 可能是个例外 我正在学习的一件事 随着我的学习 是 仅仅因为某些东西有效 并不意味着它是正确的或正确形成的 我的问题是如何确定查找中哪些需要括号 哪些不需要命令 在 OS X 中 and 是
  • Python类装饰器扩展类导致递归

    我正在覆盖 a 的保存方法ModelForm我不知道为什么它会导致递归 parsleyfy class AccountForm forms ModelForm def save self args kwargs some other cod
  • matplotlib 中的散点图

    这是我的第一个 matplotlib 程序 很抱歉我的无知 我有两个字符串数组 说 A test1 test2 and B test3 test4 如果之间存在任何相关性A and B元素 它们的 corr 值将被设置为1 test1 te
  • ClearCase 的“MVFS 文件系统”的本质是什么?

    Clearcase 服务器中的 MVFS 有何作用 MVFS 多版本文件系统 并不是 创建 文件系统 而是让您访问一个文件系统 M 在 Windows 上 或 view 在 Unix 上 是一个安装点 允许浏览您安装的任何 Vob Clea
  • 更改 xml 节点中的值时出错

    我需要更改 xml 的多个值 但是当我运行 setText 行时 它显示 java lang NullPointerException 错误 我不明白为什么
  • 如何在MySQL中找到当前用户连接的IP地址?

    在您回答 use current user 这在很多情况下都有效 或 use user 这实际上不起作用 之前 请阅读以下内容 我正在尝试在表上创建一个视图 该视图限制用户对表中某些行的访问 并由用户连接的 IP 地址控制 我的第一次尝试是
  • React Native 如何获取“getPackageManager()”

    你知道如何在react native中访问 getPackageManager 对于java 吗 我到处搜索 但只发现 getPackageManager 的一些错误 我需要它来知道我的应用程序是否已从 Play 商店或通过其他方法下载 我
  • Android appWidget 多个实例

    这个问题几乎是重复的Android 多个appWidgets播放不同的声音 https stackoverflow com questions 4225197 android multiple appwidgets playing dife