小部件setOnClickPendingIntent

ard*_*evd 4 android

所以,我很难弄清楚如何让我的应用程序小部件以我想要的方式工作,或者甚至可能.

Widget有一个ImageView,我分配setOnClickPendingIntent给它.但是,我想要完成的只是实例化一个类,并在用户点击ImageViewapp小部件时调用该类中的方法.但是,PendingIntent除了启动活动之外,我怎样才能做其他事情呢?不确定这是否有意义,但我真的很感激帮助.

           // Create an Intent to launch MainActivity
            Intent intent = new Intent(context, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
                    /**
                    /* However, I want to simply do something like this
                    /* MyClass mc = new MyClass(context);
                    /* mc.toggleEnable();
                    */

            // 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_layout);
            views.setOnClickPendingIntent(R.id.imageViewWidgetToggle, pendingIntent);
Run Code Online (Sandbox Code Playgroud)

2De*_*Dee 15

您可以使用PendingIntent.getBroadcastAppWidgetProvider课堂上收到的内容:

Intent intent = new Intent(context, YourAppWidgetProvider.class);
intent.setAction("use_custom_class");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.imageViewWidgetToggle, pendingIntent);
Run Code Online (Sandbox Code Playgroud)

然后在AppWidgetProvider:

@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);

    String action = intent.getAction();
    String actionName = "use_custom_class";

    if (actionName.equals(action)) {
        MyClass mc = new MyClass(context);
        mc.toggleEnable();
    }
}
Run Code Online (Sandbox Code Playgroud)

有关要使用的标志的详细信息,请查看有关PendingIntent的文档.我希望我能正确理解你的问题,我的答案对你有意义:)如果没有,请不要犹豫,让我知道......