具有切换功能的小部件

A widget with toggle functionality

我正在尝试创建一个具有一个 ImageView 的小部件。 我希望它像切换按钮一样工作。单击一次,它应该做一件事,再单击一次做另一件事,然后重复。

我偶然发现了很多关于小部件的教程和很多关于 Whosebug 的帖子,但到目前为止都没有成功。我想做类似的事情:第一次点击时,启动一个进程,更改 ImageView 并等待另一次点击停止。我见过这样的小部件

到目前为止我的代码:

private Boolean clicked = false;

...

// Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);

        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_camera);
        views.setImageViewBitmap(R.id.imageView, bitmap);

        Intent intent1 = new Intent(context, MainActivity.class);
        Intent intent2 = new Intent(context, MainActivity2.class);

        PendingIntent firstPIntent = PendingIntent.getActivity(context, 0, intent1, 0);
        PendingIntent secondPIntent = PendingIntent.getActivity(context, 0, intent2, 0);

        if(!clicked)
        {
            views.setOnClickPendingIntent(R.id.imageView, firstPIntent);
            clicked = true;
            Log.e("WIdGEt", "ONE");
        }
        else if(clicked)
        {
            views.setOnClickPendingIntent(R.id.imageView, secondPIntent);
            clicked = false;
            Log.e("WIdGEt", "TWO");
        }

请帮我写一些代码(或伪代码)。谢谢!

It just runs the firstPIntent.

那是因为 clicked 始终是 false,因为 clicked(显然)是您的 AppWidgetProvider 中的一个字段,并且只是一个 AppWidgetProvider 实例活一次更新。

您需要调整您的逻辑来跟踪您在文件、数据库或 SharedPreferences 中的 "clicked" 状态 — 这不仅会在 AppWidgetProvider 实例消失后持续,但是在你的进程终止后会出现一些东西。