android - 请帮助非常简单的 android 小部件按钮单击。变得非常沮丧。 :(

标签 android android-widget

我已经遍历了我能找到的每一个例子,并且我已经阅读了谷歌的官方文档。我想要做的就是通过单击小部件上的按钮创建 toast 通知。

我可以让小部件(和按钮)出现,但我无法启动 intent。我已经看到了几个例子,这些例子展示了以不同的方式做这件事,但我就是无法让它发挥作用。很长一段时间以来,我都没有对编码感到如此无助,我开始觉得自己很笨。

这是我目前所拥有的:

public class simpleclick extends AppWidgetProvider {
    /** Called when the activity is first created. */

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

        Toast.makeText(context, "doing on update", Toast.LENGTH_SHORT).show();

        for (int i=0; i<N; i++) {

            int appWidgetId = appWidgetIds[i];

            Intent intent = new Intent(context, simpleclick.class);
            intent.setAction("ham");
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main);
            views.setOnClickPendingIntent(R.id.Timm, pendingIntent);

            appWidgetManager.updateAppWidget(appWidgetId, views);

        }

    }

    //@Override
    public void onReceive(Context context, Intent intent) {
     // TODO Auto-generated method stub

     Toast.makeText(context, "action is: " + intent.getAction(), Toast.LENGTH_SHORT).show();

     super.onReceive(context, intent);

    }

}

我的 list :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.tblabs.simpleclick"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <receiver android:name="simpleclick">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
        </intent-filter>
        <meta-data android:name="android.appwidget.provider" 
            android:resource="@xml/simpleclick" />
        </receiver>

    </application>
    <uses-sdk android:minSdkVersion="5" />

</manifest> 

我会很感激一些帮助!

谢谢, 温蒂

最佳答案

正如 bigstones 所写,您需要使用广播。 示例代码:

protected PendingIntent getPendingSelfIntent(Context context, String action) {
    Intent intent = new Intent(context, getClass());
    intent.setAction(action);
    return PendingIntent.getBroadcast(context, 0, intent, 0);
}

views.setOnClickPendingIntent(R.id.Timm, getPendingSelfIntent(context,
                              "ham"));

关于android - 请帮助非常简单的 android 小部件按钮单击。变得非常沮丧。 :(,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4963865/

相关文章:

android - 通过蓝牙将多台设备连接到一台设备

java - 使用 Gradle 在 Android 项目中使用 JaCoCo

android - 如何获取 android.app.UiAutomation 的实例

android - Android Widget 中的可滚动 TextView

java - setTextViewText 不更新小部件

android - 如何在单个 Activity 中显示第一个 fragment 的第二个 fragment

android - 如何检查设备在 Android Oreo API 26 及更高版本上的存储空间是否不足

android - 从暂停恢复时全屏 TabActivity 出现问题

Android 列表小部件和项目点击不起作用

android - 如何在 Linux 上编译 aFreeRDP